feat: add first version of workbench, increase token limit, improve system prompt

This commit is contained in:
Dominic Elm 2024-07-17 20:54:46 +02:00
parent b4420a22bb
commit 621b8804d8
50 changed files with 2979 additions and 423 deletions

View File

@ -9,6 +9,8 @@ export default [
{ {
rules: { rules: {
'@blitz/catch-error-name': 'off', '@blitz/catch-error-name': 'off',
'@typescript-eslint/no-this-alias': 'off',
'@typescript-eslint/no-empty-object-type': 'off',
}, },
}, },
{ {

View File

@ -1,34 +1,176 @@
import { useStore } from '@nanostores/react'; import { useStore } from '@nanostores/react';
import { workspaceStore } from '~/lib/stores/workspace'; import { AnimatePresence, motion } from 'framer-motion';
import { computed } from 'nanostores';
import { useState } from 'react';
import { createHighlighter, type BundledLanguage, type BundledTheme, type HighlighterGeneric } from 'shiki';
import { getArtifactKey, workbenchStore, type ActionState } from '../../lib/stores/workbench';
import { classNames } from '../../utils/classNames';
import { cubicEasingFn } from '../../utils/easings';
import { IconButton } from '../ui/IconButton';
const highlighterOptions = {
langs: ['shell'],
themes: ['light-plus', 'dark-plus'],
};
const shellHighlighter: HighlighterGeneric<BundledLanguage, BundledTheme> =
import.meta.hot?.data.shellHighlighter ?? (await createHighlighter(highlighterOptions));
if (import.meta.hot) {
import.meta.hot.data.shellHighlighter = shellHighlighter;
}
interface ArtifactProps { interface ArtifactProps {
artifactId: string;
messageId: string; messageId: string;
} }
export function Artifact({ messageId }: ArtifactProps) { export function Artifact({ artifactId, messageId }: ArtifactProps) {
const artifacts = useStore(workspaceStore.artifacts); const [showActions, setShowActions] = useState(false);
const artifact = artifacts[messageId]; const artifacts = useStore(workbenchStore.artifacts);
const artifact = artifacts[getArtifactKey(artifactId, messageId)];
const actions = useStore(
computed(artifact.actions, (actions) => {
return Object.values(actions);
}),
);
return ( return (
<div className="flex flex-col overflow-hidden border rounded-lg w-full">
<div className="flex">
<button <button
className="flex border rounded-lg overflow-hidden items-stretch bg-gray-50/25 w-full" className="flex items-stretch bg-gray-50/25 w-full overflow-hidden"
onClick={() => { onClick={() => {
const showWorkspace = workspaceStore.showWorkspace.get(); const showWorkbench = workbenchStore.showWorkbench.get();
workspaceStore.showWorkspace.set(!showWorkspace); workbenchStore.showWorkbench.set(!showWorkbench);
}} }}
> >
<div className="border-r flex items-center px-6 bg-gray-100/50"> <div className="flex items-center px-6 bg-gray-100/50">
{!artifact?.closed ? ( {!artifact?.closed ? (
<div className="i-svg-spinners:90-ring-with-bg scale-130"></div> <div className="i-svg-spinners:90-ring-with-bg scale-130"></div>
) : ( ) : (
<div className="i-ph:code-bold scale-130 text-gray-600"></div> <div className="i-ph:code-bold scale-130 text-gray-600"></div>
)} )}
</div> </div>
<div className="flex flex-col items-center px-4 p-2.5"> <div className="px-4 p-3 w-full text-left">
<div className="text-left w-full">{artifact?.title}</div> <div className="w-full">{artifact?.title}</div>
<small className="w-full text-left">Click to open code</small> <small className="inline-block w-full w-full">Click to open Workbench</small>
</div> </div>
</button> </button>
<AnimatePresence>
{actions.length && (
<motion.button
initial={{ width: 0 }}
animate={{ width: 'auto' }}
exit={{ width: 0 }}
transition={{ duration: 0.15, ease: cubicEasingFn }}
className="hover:bg-gray-200"
onClick={() => setShowActions(!showActions)}
>
<div className="p-4">
<div className={showActions ? 'i-ph:caret-up-bold' : 'i-ph:caret-down-bold'}></div>
</div>
</motion.button>
)}
</AnimatePresence>
</div>
<AnimatePresence>
{showActions && actions.length > 0 && (
<motion.div
className="actions"
initial={{ height: 0 }}
animate={{ height: 'auto' }}
exit={{ height: '0px' }}
transition={{ duration: 0.15 }}
>
<div className="p-4 text-left border-t">
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
<h4 className="font-semibold mb-2">Actions</h4>
<ul className="list-none space-y-2.5">
{actions.map((action, index) => {
const { status, type, content, abort } = action;
return (
<li key={index} className={classNames(getTextColor(action.status))}>
<div className="flex items-center gap-1.5">
<div className="text-lg">
{status === 'running' ? (
<div className="i-svg-spinners:90-ring-with-bg"></div>
) : status === 'pending' ? (
<div className="i-ph:circle-duotone"></div>
) : status === 'complete' ? (
<div className="i-ph:check-circle-duotone"></div>
) : status === 'failed' || status === 'aborted' ? (
<div className="i-ph:x-circle-duotone"></div>
) : null}
</div>
{type === 'file' ? (
<div>
Create <code className="bg-gray-100 text-gray-700">{action.filePath}</code>
</div>
) : type === 'shell' ? (
<div className="flex items-center w-full min-h-[28px]">
<span className="flex-1">Run command</span>
{abort !== undefined && status === 'running' && (
<IconButton icon="i-ph:x-circle" size="xl" onClick={() => abort()} />
)}
</div>
) : null}
</div>
{type === 'shell' && <ShellCodeBlock classsName="mt-1" code={content} />}
</li>
);
})}
</ul>
</motion.div>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
function getTextColor(status: ActionState['status']) {
switch (status) {
case 'pending': {
return 'text-gray-500';
}
case 'running': {
return 'text-gray-1000';
}
case 'complete': {
return 'text-positive-600';
}
case 'aborted': {
return 'text-gray-600';
}
case 'failed': {
return 'text-negative-600';
}
default: {
return undefined;
}
}
}
interface ShellCodeBlockProps {
classsName?: string;
code: string;
}
function ShellCodeBlock({ classsName, code }: ShellCodeBlockProps) {
return (
<div
className={classNames('text-xs', classsName)}
dangerouslySetInnerHTML={{ __html: shellHighlighter.codeToHtml(code, { lang: 'shell', theme: 'dark-plus' }) }}
></div>
); );
} }

View File

@ -2,16 +2,14 @@ import type { Message } from 'ai';
import type { LegacyRef } from 'react'; import type { LegacyRef } from 'react';
import React from 'react'; import React from 'react';
import { ClientOnly } from 'remix-utils/client-only'; import { ClientOnly } from 'remix-utils/client-only';
import { IconButton } from '~/components/ui/IconButton'; import { classNames } from '../../utils/classNames';
import { Workspace } from '~/components/workspace/Workspace.client'; import { IconButton } from '../ui/IconButton';
import { classNames } from '~/utils/classNames'; import { Workbench } from '../workbench/Workbench.client';
import { Messages } from './Messages.client'; import { Messages } from './Messages.client';
import { SendButton } from './SendButton.client'; import { SendButton } from './SendButton.client';
interface BaseChatProps { interface BaseChatProps {
textareaRef?: LegacyRef<HTMLTextAreaElement> | undefined; textareaRef?: LegacyRef<HTMLTextAreaElement> | undefined;
messagesSlot?: React.ReactNode;
workspaceSlot?: React.ReactNode;
chatStarted?: boolean; chatStarted?: boolean;
isStreaming?: boolean; isStreaming?: boolean;
messages?: Message[]; messages?: Message[];
@ -80,14 +78,17 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
</ClientOnly> </ClientOnly>
<div <div
className={classNames('relative w-full max-w-3xl md:mx-auto z-2', { className={classNames('relative w-full max-w-3xl md:mx-auto z-2', {
'sticky bottom-0 bg-bolt-elements-app-backgroundColor': chatStarted, 'sticky bottom-0': chatStarted,
})} })}
> >
<div <div
className={classNames('shadow-sm mb-6 border border-gray-200 bg-white rounded-lg overflow-hidden')} className={classNames(
'shadow-sm border border-gray-200 bg-white/85 backdrop-filter backdrop-blur-[8px] rounded-lg overflow-hidden',
)}
> >
<textarea <textarea
ref={textareaRef} ref={textareaRef}
className={`w-full pl-4 pt-4 pr-16 focus:outline-none resize-none bg-transparent`}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.key === 'Enter') { if (event.key === 'Enter') {
if (event.shiftKey) { if (event.shiftKey) {
@ -103,7 +104,6 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
onChange={(event) => { onChange={(event) => {
handleInputChange?.(event); handleInputChange?.(event);
}} }}
className={`w-full pl-4 pt-4 pr-16 focus:outline-none resize-none`}
style={{ style={{
minHeight: TEXTAREA_MIN_HEIGHT, minHeight: TEXTAREA_MIN_HEIGHT,
maxHeight: TEXTAREA_MAX_HEIGHT, maxHeight: TEXTAREA_MAX_HEIGHT,
@ -146,10 +146,11 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
) : null} ) : null}
</div> </div>
</div> </div>
<div className="bg-white pb-6">{/* Ghost Element */}</div>
</div> </div>
</div> </div>
</div> </div>
<ClientOnly>{() => <Workspace chatStarted={chatStarted} />}</ClientOnly> <ClientOnly>{() => <Workbench chatStarted={chatStarted} />}</ClientOnly>
</div> </div>
</div> </div>
); );

View File

@ -1,9 +1,9 @@
import { useChat } from 'ai/react'; import { useChat } from 'ai/react';
import { useAnimate } from 'framer-motion'; import { useAnimate } from 'framer-motion';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useMessageParser, usePromptEnhancer } from '~/lib/hooks'; import { useMessageParser, usePromptEnhancer } from '../../lib/hooks';
import { cubicEasingFn } from '~/utils/easings'; import { cubicEasingFn } from '../../utils/easings';
import { createScopedLogger } from '~/utils/logger'; import { createScopedLogger } from '../../utils/logger';
import { BaseChat } from './BaseChat'; import { BaseChat } from './BaseChat';
const logger = createScopedLogger('Chat'); const logger = createScopedLogger('Chat');

View File

@ -1,25 +1,21 @@
import { memo, useEffect, useState } from 'react'; import { memo, useEffect, useState } from 'react';
import { import { bundledLanguages, codeToHtml, isSpecialLang, type BundledLanguage, type SpecialLanguage } from 'shiki';
bundledLanguages, import { classNames } from '../../utils/classNames';
codeToHtml, import { createScopedLogger } from '../../utils/logger';
isSpecialLang,
type BundledLanguage,
type BundledTheme,
type SpecialLanguage,
} from 'shiki';
import { classNames } from '~/utils/classNames';
import { createScopedLogger } from '~/utils/logger';
import styles from './CodeBlock.module.scss'; import styles from './CodeBlock.module.scss';
const logger = createScopedLogger('CodeBlock'); const logger = createScopedLogger('CodeBlock');
interface CodeBlockProps { interface CodeBlockProps {
className?: string;
code: string; code: string;
language?: BundledLanguage; language?: BundledLanguage | SpecialLanguage;
theme?: BundledTheme | SpecialLanguage; theme?: 'light-plus' | 'dark-plus';
disableCopy?: boolean;
} }
export const CodeBlock = memo(({ code, language, theme }: CodeBlockProps) => { export const CodeBlock = memo(
({ className, code, language = 'plaintext', theme = 'dark-plus', disableCopy = false }: CodeBlockProps) => {
const [html, setHTML] = useState<string | undefined>(undefined); const [html, setHTML] = useState<string | undefined>(undefined);
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
@ -45,14 +41,14 @@ export const CodeBlock = memo(({ code, language, theme }: CodeBlockProps) => {
logger.trace(`Language = ${language}`); logger.trace(`Language = ${language}`);
const processCode = async () => { const processCode = async () => {
setHTML(await codeToHtml(code, { lang: language ?? 'plaintext', theme: theme ?? 'dark-plus' })); setHTML(await codeToHtml(code, { lang: language, theme }));
}; };
processCode(); processCode();
}, [code]); }, [code]);
return ( return (
<div className="relative group"> <div className={classNames('relative group text-left', className)}>
<div <div
className={classNames( className={classNames(
styles.CopyButtonContainer, styles.CopyButtonContainer,
@ -62,6 +58,7 @@ export const CodeBlock = memo(({ code, language, theme }: CodeBlockProps) => {
}, },
)} )}
> >
{!disableCopy && (
<button <button
className={classNames( className={classNames(
'flex items-center bg-transparent p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300', 'flex items-center bg-transparent p-[6px] justify-center before:bg-white before:rounded-l-md before:text-gray-500 before:border-r before:border-gray-300',
@ -75,8 +72,10 @@ export const CodeBlock = memo(({ code, language, theme }: CodeBlockProps) => {
> >
<div className="i-ph:clipboard-text-duotone"></div> <div className="i-ph:clipboard-text-duotone"></div>
</button> </button>
)}
</div> </div>
<div dangerouslySetInnerHTML={{ __html: html ?? '' }}></div> <div dangerouslySetInnerHTML={{ __html: html ?? '' }}></div>
</div> </div>
); );
}); },
);

View File

@ -6,6 +6,12 @@ $color-link: #3498db;
$color-code-bg: #f8f8f8; $color-code-bg: #f8f8f8;
$color-blockquote-border: #dfe2e5; $color-blockquote-border: #dfe2e5;
@mixin not-inside-actions {
&:not(:has(:global(.actions)), :global(.actions *)) {
@content;
}
}
.MarkdownContent { .MarkdownContent {
line-height: 1.6; line-height: 1.6;
color: $color-text; color: $color-text;
@ -15,12 +21,14 @@ $color-blockquote-border: #dfe2e5;
} }
:is(h1, h2, h3, h4, h5, h6) { :is(h1, h2, h3, h4, h5, h6) {
@include not-inside-actions {
margin-top: 24px; margin-top: 24px;
margin-bottom: 16px; margin-bottom: 16px;
font-weight: 600; font-weight: 600;
line-height: 1.25; line-height: 1.25;
color: $color-heading; color: $color-heading;
} }
}
h1 { h1 {
font-size: 2em; font-size: 2em;
@ -68,9 +76,12 @@ $color-blockquote-border: #dfe2e5;
:not(pre) > code { :not(pre) > code {
font-family: $font-mono; font-family: $font-mono;
font-size: 14px; font-size: 14px;
background-color: $color-code-bg;
border-radius: 6px; border-radius: 6px;
padding: 0.2em 0.4em; padding: 0.2em 0.4em;
@include not-inside-actions {
background-color: $color-code-bg;
}
} }
pre { pre {
@ -83,6 +94,7 @@ $color-blockquote-border: #dfe2e5;
font-size: 14px; font-size: 14px;
background: transparent; background: transparent;
overflow-x: auto; overflow-x: auto;
min-width: 0;
} }
blockquote { blockquote {
@ -93,26 +105,36 @@ $color-blockquote-border: #dfe2e5;
} }
:is(ul, ol) { :is(ul, ol) {
@include not-inside-actions {
padding-left: 2em; padding-left: 2em;
margin-top: 0; margin-top: 0;
margin-bottom: 24px; margin-bottom: 24px;
} }
}
ul { ul {
@include not-inside-actions {
list-style-type: disc; list-style-type: disc;
} }
}
ol { ol {
@include not-inside-actions {
list-style-type: decimal; list-style-type: decimal;
} }
}
li + li { li {
@include not-inside-actions {
& + li {
margin-top: 8px; margin-top: 8px;
} }
li > *:not(:last-child) { > *:not(:last-child) {
margin-bottom: 16px; margin-bottom: 16px;
} }
}
}
img { img {
max-width: 100%; max-width: 100%;

View File

@ -1,10 +1,11 @@
import { memo, useMemo } from 'react'; import { memo, useMemo } from 'react';
import ReactMarkdown, { type Components } from 'react-markdown'; import ReactMarkdown, { type Components } from 'react-markdown';
import type { BundledLanguage } from 'shiki'; import type { BundledLanguage } from 'shiki';
import { createScopedLogger } from '~/utils/logger'; import { createScopedLogger } from '../../utils/logger';
import { rehypePlugins, remarkPlugins } from '~/utils/markdown'; import { rehypePlugins, remarkPlugins } from '../../utils/markdown';
import { Artifact } from './Artifact'; import { Artifact } from './Artifact';
import { CodeBlock } from './CodeBlock'; import { CodeBlock } from './CodeBlock';
import styles from './Markdown.module.scss'; import styles from './Markdown.module.scss';
const logger = createScopedLogger('MarkdownComponent'); const logger = createScopedLogger('MarkdownComponent');
@ -20,13 +21,18 @@ export const Markdown = memo(({ children }: MarkdownProps) => {
return { return {
div: ({ className, children, node, ...props }) => { div: ({ className, children, node, ...props }) => {
if (className?.includes('__boltArtifact__')) { if (className?.includes('__boltArtifact__')) {
const artifactId = node?.properties.dataArtifactId as string;
const messageId = node?.properties.dataMessageId as string; const messageId = node?.properties.dataMessageId as string;
if (!messageId) { if (!artifactId) {
logger.warn(`Invalud message id ${messageId}`); logger.debug(`Invalid artifact id ${messageId}`);
} }
return <Artifact messageId={messageId} />; if (!messageId) {
logger.debug(`Invalid message id ${messageId}`);
}
return <Artifact artifactId={artifactId} messageId={messageId} />;
} }
return ( return (

View File

@ -1,5 +1,5 @@
import type { Message } from 'ai'; import type { Message } from 'ai';
import { classNames } from '~/utils/classNames'; import { classNames } from '../../utils/classNames';
import { AssistantMessage } from './AssistantMessage'; import { AssistantMessage } from './AssistantMessage';
import { UserMessage } from './UserMessage'; import { UserMessage } from './UserMessage';
@ -50,9 +50,11 @@ export function Messages(props: MessagesProps) {
> >
<div className={isUserMessage ? 'i-ph:user-fill text-xl' : 'i-blitz:logo'}></div> <div className={isUserMessage ? 'i-ph:user-fill text-xl' : 'i-blitz:logo'}></div>
</div> </div>
<div className="grid grid-col-1 w-full">
{isUser ? <UserMessage content={content} /> : <AssistantMessage content={content} />} {isUser ? <UserMessage content={content} /> : <AssistantMessage content={content} />}
</div> </div>
</div> </div>
</div>
); );
}) })
: null} : null}

View File

@ -0,0 +1,7 @@
export function BinaryContent() {
return (
<div className="flex items-center justify-center absolute inset-0 z-10 text-sm bg-tk-elements-app-backgroundColor text-tk-elements-app-textColor">
File format cannot be displayed.
</div>
);
}

View File

@ -0,0 +1,339 @@
import { acceptCompletion, autocompletion, closeBrackets } from '@codemirror/autocomplete';
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
import { bracketMatching, foldGutter, indentOnInput, indentUnit } from '@codemirror/language';
import { searchKeymap } from '@codemirror/search';
import { Compartment, EditorSelection, EditorState, type Extension } from '@codemirror/state';
import {
EditorView,
drawSelection,
dropCursor,
highlightActiveLine,
highlightActiveLineGutter,
keymap,
lineNumbers,
scrollPastEnd,
} from '@codemirror/view';
import { useEffect, useRef, useState, type MutableRefObject } from 'react';
import type { Theme } from '../../../types/theme';
import { classNames } from '../../../utils/classNames';
import { debounce } from '../../../utils/debounce';
import { createScopedLogger } from '../../../utils/logger';
import { BinaryContent } from './BinaryContent';
import { getTheme, reconfigureTheme } from './cm-theme';
import { indentKeyBinding } from './indent';
import { getLanguage } from './languages';
const logger = createScopedLogger('CodeMirrorEditor');
export interface EditorDocument {
value: string | Uint8Array;
loading: boolean;
filePath: string;
scroll?: ScrollPosition;
}
export interface EditorSettings {
fontSize?: string;
tabSize?: number;
}
type TextEditorDocument = EditorDocument & {
value: string;
};
export interface ScrollPosition {
top: number;
left: number;
}
export interface EditorUpdate {
selection: EditorSelection;
content: string;
}
export type OnChangeCallback = (update: EditorUpdate) => void;
export type OnScrollCallback = (position: ScrollPosition) => void;
interface Props {
theme: Theme;
id?: unknown;
doc?: EditorDocument;
debounceChange?: number;
debounceScroll?: number;
autoFocusOnDocumentChange?: boolean;
onChange?: OnChangeCallback;
onScroll?: OnScrollCallback;
className?: string;
settings?: EditorSettings;
}
type EditorStates = Map<string, EditorState>;
export function CodeMirrorEditor({
id,
doc,
debounceScroll = 100,
debounceChange = 150,
autoFocusOnDocumentChange = false,
onScroll,
onChange,
theme,
settings,
className = '',
}: Props) {
const [language] = useState(new Compartment());
const [readOnly] = useState(new Compartment());
const containerRef = useRef<HTMLDivElement | null>(null);
const viewRef = useRef<EditorView>();
const themeRef = useRef<Theme>();
const docRef = useRef<EditorDocument>();
const editorStatesRef = useRef<EditorStates>();
const onScrollRef = useRef(onScroll);
const onChangeRef = useRef(onChange);
const isBinaryFile = doc?.value instanceof Uint8Array;
onScrollRef.current = onScroll;
onChangeRef.current = onChange;
docRef.current = doc;
themeRef.current = theme;
useEffect(() => {
const onUpdate = debounce((update: EditorUpdate) => {
onChangeRef.current?.(update);
}, debounceChange);
const view = new EditorView({
parent: containerRef.current!,
dispatchTransactions(transactions) {
const previousSelection = view.state.selection;
view.update(transactions);
const newSelection = view.state.selection;
const selectionChanged =
newSelection !== previousSelection &&
(newSelection === undefined || previousSelection === undefined || !newSelection.eq(previousSelection));
if (
docRef.current &&
!docRef.current.loading &&
(transactions.some((transaction) => transaction.docChanged) || selectionChanged)
) {
onUpdate({
selection: view.state.selection,
content: view.state.doc.toString(),
});
editorStatesRef.current!.set(docRef.current.filePath, view.state);
}
},
});
viewRef.current = view;
return () => {
viewRef.current?.destroy();
viewRef.current = undefined;
};
}, []);
useEffect(() => {
if (!viewRef.current) {
return;
}
viewRef.current.dispatch({
effects: [reconfigureTheme(theme)],
});
}, [theme]);
useEffect(() => {
editorStatesRef.current = new Map<string, EditorState>();
}, [id]);
useEffect(() => {
const editorStates = editorStatesRef.current!;
const view = viewRef.current!;
const theme = themeRef.current!;
if (!doc) {
const state = newEditorState('', theme, settings, onScrollRef, debounceScroll, [language.of([])]);
view.setState(state);
setNoDocument(view);
return;
}
if (doc.value instanceof Uint8Array) {
return;
}
if (doc.filePath === '') {
logger.warn('File path should not be empty');
}
let state = editorStates.get(doc.filePath);
if (!state) {
state = newEditorState(doc.value, theme, settings, onScrollRef, debounceScroll, [
language.of([]),
readOnly.of([EditorState.readOnly.of(doc.loading)]),
]);
editorStates.set(doc.filePath, state);
}
view.setState(state);
setEditorDocument(view, theme, language, readOnly, autoFocusOnDocumentChange, doc as TextEditorDocument);
}, [doc?.value, doc?.filePath, doc?.loading, autoFocusOnDocumentChange]);
return (
<div className={classNames('relative h-full', className)}>
{isBinaryFile && <BinaryContent />}
<div className="h-full overflow-hidden" ref={containerRef} />
</div>
);
}
export default CodeMirrorEditor;
CodeMirrorEditor.displayName = 'CodeMirrorEditor';
function newEditorState(
content: string,
theme: Theme,
settings: EditorSettings | undefined,
onScrollRef: MutableRefObject<OnScrollCallback | undefined>,
debounceScroll: number,
extensions: Extension[],
) {
return EditorState.create({
doc: content,
extensions: [
EditorView.domEventHandlers({
scroll: debounce((_event, view) => {
onScrollRef.current?.({ left: view.scrollDOM.scrollLeft, top: view.scrollDOM.scrollTop });
}, debounceScroll),
keydown: (event) => {
if (event.code === 'KeyS' && (event.ctrlKey || event.metaKey)) {
event.preventDefault();
}
},
}),
getTheme(theme, settings),
history(),
keymap.of([
...defaultKeymap,
...historyKeymap,
...searchKeymap,
{ key: 'Tab', run: acceptCompletion },
indentKeyBinding,
]),
indentUnit.of('\t'),
autocompletion({
closeOnBlur: false,
}),
closeBrackets(),
lineNumbers(),
scrollPastEnd(),
dropCursor(),
drawSelection(),
bracketMatching(),
EditorState.tabSize.of(settings?.tabSize ?? 2),
indentOnInput(),
highlightActiveLineGutter(),
highlightActiveLine(),
foldGutter({
markerDOM: (open) => {
const icon = document.createElement('div');
icon.className = `fold-icon ${open ? 'i-ph-caret-down-bold' : 'i-ph-caret-right-bold'}`;
return icon;
},
}),
...extensions,
],
});
}
function setNoDocument(view: EditorView) {
view.dispatch({
selection: { anchor: 0 },
changes: {
from: 0,
to: view.state.doc.length,
insert: '',
},
});
view.scrollDOM.scrollTo(0, 0);
}
function setEditorDocument(
view: EditorView,
theme: Theme,
language: Compartment,
readOnly: Compartment,
autoFocus: boolean,
doc: TextEditorDocument,
) {
if (doc.value !== view.state.doc.toString()) {
view.dispatch({
selection: { anchor: 0 },
changes: {
from: 0,
to: view.state.doc.length,
insert: doc.value,
},
});
}
view.dispatch({
effects: [readOnly.reconfigure([EditorState.readOnly.of(doc.loading)])],
});
getLanguage(doc.filePath).then((languageSupport) => {
if (!languageSupport) {
return;
}
view.dispatch({
effects: [language.reconfigure([languageSupport]), reconfigureTheme(theme)],
});
requestAnimationFrame(() => {
const currentLeft = view.scrollDOM.scrollLeft;
const currentTop = view.scrollDOM.scrollTop;
const newLeft = doc.scroll?.left ?? 0;
const newTop = doc.scroll?.top ?? 0;
const needsScrolling = currentLeft !== newLeft || currentTop !== newTop;
if (autoFocus) {
if (needsScrolling) {
// we have to wait until the scroll position was changed before we can set the focus
view.scrollDOM.addEventListener(
'scroll',
() => {
view.focus();
},
{ once: true },
);
} else {
// if the scroll position is still the same we can focus immediately
view.focus();
}
}
view.scrollDOM.scrollTo(newLeft, newTop);
});
});
}

View File

@ -0,0 +1,165 @@
import { defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { Compartment, type Extension } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import type { Theme } from '../../../types/theme.js';
import type { EditorSettings } from './CodeMirrorEditor.js';
import { vscodeDarkTheme } from './themes/vscode-dark.js';
import './styles.css';
export const darkTheme = EditorView.theme({}, { dark: true });
export const themeSelection = new Compartment();
export function getTheme(theme: Theme, settings: EditorSettings = {}): Extension {
return [
getEditorTheme(settings),
theme === 'dark' ? themeSelection.of([getDarkTheme()]) : themeSelection.of([getLightTheme()]),
];
}
export function reconfigureTheme(theme: Theme) {
return themeSelection.reconfigure(theme === 'dark' ? getDarkTheme() : getLightTheme());
}
function getEditorTheme(settings: EditorSettings) {
return EditorView.theme({
...(settings.fontSize && {
'&': {
fontSize: settings.fontSize,
},
}),
'&.cm-editor': {
height: '100%',
background: 'var(--cm-backgroundColor)',
color: 'var(--cm-textColor)',
},
'.cm-cursor': {
borderLeft: 'var(--cm-cursor-width) solid var(--cm-cursor-backgroundColor)',
},
'.cm-scroller': {
lineHeight: '1.5',
},
'.cm-line': {
padding: '0 0 0 4px',
},
'&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
backgroundColor: 'var(--cm-selection-backgroundColorFocused)',
opacity: 'var(--cm-selection-backgroundOpacityFocused, 0.3)',
},
'&:not(.cm-focused) > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
backgroundColor: 'var(--cm-selection-backgroundColorBlured)',
opacity: 'var(--cm-selection-backgroundOpacityBlured, 0.3)',
},
'&.cm-focused > .cm-scroller .cm-matchingBracket': {
backgroundColor: 'var(--cm-matching-bracket)',
},
'.cm-activeLine': {
background: 'var(--cm-activeLineBackgroundColor)',
},
'.cm-gutters': {
background: 'var(--cm-gutter-backgroundColor)',
borderRight: 0,
color: 'var(--cm-gutter-textColor)',
},
'.cm-gutter': {
'&.cm-lineNumbers': {
fontFamily: 'Roboto Mono, monospace',
fontSize: '13px',
minWidth: '28px',
},
'& .cm-activeLineGutter': {
background: 'transparent',
color: 'var(--cm-gutter-activeLineTextColor)',
},
'&.cm-foldGutter .cm-gutterElement > .fold-icon': {
cursor: 'pointer',
color: 'var(--cm-foldGutter-textColor)',
transform: 'translateY(2px)',
'&:hover': {
color: 'var(--cm-foldGutter-textColorHover)',
},
},
},
'.cm-foldGutter .cm-gutterElement': {
padding: '0 4px',
},
'.cm-tooltip-autocomplete > ul > li': {
minHeight: '18px',
},
'.cm-panel.cm-search label': {
marginLeft: '2px',
},
'.cm-panel.cm-search input[type=checkbox]': {
position: 'relative',
transform: 'translateY(2px)',
marginRight: '4px',
},
'.cm-panels': {
borderColor: 'var(--cm-panels-borderColor)',
},
'.cm-panel.cm-search': {
background: 'var(--cm-search-backgroundColor)',
color: 'var(--cm-search-textColor)',
padding: '6px 8px',
},
'.cm-search .cm-button': {
background: 'var(--cm-search-button-backgroundColor)',
borderColor: 'var(--cm-search-button-borderColor)',
color: 'var(--cm-search-button-textColor)',
borderRadius: '4px',
'&:hover': {
color: 'var(--cm-search-button-textColorHover)',
},
'&:focus-visible': {
outline: 'none',
borderColor: 'var(--cm-search-button-borderColorFocused)',
},
'&:hover:not(:focus-visible)': {
background: 'var(--cm-search-button-backgroundColorHover)',
borderColor: 'var(--cm-search-button-borderColorHover)',
},
'&:hover:focus-visible': {
background: 'var(--cm-search-button-backgroundColorHover)',
borderColor: 'var(--cm-search-button-borderColorFocused)',
},
},
'.cm-panel.cm-search [name=close]': {
top: '6px',
right: '6px',
padding: '0 6px',
backgroundColor: 'var(--cm-search-closeButton-backgroundColor)',
color: 'var(--cm-search-closeButton-textColor)',
'&:hover': {
'border-radius': '6px',
color: 'var(--cm-search-closeButton-textColorHover)',
backgroundColor: 'var(--cm-search-closeButton-backgroundColorHover)',
},
},
'.cm-search input': {
background: 'var(--cm-search-input-backgroundColor)',
borderColor: 'var(--cm-search-input-borderColor)',
outline: 'none',
borderRadius: '4px',
'&:focus-visible': {
borderColor: 'var(--cm-search-input-borderColorFocused)',
},
},
'.cm-tooltip': {
background: 'var(--cm-tooltip-backgroundColor)',
borderColor: 'var(--cm-tooltip-borderColor)',
color: 'var(--cm-tooltip-textColor)',
},
'.cm-tooltip.cm-tooltip-autocomplete ul li[aria-selected]': {
background: 'var(--cm-tooltip-backgroundColorSelected)',
color: 'var(--cm-tooltip-textColorSelected)',
},
});
}
function getLightTheme() {
return syntaxHighlighting(defaultHighlightStyle);
}
function getDarkTheme() {
return syntaxHighlighting(vscodeDarkTheme);
}

View File

@ -0,0 +1,68 @@
import { indentLess } from '@codemirror/commands';
import { indentUnit } from '@codemirror/language';
import { EditorSelection, EditorState, Line, type ChangeSpec } from '@codemirror/state';
import { EditorView, type KeyBinding } from '@codemirror/view';
export const indentKeyBinding: KeyBinding = {
key: 'Tab',
run: indentMore,
shift: indentLess,
};
function indentMore({ state, dispatch }: EditorView) {
if (state.readOnly) {
return false;
}
dispatch(
state.update(
changeBySelectedLine(state, (from, to, changes) => {
changes.push({ from, to, insert: state.facet(indentUnit) });
}),
{ userEvent: 'input.indent' },
),
);
return true;
}
function changeBySelectedLine(
state: EditorState,
cb: (from: number, to: number | undefined, changes: ChangeSpec[], line: Line) => void,
) {
return state.changeByRange((range) => {
const changes: ChangeSpec[] = [];
const line = state.doc.lineAt(range.from);
// just insert single indent unit at the current cursor position
if (range.from === range.to) {
cb(range.from, undefined, changes, line);
}
// handle the case when multiple characters are selected in a single line
else if (range.from < range.to && range.to <= line.to) {
cb(range.from, range.to, changes, line);
} else {
let atLine = -1;
// handle the case when selection spans multiple lines
for (let pos = range.from; pos <= range.to; ) {
const line = state.doc.lineAt(pos);
if (line.number > atLine && (range.empty || range.to > line.from)) {
cb(line.from, undefined, changes, line);
atLine = line.number;
}
pos = line.to + 1;
}
}
const changeSet = state.changes(changes);
return {
changes,
range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)),
};
});
}

View File

@ -0,0 +1,91 @@
import { LanguageDescription } from '@codemirror/language';
export const supportedLanguages = [
LanguageDescription.of({
name: 'TS',
extensions: ['ts'],
async load() {
return import('@codemirror/lang-javascript').then((module) => module.javascript({ typescript: true }));
},
}),
LanguageDescription.of({
name: 'JS',
extensions: ['js', 'mjs', 'cjs'],
async load() {
return import('@codemirror/lang-javascript').then((module) => module.javascript());
},
}),
LanguageDescription.of({
name: 'TSX',
extensions: ['tsx'],
async load() {
return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true, typescript: true }));
},
}),
LanguageDescription.of({
name: 'JSX',
extensions: ['jsx'],
async load() {
return import('@codemirror/lang-javascript').then((module) => module.javascript({ jsx: true }));
},
}),
LanguageDescription.of({
name: 'HTML',
extensions: ['html'],
async load() {
return import('@codemirror/lang-html').then((module) => module.html());
},
}),
LanguageDescription.of({
name: 'CSS',
extensions: ['css'],
async load() {
return import('@codemirror/lang-css').then((module) => module.css());
},
}),
LanguageDescription.of({
name: 'SASS',
extensions: ['sass'],
async load() {
return import('@codemirror/lang-sass').then((module) => module.sass({ indented: true }));
},
}),
LanguageDescription.of({
name: 'SCSS',
extensions: ['scss'],
async load() {
return import('@codemirror/lang-sass').then((module) => module.sass({ indented: false }));
},
}),
LanguageDescription.of({
name: 'JSON',
extensions: ['json'],
async load() {
return import('@codemirror/lang-json').then((module) => module.json());
},
}),
LanguageDescription.of({
name: 'Markdown',
extensions: ['md'],
async load() {
return import('@codemirror/lang-markdown').then((module) => module.markdown());
},
}),
LanguageDescription.of({
name: 'Wasm',
extensions: ['wat'],
async load() {
return import('@codemirror/lang-wast').then((module) => module.wast());
},
}),
];
export async function getLanguage(fileName: string) {
const languageDescription = LanguageDescription.matchFilename(supportedLanguages, fileName);
if (languageDescription) {
return await languageDescription.load();
}
return undefined;
}

View File

@ -0,0 +1,133 @@
:root {
--cm-backgroundColor: var(--bolt-elements-editor-backgroundColor, var(--bolt-elements-app-backgroundColor));
--cm-textColor: var(--bolt-elements-editor-textColor, var(--bolt-text-primary));
/* Gutter */
--cm-gutter-backgroundColor: var(--bolt-elements-editor-gutter-backgroundColor, var(--cm-backgroundColor));
--cm-gutter-textColor: var(--bolt-elements-editor-gutter-textColor, var(--bolt-text-secondary));
--cm-gutter-activeLineTextColor: var(--bolt-elements-editor-gutter-activeLineTextColor, var(--cm-gutter-textColor));
/* Fold Gutter */
--cm-foldGutter-textColor: var(--bolt-elements-editor-foldGutter-textColor, var(--cm-gutter-textColor));
--cm-foldGutter-textColorHover: var(--bolt-elements-editor-foldGutter-textColorHover, var(--cm-gutter-textColor));
/* Active Line */
--cm-activeLineBackgroundColor: var(--bolt-elements-editor-activeLineBackgroundColor, rgb(224 231 235 / 30%));
/* Cursor */
--cm-cursor-width: 2px;
--cm-cursor-backgroundColor: var(--bolt-elements-editor-cursorColor, var(--bolt-text-primary));
/* Matching Brackets */
--cm-matching-bracket: var(--bolt-elements-editor-matchingBracketBackgroundColor, rgb(50 140 130 / 0.3));
/* Selection */
--cm-selection-backgroundColorFocused: var(--bolt-elements-editor-selection-backgroundColor, #42b4ff);
--cm-selection-backgroundOpacityFocused: var(--bolt-elements-editor-selection-backgroundOpacity, 0.3);
--cm-selection-backgroundColorBlured: var(--bolt-elements-editor-selection-inactiveBackgroundColor, #c9e9ff);
--cm-selection-backgroundOpacityBlured: var(--bolt-elements-editor-selection-inactiveBackgroundOpacity, 0.3);
/* Panels */
--cm-panels-borderColor: var(--bolt-elements-editor-panels-borderColor, var(--bolt-elements-app-borderColor));
/* Search */
--cm-search-backgroundColor: var(--bolt-elements-editor-search-backgroundColor, var(--cm-backgroundColor));
--cm-search-textColor: var(--bolt-elements-editor-search-textColor, var(--bolt-elements-app-textColor));
--cm-search-closeButton-backgroundColor: var(--bolt-elements-editor-search-closeButton-backgroundColor, transparent);
--cm-search-closeButton-backgroundColorHover: var(
--bolt-elements-editor-search-closeButton-backgroundColorHover,
var(--bolt-background-secondary)
);
--cm-search-closeButton-textColor: var(
--bolt-elements-editor-search-closeButton-textColor,
var(--bolt-text-secondary)
);
--cm-search-closeButton-textColorHover: var(
--bolt-elements-editor-search-closeButton-textColorHover,
var(--bolt-text-primary)
);
--cm-search-button-backgroundColor: var(
--bolt-elements-editor-search-button-backgroundColor,
var(--bolt-background-secondary)
);
--cm-search-button-backgroundColorHover: var(
--bolt-elements-editor-search-button-backgroundColorHover,
var(--bolt-background-active)
);
--cm-search-button-textColor: var(--bolt-elements-editor-search-button-textColor, var(--bolt-text-secondary));
--cm-search-button-textColorHover: var(--bolt-elements-editor-search-button-textColorHover, var(--bolt-text-primary));
--cm-search-button-borderColor: var(--bolt-elements-editor-search-button-borderColor, transparent);
--cm-search-button-borderColorHover: var(
--bolt-elements-editor-search-button-borderColorHover,
var(--cm-search-button-borderColor)
);
--cm-search-button-borderColorFocused: var(
--bolt-elements-editor-search-button-borderColorFocused,
var(--bolt-border-accent)
);
--cm-search-input-backgroundColor: var(
--bolt-elements-editor-search-input-backgroundColor,
var(--bolt-background-primary)
);
--cm-search-input-borderColor: var(
--bolt-elements-editor-search-input-borderColor,
var(--bolt-elements-app-borderColor)
);
--cm-search-input-borderColorFocused: var(
--bolt-elements-editor-search-input-borderColorFocused,
var(--bolt-border-accent)
);
/* Tooltip */
--cm-tooltip-backgroundColor: var(
--bolt-elements-editor-tooltip-backgroundColor,
var(--bolt-elements-app-backgroundColor)
);
--cm-tooltip-textColor: var(--bolt-elements-editor-tooltip-textColor, var(--bolt-text-primary));
--cm-tooltip-backgroundColorSelected: var(
--bolt-elements-editor-tooltip-backgroundColorSelected,
var(--bolt-background-accent)
);
--cm-tooltip-textColorSelected: var(
--bolt-elements-editor-tooltip-textColorSelected,
var(--bolt-text-primary-inverted)
);
--cm-tooltip-borderColor: var(--bolt-elements-editor-tooltip-borderColor, var(--bolt-elements-app-borderColor));
}
html[data-theme='light'] {
--bolt-elements-editor-gutter-textColor: #237893;
--bolt-elements-editor-gutter-activeLineTextColor: var(--bolt-text-primary);
--bolt-elements-editor-foldGutter-textColorHover: var(--bolt-text-primary);
}
html[data-theme='dark'] {
--bolt-elements-editor-gutter-activeLineTextColor: var(--bolt-text-primary);
--bolt-elements-editor-selection-backgroundOpacityBlured: 0.1;
--bolt-elements-editor-activeLineBackgroundColor: rgb(50 53 63 / 50%);
--bolt-elements-editor-foldGutter-textColorHover: var(--bolt-text-primary);
}

View File

@ -0,0 +1,76 @@
import { HighlightStyle } from '@codemirror/language';
import { tags } from '@lezer/highlight';
export const vscodeDarkTheme = HighlightStyle.define([
{
tag: [
tags.keyword,
tags.operatorKeyword,
tags.modifier,
tags.color,
tags.constant(tags.name),
tags.standard(tags.name),
tags.standard(tags.tagName),
tags.special(tags.brace),
tags.atom,
tags.bool,
tags.special(tags.variableName),
],
color: '#569cd6',
},
{
tag: [tags.controlKeyword, tags.moduleKeyword],
color: '#c586c0',
},
{
tag: [
tags.name,
tags.deleted,
tags.character,
tags.macroName,
tags.propertyName,
tags.variableName,
tags.labelName,
tags.definition(tags.name),
],
color: '#9cdcfe',
},
{ tag: tags.heading, fontWeight: 'bold', color: '#9cdcfe' },
{
tag: [
tags.typeName,
tags.className,
tags.tagName,
tags.number,
tags.changed,
tags.annotation,
tags.self,
tags.namespace,
],
color: '#4ec9b0',
},
{
tag: [tags.function(tags.variableName), tags.function(tags.propertyName)],
color: '#dcdcaa',
},
{ tag: [tags.number], color: '#b5cea8' },
{
tag: [tags.operator, tags.punctuation, tags.separator, tags.url, tags.escape, tags.regexp],
color: '#d4d4d4',
},
{
tag: [tags.regexp],
color: '#d16969',
},
{
tag: [tags.special(tags.string), tags.processingInstruction, tags.string, tags.inserted],
color: '#ce9178',
},
{ tag: [tags.angleBracket], color: '#808080' },
{ tag: tags.strong, fontWeight: 'bold' },
{ tag: tags.emphasis, fontStyle: 'italic' },
{ tag: tags.strikethrough, textDecoration: 'line-through' },
{ tag: [tags.meta, tags.comment], color: '#6a9955' },
{ tag: tags.link, color: '#6a9955', textDecoration: 'underline' },
{ tag: tags.invalid, color: '#ff0000' },
]);

View File

@ -1,5 +1,5 @@
import { memo } from 'react'; import { memo } from 'react';
import { classNames } from '~/utils/classNames'; import { classNames } from '../../utils/classNames';
type IconSize = 'sm' | 'md' | 'xl' | 'xxl'; type IconSize = 'sm' | 'md' | 'xl' | 'xxl';

View File

@ -0,0 +1,21 @@
import { useStore } from '@nanostores/react';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { themeStore } from '../../lib/stores/theme';
import CodeMirrorEditor from '../editor/codemirror/CodeMirrorEditor';
import { FileTreePanel } from './FileTreePanel';
export function EditorPanel() {
const theme = useStore(themeStore);
return (
<PanelGroup direction="horizontal">
<Panel defaultSize={30} minSize={20} collapsible={false}>
<FileTreePanel />
</Panel>
<PanelResizeHandle />
<Panel defaultSize={70} minSize={20}>
<CodeMirrorEditor theme={theme} settings={{ tabSize: 2 }} />
</Panel>
</PanelGroup>
);
}

View File

@ -0,0 +1,3 @@
export function FileTree() {
return <div>File Tree</div>;
}

View File

@ -0,0 +1,9 @@
import { FileTree } from './FileTree';
export function FileTreePanel() {
return (
<div className="border-r h-full p-4">
<FileTree />
</div>
);
}

View File

@ -0,0 +1,63 @@
import { useStore } from '@nanostores/react';
import { memo, useEffect, useRef, useState } from 'react';
import { workbenchStore } from '../../lib/stores/workbench';
import { IconButton } from '../ui/IconButton';
export const Preview = memo(() => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [activePreviewIndex] = useState(0);
const previews = useStore(workbenchStore.previews);
const activePreview = previews[activePreviewIndex];
const [url, setUrl] = useState('');
const [iframeUrl, setIframeUrl] = useState<string | undefined>();
useEffect(() => {
if (activePreview && !iframeUrl) {
const { baseUrl } = activePreview;
setUrl(baseUrl);
setIframeUrl(baseUrl);
}
}, [activePreview, iframeUrl]);
const reloadPreview = () => {
if (iframeRef.current) {
iframeRef.current.src = iframeRef.current.src;
}
};
return (
<div className="w-full h-full flex flex-col">
<div className="bg-gray-100 rounded-t-lg p-2 flex items-center space-x-1.5">
<div className="i-ph:circle-fill text-[#FF5F57]"></div>
<div className="i-ph:circle-fill text-[#FEBC2E]"></div>
<div className="i-ph:circle-fill text-[#29CC41]"></div>
<div className="flex-grow"></div>
</div>
<div className="bg-white p-2 flex items-center gap-1">
<IconButton icon="i-ph:arrow-clockwise" onClick={reloadPreview} />
<div className="flex items-center gap-1 flex-grow bg-gray-100 rounded-full px-3 py-1 text-sm text-gray-600 hover:bg-gray-200 hover:focus-within:bg-white focus-within:bg-white focus-within:ring-2 focus-within:ring-accent">
<div className="bg-white rounded-full p-[2px] -ml-1">
<div className="i-ph:info-bold text-lg"></div>
</div>
<input
className="w-full bg-transparent outline-none"
type="text"
value={url}
onChange={(event) => {
setUrl(event.target.value);
}}
/>
</div>
</div>
<div className="flex-1 bg-white border-t">
{activePreview ? (
<iframe ref={iframeRef} className="border-none w-full h-full" src={iframeUrl}></iframe>
) : (
<div className="flex w-full h-full justify-center items-center">No preview available</div>
)}
</div>
</div>
);
});

View File

@ -0,0 +1,69 @@
import { useStore } from '@nanostores/react';
import { AnimatePresence, motion, type Variants } from 'framer-motion';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { workbenchStore } from '../../lib/stores/workbench';
import { cubicEasingFn } from '../../utils/easings';
import { IconButton } from '../ui/IconButton';
import { EditorPanel } from './EditorPanel';
import { Preview } from './Preview';
interface WorkspaceProps {
chatStarted?: boolean;
}
const workbenchVariants = {
closed: {
width: 0,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
width: '100%',
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
} satisfies Variants;
export function Workbench({ chatStarted }: WorkspaceProps) {
const showWorkbench = useStore(workbenchStore.showWorkbench);
return (
chatStarted && (
<AnimatePresence>
{showWorkbench && (
<motion.div initial="closed" animate="open" exit="closed" variants={workbenchVariants}>
<div className="fixed top-[calc(var(--header-height)+1.5rem)] bottom-[calc(1.5rem-1px)] w-[50vw] mr-4 z-0">
<div className="flex flex-col bg-white border border-gray-200 shadow-sm rounded-lg overflow-hidden absolute inset-0 right-8">
<div className="px-3 py-2 border-b border-gray-200">
<IconButton
icon="i-ph:x-circle"
className="ml-auto"
size="xxl"
onClick={() => {
workbenchStore.showWorkbench.set(false);
}}
/>
</div>
<div className="flex-1 overflow-hidden">
<PanelGroup direction="vertical">
<Panel defaultSize={50} minSize={20}>
<EditorPanel />
</Panel>
<PanelResizeHandle />
<Panel defaultSize={50} minSize={20}>
<Preview />
</Panel>
</PanelGroup>
</div>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
)
);
}

View File

@ -1,55 +0,0 @@
import { useStore } from '@nanostores/react';
import { AnimatePresence, motion, type Variants } from 'framer-motion';
import { IconButton } from '~/components/ui/IconButton';
import { cubicEasingFn } from '~/utils/easings';
import { workspaceStore } from '../../lib/stores/workspace';
interface WorkspaceProps {
chatStarted?: boolean;
}
const workspaceVariants = {
closed: {
width: 0,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
width: '100%',
transition: {
duration: 0.5,
type: 'spring',
},
},
} satisfies Variants;
export function Workspace({ chatStarted }: WorkspaceProps) {
const showWorkspace = useStore(workspaceStore.showWorkspace);
return (
chatStarted && (
<AnimatePresence>
{showWorkspace && (
<motion.div initial="closed" animate="open" exit="closed" variants={workspaceVariants}>
<div className="fixed top-[calc(var(--header-height)+1.5rem)] bottom-6 w-[50vw] mr-4 z-0">
<div className="bg-white border border-gray-200 shadow-sm rounded-lg overflow-hidden absolute inset-0 right-8">
<header className="px-3 py-2 border-b border-gray-200">
<IconButton
icon="i-ph:x-circle"
className="ml-auto"
size="xxl"
onClick={() => {
workspaceStore.showWorkspace.set(false);
}}
/>
</header>
</div>
</div>
</motion.div>
)}
</AnimatePresence>
)
);
}

View File

@ -0,0 +1,2 @@
// see https://docs.anthropic.com/en/docs/about-claude/models
export const MAX_TOKENS = 8192;

View File

@ -1,4 +1,4 @@
export const systemPrompt = ` export const getSystemPrompt = (cwd: string = '/home/project') => `
You are Bolt, an expert AI assistant and exceptional senior software developer with vast knowledge across multiple programming languages, frameworks, and best practices. You are Bolt, an expert AI assistant and exceptional senior software developer with vast knowledge across multiple programming languages, frameworks, and best practices.
<system_constraints> <system_constraints>
@ -22,34 +22,45 @@ You are Bolt, an expert AI assistant and exceptional senior software developer w
- Shell commands to run including dependencies to install using a package manager (NPM) - Shell commands to run including dependencies to install using a package manager (NPM)
- Files to create and their contents - Files to create and their contents
- Folders to create if necessary
<artifact_instructions> <artifact_instructions>
1. Think BEFORE creating an artifact. 1. Think BEFORE creating an artifact
2. Wrap the content in opening and closing \`<boltArtifact>\` tags. These tags contain more specific \`<boltAction>\` elements. 2. The current working directory is \`${cwd}\`.
3. Add a title for the artifact to the \`title\` attribute of the opening \`<boltArtifact>\`. 3. Wrap the content in opening and closing \`<boltArtifact>\` tags. These tags contain more specific \`<boltAction>\` elements.
3. Use \`<boltAction>\` tags to define specific actions to perform. 4. Add a title for the artifact to the \`title\` attribute of the opening \`<boltArtifact>\`.
4. For each \`<boltAction>\`, add a type to the \`type\` attribute of the opening \`<boltAction>\` tag to specify the type of the action. Assign one of the following values to the \`type\` attribute: 5. Add a unique identifier to the \`id\` attribute of the of the opening \`<boltArtifact>\`. For updates, reuse the prior identifier. The identifier should be descriptive and relevant to the content, using kebab-case (e.g., "example-code-snippet"). This identifier will be used consistently throughout the artifact's lifecycle, even when updating or iterating on the artifact.
- shell: For running shell commands. When Using \`npx\`, ALWAYS provide the \`--yes\` flag! 6. Use \`<boltAction>\` tags to define specific actions to perform.
- file: For writing new files or updating existing files. For each file add a \`path\` attribute to the opening \`<boltArtifact>\` tag to specify the file path. The content of the the file artifact is the file contents. 7. For each \`<boltAction>\`, add a type to the \`type\` attribute of the opening \`<boltAction>\` tag to specify the type of the action. Assign one of the following values to the \`type\` attribute:
4. The order of the actions is VERY IMPORTANT. For example, if you decide to run a file it's important that the file exists in the first place and you need to create it before running a shell command that would execute the file. - shell: For running shell commands.
5. ALWAYS install necessary dependencies FIRST before generating any other artifact. If that requires a \`package.json\` then you should create that first! - When Using \`npx\`, ALWAYS provide the \`--yes\` flag.
- When running multiple shell commands, use \`&&\` to run them sequentially.
- Do NOT re-run a dev command if there is one that starts a dev server and new dependencies were installed. If a dev server has started already, assume that installing dependencies will be executed in a different process and will be picked up by the dev server.
- file: For writing new files or updating existing files. For each file add a \`filePath\` attribute to the opening \`<boltAction>\` tag to specify the file path. The content of the file artifact is the file contents. All file paths MUST BE relative to the current working directory.
8. The order of the actions is VERY IMPORTANT. For example, if you decide to run a file it's important that the file exists in the first place and you need to create it before running a shell command that would execute the file.
9. ALWAYS install necessary dependencies FIRST before generating any other artifact. If that requires a \`package.json\` then you should create that first!
IMPORTANT: Add all required dependencies to the \`package.json\` already and try to avoid \`npm i <pkg>\` if possible! IMPORTANT: Add all required dependencies to the \`package.json\` already and try to avoid \`npm i <pkg>\` if possible!
5. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...". 10. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...".
6. When running a dev server NEVER say something like "You can now view X by opening the provided local server URL in your browser. The preview will be opened automatically or by the user manually! 11. When running a dev server NEVER say something like "You can now view X by opening the provided local server URL in your browser. The preview will be opened automatically or by the user manually!
</artifact_instructions> </artifact_instructions>
</artifact_info> </artifact_info>
BEST PRACTICES: Follow coding best practices. Whenever creating files, split functionality into smaller modules instead of placing everything in a single large file. If possible, files should be as small as possible, with functionality extracted into separate modules. This is VERY IMPORTANT so that updates to the project can be done to smaller modules without re-generating large files!
NEVER use the word "artifact". For example: NEVER use the word "artifact". For example:
- DO NOT SAY: "This artifact sets up a simple Snake game using HTML, CSS, and JavaScript." - DO NOT SAY: "This artifact sets up a simple Snake game using HTML, CSS, and JavaScript."
- INSTEAD SAY: "We set up a simple Snake game using HTML, CSS, and JavaScript." - INSTEAD SAY: "We set up a simple Snake game using HTML, CSS, and JavaScript."
@ -69,16 +80,10 @@ Here are some examples of correct usage of artifacts:
<assistant_response> <assistant_response>
Certainly, I can help you create a JavaScript function to calculate the factorial of a number. Certainly, I can help you create a JavaScript function to calculate the factorial of a number.
<boltArtifact title="JavaScript Factorial Function"> <boltArtifact id="factorial-function" title="JavaScript Factorial Function">
<boltAction type="file" path="index.js"> <boltAction type="file" filePath="index.js">
function factorial(n) { function factorial(n) {
if (n === 0 || n === 1) { ...
return 1;
} else if (n < 0) {
return "Factorial is not defined for negative numbers";
} else {
return n * factorial(n - 1);
}
} }
... ...
@ -97,8 +102,8 @@ Here are some examples of correct usage of artifacts:
<assistant_response> <assistant_response>
Certainly! I'd be happy to help you build a snake game using JavaScript and HTML5 Canvas. This will be a basic implementation that you can later expand upon. Let's create the game step by step. Certainly! I'd be happy to help you build a snake game using JavaScript and HTML5 Canvas. This will be a basic implementation that you can later expand upon. Let's create the game step by step.
<boltArtifact title="Snake Game in HTML and JavaScript"> <boltArtifact id="snake-game" title="Snake Game in HTML and JavaScript">
<boltAction type="file" path="package.json"> <boltAction type="file" filePath="package.json">
{ {
"name": "snake", "name": "snake",
"scripts": { "scripts": {
@ -112,7 +117,7 @@ Here are some examples of correct usage of artifacts:
npm install --save-dev vite npm install --save-dev vite
</boltAction> </boltAction>
<boltAction type="file" path="index.html"> <boltAction type="file" filePath="index.html">
... ...
</boltAction> </boltAction>
@ -131,8 +136,8 @@ Here are some examples of correct usage of artifacts:
<assistant_response> <assistant_response>
Certainly! I'll create a bouncing ball with real gravity using React. We'll use the react-spring library for physics-based animations. Certainly! I'll create a bouncing ball with real gravity using React. We'll use the react-spring library for physics-based animations.
<boltArtifact title="Bouncing Ball with Gravity in React"> <boltArtifact id="bouncing-ball-react" title="Bouncing Ball with Gravity in React">
<boltAction type="file" path="package.json"> <boltAction type="file" filePath="package.json">
{ {
"name": "bouncing-ball", "name": "bouncing-ball",
"private": true, "private": true,
@ -157,19 +162,19 @@ Here are some examples of correct usage of artifacts:
} }
</boltAction> </boltAction>
<boltAction type="file" path="index.html"> <boltAction type="file" filePath="index.html">
... ...
</boltAction> </boltAction>
<boltAction type="file" path="src/main.jsx"> <boltAction type="file" filePath="src/main.jsx">
... ...
</boltAction> </boltAction>
<boltAction type="file" path="src/index.css"> <boltAction type="file" filePath="src/index.css">
... ...
</boltAction> </boltAction>
<boltAction type="file" path="src/App.jsx"> <boltAction type="file" filePath="src/App.jsx">
... ...
</boltAction> </boltAction>

View File

@ -0,0 +1,38 @@
import { streamText as _streamText, convertToCoreMessages } from 'ai';
import { getAPIKey } from '../llm/api-key';
import { getAnthropicModel } from '../llm/model';
import { MAX_TOKENS } from './constants';
import { getSystemPrompt } from './prompts';
interface ToolResult<Name extends string, Args, Result> {
toolCallId: string;
toolName: Name;
args: Args;
result: Result;
}
interface Message {
role: 'user' | 'assistant';
content: string;
toolInvocations?: ToolResult<string, unknown, unknown>[];
}
export type Messages = Message[];
export type StreamingOptions = Omit<Parameters<typeof _streamText>[0], 'model'>;
export function streamText(messages: Messages, env: Env, options?: StreamingOptions) {
return _streamText({
model: getAnthropicModel(getAPIKey(env)),
system: getSystemPrompt(),
maxTokens: MAX_TOKENS,
headers: {
'anthropic-beta': 'max-tokens-3-5-sonnet-2024-07-15',
},
messages: convertToCoreMessages(messages),
onFinish: ({ finishReason, usage, warnings }) => {
console.log({ finishReason, usage, warnings });
},
...options,
});
}

View File

@ -1,23 +1,28 @@
import type { Message } from 'ai'; import type { Message } from 'ai';
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { StreamingMessageParser } from '~/lib/runtime/message-parser'; import { createScopedLogger } from '../../utils/logger';
import { workspaceStore } from '~/lib/stores/workspace'; import { StreamingMessageParser } from '../runtime/message-parser';
import { createScopedLogger } from '~/utils/logger'; import { workbenchStore } from '../stores/workbench';
const logger = createScopedLogger('useMessageParser'); const logger = createScopedLogger('useMessageParser');
const messageParser = new StreamingMessageParser({ const messageParser = new StreamingMessageParser({
callbacks: { callbacks: {
onArtifactOpen: (messageId, { title }) => { onArtifactOpen: (data) => {
logger.debug('onArtifactOpen', title); logger.trace('onArtifactOpen', data);
workspaceStore.updateArtifact(messageId, { title, closed: false });
workbenchStore.showWorkbench.set(true);
workbenchStore.addArtifact(data);
}, },
onArtifactClose: (messageId) => { onArtifactClose: (data) => {
logger.debug('onArtifactClose'); logger.trace('onArtifactClose');
workspaceStore.updateArtifact(messageId, { closed: true });
workbenchStore.updateArtifact(data, { closed: true });
}, },
onAction: (messageId, { type, path, content }) => { onAction: (data) => {
console.log('ACTION', messageId, { type, path, content }); logger.trace('onAction', data);
workbenchStore.runAction(data);
}, },
}, },
}); });

View File

@ -1,5 +1,5 @@
import { useState } from 'react'; import { useState } from 'react';
import { createScopedLogger } from '~/utils/logger'; import { createScopedLogger } from '../../utils/logger';
const logger = createScopedLogger('usePromptEnhancement'); const logger = createScopedLogger('usePromptEnhancement');

View File

@ -0,0 +1,68 @@
import { WebContainer } from '@webcontainer/api';
import * as nodePath from 'node:path';
import { createScopedLogger } from '../../utils/logger';
import type { ActionCallbackData } from './message-parser';
const logger = createScopedLogger('ActionRunner');
export class ActionRunner {
#webcontainer: Promise<WebContainer>;
constructor(webcontainerPromise: Promise<WebContainer>) {
this.#webcontainer = webcontainerPromise;
}
async runAction({ action }: ActionCallbackData, abortSignal?: AbortSignal) {
logger.trace('Running action', action);
const { content } = action;
const webcontainer = await this.#webcontainer;
switch (action.type) {
case 'file': {
let folder = nodePath.dirname(action.filePath);
// remove trailing slashes
folder = folder.replace(/\/$/g, '');
if (folder !== '.') {
try {
await webcontainer.fs.mkdir(folder, { recursive: true });
logger.debug('Created folder', folder);
} catch (error) {
logger.error('Failed to create folder\n', error);
}
}
try {
await webcontainer.fs.writeFile(action.filePath, content);
logger.debug(`File written ${action.filePath}`);
} catch (error) {
logger.error('Failed to write file\n', error);
}
break;
}
case 'shell': {
const process = await webcontainer.spawn('jsh', ['-c', content]);
abortSignal?.addEventListener('abort', () => {
process.kill();
});
process.output.pipeTo(
new WritableStream({
write(data) {
console.log(data);
},
}),
);
const exitCode = await process.exit;
logger.debug(`Process terminated with code ${exitCode}`);
}
}
}
}

View File

@ -38,28 +38,30 @@ describe('StreamingMessageParser', () => {
['Before <boltArtifactt>foo</boltArtifact> After', 'Before <boltArtifactt>foo</boltArtifact> After'], ['Before <boltArtifactt>foo</boltArtifact> After', 'Before <boltArtifactt>foo</boltArtifact> After'],
['Before <boltArtifact title="Some title">foo</boltArtifact> After', 'Before After'], ['Before <boltArtifact title="Some title">foo</boltArtifact> After', 'Before After'],
[ [
'Before <boltArtifact title="Some title"><boltAction type="shell">npm install</boltAction></boltArtifact> After', 'Before <boltArtifact title="Some title" id="artifact_1"><boltAction type="shell">npm install</boltAction></boltArtifact> After',
'Before After', 'Before After',
[{ type: 'shell', content: 'npm install' }], [{ type: 'shell', content: 'npm install' }],
], ],
[ [
'Before <boltArtifact title="Some title"><boltAction type="shell">npm install</boltAction><boltAction type="file" path="index.js">some content</boltAction></boltArtifact> After', 'Before <boltArtifact title="Some title" id="artifact_1"><boltAction type="shell">npm install</boltAction><boltAction type="file" filePath="index.js">some content</boltAction></boltArtifact> After',
'Before After', 'Before After',
[ [
{ type: 'shell', content: 'npm install' }, { type: 'shell', content: 'npm install' },
{ type: 'file', path: 'index.js', content: 'some content\n' }, { type: 'file', filePath: 'index.js', content: 'some content\n' },
], ],
], ],
])('should correctly parse chunks and strip out bolt artifacts', (input, expected, expectedActions = []) => { ])('should correctly parse chunks and strip out bolt artifacts', (input, expected, expectedActions = []) => {
let actionCounter = 0; let actionCounter = 0;
const testId = 'test_id'; const expectedArtifactId = 'artifact_1';
const expectedMessageId = 'message_1';
const parser = new StreamingMessageParser({ const parser = new StreamingMessageParser({
artifactElement: '', artifactElement: '',
callbacks: { callbacks: {
onAction: (id, action) => { onAction: ({ artifactId, messageId, action }) => {
expect(testId).toBe(id); expect(artifactId).toBe(expectedArtifactId);
expect(messageId).toBe(expectedMessageId);
expect(action).toEqual(expectedActions[actionCounter]); expect(action).toEqual(expectedActions[actionCounter]);
actionCounter++; actionCounter++;
}, },
@ -75,7 +77,7 @@ describe('StreamingMessageParser', () => {
for (const chunk of chunks) { for (const chunk of chunks) {
message += chunk; message += chunk;
result += parser.parse(testId, message); result += parser.parse(expectedMessageId, message);
} }
expect(actionCounter).toBe(expectedActions.length); expect(actionCounter).toBe(expectedActions.length);

View File

@ -1,24 +1,30 @@
import type { ActionType, BoltAction, BoltActionData, FileAction, ShellAction } from '../../types/actions';
import type { BoltArtifactData } from '../../types/artifact';
import { createScopedLogger } from '../../utils/logger';
import { unreachable } from '../../utils/unreachable';
const ARTIFACT_TAG_OPEN = '<boltArtifact'; const ARTIFACT_TAG_OPEN = '<boltArtifact';
const ARTIFACT_TAG_CLOSE = '</boltArtifact>'; const ARTIFACT_TAG_CLOSE = '</boltArtifact>';
const ARTIFACT_ACTION_TAG_OPEN = '<boltAction'; const ARTIFACT_ACTION_TAG_OPEN = '<boltAction';
const ARTIFACT_ACTION_TAG_CLOSE = '</boltAction>'; const ARTIFACT_ACTION_TAG_CLOSE = '</boltAction>';
interface BoltArtifact { const logger = createScopedLogger('MessageParser');
title: string;
export interface ArtifactCallbackData extends BoltArtifactData {
messageId: string;
} }
type ArtifactOpenCallback = (messageId: string, artifact: BoltArtifact) => void; export interface ActionCallbackData {
type ArtifactCloseCallback = (messageId: string) => void; artifactId: string;
type ActionCallback = (messageId: string, action: BoltActionData) => void; messageId: string;
actionId: string;
type ActionType = 'file' | 'shell'; action: BoltAction;
export interface BoltActionData {
type?: ActionType;
path?: string;
content: string;
} }
type ArtifactOpenCallback = (data: ArtifactCallbackData) => void;
type ArtifactCloseCallback = (data: ArtifactCallbackData) => void;
type ActionCallback = (data: ActionCallbackData) => void;
interface Callbacks { interface Callbacks {
onArtifactOpen?: ArtifactOpenCallback; onArtifactOpen?: ArtifactOpenCallback;
onArtifactClose?: ArtifactCloseCallback; onArtifactClose?: ArtifactCloseCallback;
@ -32,39 +38,72 @@ interface StreamingMessageParserOptions {
artifactElement?: string | ElementFactory; artifactElement?: string | ElementFactory;
} }
interface MessageState {
position: number;
insideArtifact: boolean;
insideAction: boolean;
currentArtifact?: BoltArtifactData;
currentAction: BoltActionData;
actionId: number;
}
export class StreamingMessageParser { export class StreamingMessageParser {
#lastPositions = new Map<string, number>(); #messages = new Map<string, MessageState>();
#insideArtifact = false;
#insideAction = false;
#currentAction: BoltActionData = { content: '' };
constructor(private _options: StreamingMessageParserOptions = {}) {} constructor(private _options: StreamingMessageParserOptions = {}) {}
parse(id: string, input: string) { parse(messageId: string, input: string) {
let state = this.#messages.get(messageId);
if (!state) {
state = {
position: 0,
insideAction: false,
insideArtifact: false,
currentAction: { content: '' },
actionId: 0,
};
this.#messages.set(messageId, state);
}
let output = ''; let output = '';
let i = this.#lastPositions.get(id) ?? 0; let i = state.position;
let earlyBreak = false; let earlyBreak = false;
while (i < input.length) { while (i < input.length) {
if (this.#insideArtifact) { if (state.insideArtifact) {
if (this.#insideAction) { const currentArtifact = state.currentArtifact;
if (currentArtifact === undefined) {
unreachable('Artifact not initialized');
}
if (state.insideAction) {
const closeIndex = input.indexOf(ARTIFACT_ACTION_TAG_CLOSE, i); const closeIndex = input.indexOf(ARTIFACT_ACTION_TAG_CLOSE, i);
const currentAction = state.currentAction;
if (closeIndex !== -1) { if (closeIndex !== -1) {
this.#currentAction.content += input.slice(i, closeIndex); currentAction.content += input.slice(i, closeIndex);
let content = this.#currentAction.content.trim(); let content = currentAction.content.trim();
if (this.#currentAction.type === 'file') { if ('type' in currentAction && currentAction.type === 'file') {
content += '\n'; content += '\n';
} }
this.#currentAction.content = content; currentAction.content = content;
this._options.callbacks?.onAction?.(id, this.#currentAction); this._options.callbacks?.onAction?.({
artifactId: currentArtifact.id,
messageId,
actionId: String(state.actionId++),
action: currentAction as BoltAction,
});
this.#insideAction = false; state.insideAction = false;
this.#currentAction = { content: '' }; state.currentAction = { content: '' };
i = closeIndex + ARTIFACT_ACTION_TAG_CLOSE.length; i = closeIndex + ARTIFACT_ACTION_TAG_CLOSE.length;
} else { } else {
@ -79,17 +118,39 @@ export class StreamingMessageParser {
if (actionEndIndex !== -1) { if (actionEndIndex !== -1) {
const actionTag = input.slice(actionOpenIndex, actionEndIndex + 1); const actionTag = input.slice(actionOpenIndex, actionEndIndex + 1);
this.#currentAction.type = this.#extractAttribute(actionTag, 'type') as ActionType;
this.#currentAction.path = this.#extractAttribute(actionTag, 'path'); const actionType = this.#extractAttribute(actionTag, 'type') as ActionType;
this.#insideAction = true;
const actionAttributes = {
type: actionType,
content: '',
};
if (actionType === 'file') {
const filePath = this.#extractAttribute(actionTag, 'filePath') as string;
if (!filePath) {
logger.debug('File path not specified');
}
(actionAttributes as FileAction).filePath = filePath;
} else if (actionType !== 'shell') {
logger.warn(`Unknown action type '${actionType}'`);
}
state.currentAction = actionAttributes as FileAction | ShellAction;
state.insideAction = true;
i = actionEndIndex + 1; i = actionEndIndex + 1;
} else { } else {
break; break;
} }
} else if (artifactCloseIndex !== -1) { } else if (artifactCloseIndex !== -1) {
this.#insideArtifact = false; this._options.callbacks?.onArtifactClose?.({ messageId, ...currentArtifact });
this._options.callbacks?.onArtifactClose?.(id); state.insideArtifact = false;
state.currentArtifact = undefined;
i = artifactCloseIndex + ARTIFACT_TAG_CLOSE.length; i = artifactCloseIndex + ARTIFACT_TAG_CLOSE.length;
} else { } else {
@ -118,12 +179,30 @@ export class StreamingMessageParser {
const artifactTag = input.slice(i, openTagEnd + 1); const artifactTag = input.slice(i, openTagEnd + 1);
const artifactTitle = this.#extractAttribute(artifactTag, 'title') as string; const artifactTitle = this.#extractAttribute(artifactTag, 'title') as string;
const artifactId = this.#extractAttribute(artifactTag, 'id') as string;
this.#insideArtifact = true; if (!artifactTitle) {
logger.warn('Artifact title missing');
}
this._options.callbacks?.onArtifactOpen?.(id, { title: artifactTitle }); if (!artifactId) {
logger.warn('Artifact id missing');
}
output += this._options.artifactElement ?? `<div class="__boltArtifact__" data-message-id="${id}"></div>`; state.insideArtifact = true;
const currentArtifact = {
id: artifactId,
title: artifactTitle,
} satisfies BoltArtifactData;
state.currentArtifact = currentArtifact;
this._options.callbacks?.onArtifactOpen?.({ messageId, ...currentArtifact });
output +=
this._options.artifactElement ??
`<div class="__boltArtifact__" data-artifact-id="${artifactId}" data-message-id="${messageId}"></div>`;
i = openTagEnd + 1; i = openTagEnd + 1;
} else { } else {
@ -153,16 +232,13 @@ export class StreamingMessageParser {
} }
} }
this.#lastPositions.set(id, i); state.position = i;
return output; return output;
} }
reset() { reset() {
this.#lastPositions.clear(); this.#messages.clear();
this.#insideArtifact = false;
this.#insideAction = false;
this.#currentAction = { content: '' };
} }
#extractAttribute(tag: string, attributeName: string): string | undefined { #extractAttribute(tag: string, attributeName: string): string | undefined {

View File

@ -0,0 +1,42 @@
import type { WebContainer } from '@webcontainer/api';
import { atom } from 'nanostores';
export interface PreviewInfo {
port: number;
ready: boolean;
baseUrl: string;
}
export class PreviewsStore {
#availablePreviews = new Map<number, PreviewInfo>();
#webcontainer: Promise<WebContainer>;
previews = atom<PreviewInfo[]>([]);
constructor(webcontainerPromise: Promise<WebContainer>) {
this.#webcontainer = webcontainerPromise;
this.#init();
}
async #init() {
const webcontainer = await this.#webcontainer;
webcontainer.on('port', (port, type, url) => {
let previewInfo = this.#availablePreviews.get(port);
const previews = this.previews.get();
if (!previewInfo) {
previewInfo = { port, ready: type === 'open', baseUrl: url };
this.#availablePreviews.set(port, previewInfo);
previews.push(previewInfo);
}
previewInfo.ready = type === 'open';
previewInfo.baseUrl = url;
this.previews.set([...previews]);
});
}
}

View File

@ -0,0 +1,33 @@
import { atom } from 'nanostores';
export type Theme = 'dark' | 'light';
export const kTheme = 'bolt_theme';
export function themeIsDark() {
return themeStore.get() === 'dark';
}
export const themeStore = atom<Theme>(initStore());
function initStore() {
if (!import.meta.env.SSR) {
const persistedTheme = localStorage.getItem(kTheme) as Theme | undefined;
const themeAttribute = document.querySelector('html')?.getAttribute('data-theme');
return persistedTheme ?? (themeAttribute as Theme) ?? 'light';
}
return 'light';
}
export function toggleTheme() {
const currentTheme = themeStore.get();
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
themeStore.set(newTheme);
localStorage.setItem(kTheme, newTheme);
document.querySelector('html')?.setAttribute('data-theme', newTheme);
}

View File

@ -0,0 +1,153 @@
import { atom, map, type MapStore, type WritableAtom } from 'nanostores';
import type { BoltAction } from '../../types/actions';
import { unreachable } from '../../utils/unreachable';
import { ActionRunner } from '../runtime/action-runner';
import type { ActionCallbackData, ArtifactCallbackData } from '../runtime/message-parser';
import { webcontainer } from '../webcontainer';
import { PreviewsStore } from './previews';
export type RunningState = BoltAction & {
status: 'running' | 'complete' | 'pending' | 'aborted';
abort?: () => void;
};
export type FailedState = BoltAction & {
status: 'failed';
error: string;
abort?: () => void;
};
export type ActionState = RunningState | FailedState;
export type ActionStateUpdate =
| { status: 'running' | 'complete' | 'pending' | 'aborted'; abort?: () => void }
| { status: 'failed'; error: string; abort?: () => void }
| { abort?: () => void };
export interface ArtifactState {
title: string;
closed: boolean;
currentActionPromise: Promise<void>;
actions: MapStore<Record<string, ActionState>>;
}
type Artifacts = MapStore<Record<string, ArtifactState>>;
export class WorkbenchStore {
#actionRunner = new ActionRunner(webcontainer);
#previewsStore = new PreviewsStore(webcontainer);
artifacts: Artifacts = import.meta.hot?.data.artifacts ?? map({});
showWorkbench: WritableAtom<boolean> = import.meta.hot?.data.showWorkbench ?? atom(false);
get previews() {
return this.#previewsStore.previews;
}
setShowWorkbench(show: boolean) {
this.showWorkbench.set(show);
}
addArtifact({ id, messageId, title }: ArtifactCallbackData) {
const artifacts = this.artifacts.get();
const artifactKey = getArtifactKey(id, messageId);
const artifact = artifacts[artifactKey];
if (artifact) {
return;
}
this.artifacts.setKey(artifactKey, {
title,
closed: false,
actions: map({}),
currentActionPromise: Promise.resolve(),
});
}
updateArtifact({ id, messageId }: ArtifactCallbackData, state: Partial<ArtifactState>) {
const artifacts = this.artifacts.get();
const key = getArtifactKey(id, messageId);
const artifact = artifacts[key];
if (!artifact) {
return;
}
this.artifacts.setKey(key, { ...artifact, ...state });
}
async runAction(data: ActionCallbackData) {
const { artifactId, messageId, actionId } = data;
const artifacts = this.artifacts.get();
const key = getArtifactKey(artifactId, messageId);
const artifact = artifacts[key];
if (!artifact) {
unreachable('Artifact not found');
}
const actions = artifact.actions.get();
const action = actions[actionId];
if (action) {
return;
}
artifact.actions.setKey(actionId, { ...data.action, status: 'pending' });
artifact.currentActionPromise = artifact.currentActionPromise.then(async () => {
try {
let abortController: AbortController | undefined;
if (data.action.type === 'shell') {
abortController = new AbortController();
}
let aborted = false;
this.#updateAction(key, actionId, {
status: 'running',
abort: () => {
aborted = true;
abortController?.abort();
},
});
await this.#actionRunner.runAction(data, abortController?.signal);
this.#updateAction(key, actionId, { status: aborted ? 'aborted' : 'complete' });
} catch (error) {
this.#updateAction(key, actionId, { status: 'failed', error: 'Action failed' });
throw error;
}
});
}
#updateAction(artifactId: string, actionId: string, newState: ActionStateUpdate) {
const artifacts = this.artifacts.get();
const artifact = artifacts[artifactId];
if (!artifact) {
return;
}
const actions = artifact.actions.get();
artifact.actions.setKey(actionId, { ...actions[actionId], ...newState });
}
}
export function getArtifactKey(artifactId: string, messageId: string) {
return `${artifactId}_${messageId}`;
}
export const workbenchStore = new WorkbenchStore();
if (import.meta.hot) {
import.meta.hot.data.artifacts = workbenchStore.artifacts;
import.meta.hot.data.showWorkbench = workbenchStore.showWorkbench;
}

View File

@ -1,42 +0,0 @@
import type { WebContainer } from '@webcontainer/api';
import { atom, map, type MapStore, type WritableAtom } from 'nanostores';
import { webcontainer } from '~/lib/webcontainer';
interface WorkspaceStoreOptions {
webcontainer: Promise<WebContainer>;
}
interface ArtifactState {
title: string;
closed: boolean;
actions: any /* TODO */;
}
export class WorkspaceStore {
#webcontainer: Promise<WebContainer>;
artifacts: MapStore<Record<string, ArtifactState>> = import.meta.hot?.data.artifacts ?? map({});
showWorkspace: WritableAtom<boolean> = import.meta.hot?.data.showWorkspace ?? atom(false);
constructor({ webcontainer }: WorkspaceStoreOptions) {
this.#webcontainer = webcontainer;
}
updateArtifact(id: string, state: Partial<ArtifactState>) {
const artifacts = this.artifacts.get();
const artifact = artifacts[id];
this.artifacts.setKey(id, { ...artifact, ...state });
}
runAction() {
// TODO
}
}
export const workspaceStore = new WorkspaceStore({ webcontainer });
if (import.meta.hot) {
import.meta.hot.data.artifacts = workspaceStore.artifacts;
import.meta.hot.data.showWorkspace = workspaceStore.showWorkspace;
}

View File

@ -21,8 +21,9 @@ if (!import.meta.env.SSR) {
import.meta.hot?.data.webcontainer ?? import.meta.hot?.data.webcontainer ??
Promise.resolve() Promise.resolve()
.then(() => WebContainer.boot({ workdirName: 'project' })) .then(() => WebContainer.boot({ workdirName: 'project' }))
.then(() => { .then((webcontainer) => {
webcontainerContext.loaded = true; webcontainerContext.loaded = true;
return webcontainer;
}); });
if (import.meta.hot) { if (import.meta.hot) {

View File

@ -1,7 +1,11 @@
import { useStore } from '@nanostores/react';
import type { LinksFunction } from '@remix-run/cloudflare'; import type { LinksFunction } from '@remix-run/cloudflare';
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react'; import { Links, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react';
import tailwindReset from '@unocss/reset/tailwind-compat.css?url'; import tailwindReset from '@unocss/reset/tailwind-compat.css?url';
import globalStyles from '~/styles/index.scss?url'; import { themeStore } from './lib/stores/theme';
import { stripIndents } from './utils/stripIndent';
import globalStyles from './styles/index.scss?url';
import 'virtual:uno.css'; import 'virtual:uno.css';
@ -28,14 +32,31 @@ export const links: LinksFunction = () => [
}, },
]; ];
const inlineThemeCode = stripIndents`
setTutorialKitTheme();
function setTutorialKitTheme() {
let theme = localStorage.getItem('bolt_theme');
if (!theme) {
theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
document.querySelector('html')?.setAttribute('data-theme', theme);
}
`;
export function Layout({ children }: { children: React.ReactNode }) { export function Layout({ children }: { children: React.ReactNode }) {
const theme = useStore(themeStore);
return ( return (
<html lang="en"> <html lang="en" data-theme={theme}>
<head> <head>
<meta charSet="utf-8" /> <meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta /> <Meta />
<Links /> <Links />
<script dangerouslySetInnerHTML={{ __html: inlineThemeCode }} />
</head> </head>
<body> <body>
{children} {children}

View File

@ -1,9 +1,9 @@
import { json, redirect, type LoaderFunctionArgs, type MetaFunction } from '@remix-run/cloudflare'; import { json, redirect, type LoaderFunctionArgs, type MetaFunction } from '@remix-run/cloudflare';
import { ClientOnly } from 'remix-utils/client-only'; import { ClientOnly } from 'remix-utils/client-only';
import { BaseChat } from '~/components/chat/BaseChat'; import { BaseChat } from '../components/chat/BaseChat';
import { Chat } from '~/components/chat/Chat.client'; import { Chat } from '../components/chat/Chat.client';
import { Header } from '~/components/Header'; import { Header } from '../components/Header';
import { isAuthenticated } from '~/lib/.server/sessions'; import { isAuthenticated } from '../lib/.server/sessions';
export const meta: MetaFunction = () => { export const meta: MetaFunction = () => {
return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }]; return [{ title: 'Bolt' }, { name: 'description', content: 'Talk with Bolt, an AI assistant from StackBlitz' }];

View File

@ -1,36 +1,11 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare'; import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { convertToCoreMessages, streamText } from 'ai'; import { streamText, type Messages } from '../lib/.server/llm/stream-text';
import { getAPIKey } from '~/lib/.server/llm/api-key';
import { getAnthropicModel } from '~/lib/.server/llm/model';
import { systemPrompt } from '~/lib/.server/llm/prompts';
interface ToolResult<Name extends string, Args, Result> {
toolCallId: string;
toolName: Name;
args: Args;
result: Result;
}
interface Message {
role: 'user' | 'assistant';
content: string;
toolInvocations?: ToolResult<string, unknown, unknown>[];
}
export async function action({ context, request }: ActionFunctionArgs) { export async function action({ context, request }: ActionFunctionArgs) {
const { messages } = await request.json<{ messages: Message[] }>(); const { messages } = await request.json<{ messages: Messages }>();
try { try {
const result = await streamText({ const result = await streamText(messages, context.cloudflare.env, { toolChoice: 'none' });
model: getAnthropicModel(getAPIKey(context.cloudflare.env)),
messages: convertToCoreMessages(messages),
toolChoice: 'none',
onFinish: ({ finishReason, usage, warnings }) => {
console.log({ finishReason, usage, warnings });
},
system: systemPrompt,
});
return result.toAIStreamResponse(); return result.toAIStreamResponse();
} catch (error) { } catch (error) {
console.log(error); console.log(error);

View File

@ -1,9 +1,7 @@
import { type ActionFunctionArgs } from '@remix-run/cloudflare'; import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { StreamingTextResponse, convertToCoreMessages, parseStreamPart, streamText } from 'ai'; import { StreamingTextResponse, parseStreamPart } from 'ai';
import { getAPIKey } from '~/lib/.server/llm/api-key'; import { streamText } from '../lib/.server/llm/stream-text';
import { getAnthropicModel } from '~/lib/.server/llm/model'; import { stripIndents } from '../utils/stripIndent';
import { systemPrompt } from '~/lib/.server/llm/prompts';
import { stripIndents } from '~/utils/stripIndent';
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const decoder = new TextDecoder(); const decoder = new TextDecoder();
@ -12,10 +10,8 @@ export async function action({ context, request }: ActionFunctionArgs) {
const { message } = await request.json<{ message: string }>(); const { message } = await request.json<{ message: string }>();
try { try {
const result = await streamText({ const result = await streamText(
model: getAnthropicModel(getAPIKey(context.cloudflare.env)), [
system: systemPrompt,
messages: convertToCoreMessages([
{ {
role: 'user', role: 'user',
content: stripIndents` content: stripIndents`
@ -28,14 +24,9 @@ export async function action({ context, request }: ActionFunctionArgs) {
</original_prompt> </original_prompt>
`, `,
}, },
]), ],
}); context.cloudflare.env,
);
if (import.meta.env.DEV) {
result.usage.then((usage) => {
console.log('Usage', usage);
});
}
const transformStream = new TransformStream({ const transformStream = new TransformStream({
transform(chunk, controller) { transform(chunk, controller) {

View File

@ -6,8 +6,8 @@ import {
type TypedResponse, type TypedResponse,
} from '@remix-run/cloudflare'; } from '@remix-run/cloudflare';
import { Form, useActionData } from '@remix-run/react'; import { Form, useActionData } from '@remix-run/react';
import { verifyPassword } from '~/lib/.server/login'; import { verifyPassword } from '../lib/.server/login';
import { createUserSession, isAuthenticated } from '~/lib/.server/sessions'; import { createUserSession, isAuthenticated } from '../lib/.server/sessions';
interface Errors { interface Errors {
password?: string; password?: string;

View File

@ -1,12 +1,30 @@
/* Color Tokens Light Theme */
:root, :root,
:root[data-theme='light'] { :root[data-theme='light'] {
/* Color Tokens */ --bolt-background-primary: theme('colors.gray.0');
--bolt-background-primary: theme('colors.gray.50'); --bolt-background-secondary: theme('colors.gray.50');
--bolt-background-active: theme('colors.gray.200');
--bolt-background-accent: theme('colors.accent.600');
--bolt-background-accent-secondary: theme('colors.accent.600');
--bolt-background-accent-active: theme('colors.accent.500');
--bolt-text-primary: theme('colors.gray.800');
--bolt-text-primary-inverted: theme('colors.gray.0');
--bolt-text-secondary: theme('colors.gray.600');
--bolt-text-secondary-inverted: theme('colors.gray.200');
--bolt-text-disabled: theme('colors.gray.400');
--bolt-text-accent: theme('colors.accent.600');
--bolt-text-positive: theme('colors.positive.700');
--bolt-text-warning: theme('colors.warning.600');
--bolt-text-negative: theme('colors.negative.600');
--bolt-border-primary: theme('colors.gray.200');
--bolt-border-accent: theme('colors.accent.600');
} }
/* Color Tokens Dark Theme */
:root, :root,
:root[data-theme='dark'] { :root[data-theme='dark'] {
/* Color Tokens */
--bolt-background-primary: theme('colors.gray.50'); --bolt-background-primary: theme('colors.gray.50');
} }
@ -20,4 +38,7 @@
/* App */ /* App */
--bolt-elements-app-backgroundColor: var(--bolt-background-primary); --bolt-elements-app-backgroundColor: var(--bolt-background-primary);
--bolt-elements-app-borderColor: var(--bolt-border-primary);
--bolt-elements-app-textColor: var(--bolt-text-primary);
--bolt-elements-app-linkColor: var(--bolt-text-accent);
} }

View File

@ -0,0 +1,18 @@
export type ActionType = 'file' | 'shell';
export interface BaseAction {
content: string;
}
export interface FileAction extends BaseAction {
type: 'file';
filePath: string;
}
export interface ShellAction extends BaseAction {
type: 'shell';
}
export type BoltAction = FileAction | ShellAction;
export type BoltActionData = BoltAction | BaseAction;

View File

@ -0,0 +1,4 @@
export interface BoltArtifactData {
id: string;
title: string;
}

View File

@ -0,0 +1 @@
export type Theme = 'dark' | 'light';

View File

@ -0,0 +1,17 @@
export function debounce<Args extends any[]>(fn: (...args: Args) => void, delay = 100) {
if (delay === 0) {
return fn;
}
let timer: number | undefined;
return function <U>(this: U, ...args: Args) {
const context = this;
clearTimeout(timer);
timer = window.setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}

View File

@ -0,0 +1,3 @@
export function unreachable(message: string): never {
throw new Error(`Unreachable: ${message}`);
}

View File

@ -9,31 +9,47 @@
"build": "remix vite:build", "build": "remix vite:build",
"dev": "remix vite:dev", "dev": "remix vite:dev",
"test": "vitest --run", "test": "vitest --run",
"test:watch": "vitest",
"start": "bindings=$(./bindings.sh) && wrangler pages dev ./build/client $bindings", "start": "bindings=$(./bindings.sh) && wrangler pages dev ./build/client $bindings",
"typecheck": "tsc", "typecheck": "tsc",
"typegen": "wrangler types", "typegen": "wrangler types",
"preview": "pnpm run build && pnpm run start" "preview": "pnpm run build && pnpm run start"
}, },
"dependencies": { "dependencies": {
"@ai-sdk/anthropic": "^0.0.27", "@ai-sdk/anthropic": "^0.0.30",
"@codemirror/autocomplete": "^6.17.0",
"@codemirror/commands": "^6.6.0",
"@codemirror/lang-css": "^6.2.1",
"@codemirror/lang-html": "^6.4.9",
"@codemirror/lang-javascript": "^6.2.2",
"@codemirror/lang-json": "^6.0.1",
"@codemirror/lang-markdown": "^6.2.5",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-wast": "^6.0.2",
"@codemirror/language": "^6.10.2",
"@codemirror/search": "^6.5.6",
"@codemirror/state": "^6.4.1",
"@codemirror/view": "^6.28.4",
"@iconify-json/ph": "^1.1.13", "@iconify-json/ph": "^1.1.13",
"@iconify-json/svg-spinners": "^1.1.2", "@iconify-json/svg-spinners": "^1.1.2",
"@lezer/highlight": "^1.2.0",
"@nanostores/react": "^0.7.2", "@nanostores/react": "^0.7.2",
"@remix-run/cloudflare": "^2.10.2", "@remix-run/cloudflare": "^2.10.2",
"@remix-run/cloudflare-pages": "^2.10.2", "@remix-run/cloudflare-pages": "^2.10.2",
"@remix-run/react": "^2.10.2", "@remix-run/react": "^2.10.2",
"@unocss/reset": "^0.61.0", "@unocss/reset": "^0.61.0",
"@webcontainer/api": "^1.2.0", "@webcontainer/api": "^1.3.0-internal.1",
"@xterm/addon-fit": "^0.10.0", "@xterm/addon-fit": "^0.10.0",
"@xterm/addon-web-links": "^0.11.0", "@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0", "@xterm/xterm": "^5.5.0",
"ai": "^3.2.16", "ai": "^3.2.27",
"framer-motion": "^11.2.12", "framer-motion": "^11.2.12",
"isbot": "^4.1.0", "isbot": "^4.1.0",
"nanostores": "^0.10.3", "nanostores": "^0.10.3",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-markdown": "^9.0.1", "react-markdown": "^9.0.1",
"react-resizable-panels": "^2.0.20",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"remark-gfm": "^4.0.0", "remark-gfm": "^4.0.0",
"remix-utils": "^7.6.0", "remix-utils": "^7.6.0",
@ -49,6 +65,8 @@
"unified": "^11.0.5", "unified": "^11.0.5",
"unocss": "^0.61.3", "unocss": "^0.61.3",
"vite": "^5.3.1", "vite": "^5.3.1",
"vite-plugin-node-polyfills": "^0.22.0",
"vite-plugin-optimize-css-modules": "^1.1.0",
"vite-tsconfig-paths": "^4.3.2", "vite-tsconfig-paths": "^4.3.2",
"wrangler": "^3.63.2", "wrangler": "^3.63.2",
"zod": "^3.23.8" "zod": "^3.23.8"

View File

@ -111,6 +111,9 @@ export default defineConfig({
elements: { elements: {
app: { app: {
backgroundColor: 'var(--bolt-elements-app-backgroundColor)', backgroundColor: 'var(--bolt-elements-app-backgroundColor)',
borderColor: 'var(--bolt-elements-app-borderColor)',
textColor: 'var(--bolt-elements-app-textColor)',
linkColor: 'var(--bolt-elements-app-linkColor)',
}, },
}, },
}, },

View File

@ -1,11 +1,16 @@
import { cloudflareDevProxyVitePlugin as remixCloudflareDevProxy, vitePlugin as remixVitePlugin } from '@remix-run/dev'; import { cloudflareDevProxyVitePlugin as remixCloudflareDevProxy, vitePlugin as remixVitePlugin } from '@remix-run/dev';
import UnoCSS from 'unocss/vite'; import UnoCSS from 'unocss/vite';
import { defineConfig } from 'vite'; import { defineConfig } from 'vite';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import { optimizeCssModules } from 'vite-plugin-optimize-css-modules';
import tsconfigPaths from 'vite-tsconfig-paths'; import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig((config) => { export default defineConfig((config) => {
return { return {
plugins: [ plugins: [
nodePolyfills({
include: ['path'],
}),
config.mode !== 'test' && remixCloudflareDevProxy(), config.mode !== 'test' && remixCloudflareDevProxy(),
remixVitePlugin({ remixVitePlugin({
future: { future: {
@ -16,6 +21,7 @@ export default defineConfig((config) => {
}), }),
UnoCSS(), UnoCSS(),
tsconfigPaths(), tsconfigPaths(),
config.mode === 'production' && optimizeCssModules({ apply: 'build' }),
], ],
}; };
}); });

1038
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff