Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Add persistent design systems for prompts
Abi Rajabdb91eb79ebb
diff --git a/backend/main.py b/backend/main.pyindex 45b8364f..20d7d062 100644--- a/backend/main.py+++ b/backend/main.py@@ -7,7 +7,7 @@ load_dotenv()from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom config import IS_DEBUG_ENABLED-from routes import screenshot, generate_code, home, evals, export+from routes import screenshot, generate_code, home, evals, export, design_systemsapp = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)@@ -32,3 +32,4 @@ app.include_router(screenshot.router)app.include_router(home.router)app.include_router(evals.router)app.include_router(export.router)+app.include_router(design_systems.router)diff --git a/backend/prompts/create/__init__.py b/backend/prompts/create/__init__.pyindex 58ab525a..04fc86a0 100644--- a/backend/prompts/create/__init__.py+++ b/backend/prompts/create/__init__.py@@ -11,6 +11,7 @@ def build_create_prompt_from_input(stack: Stack,prompt: UserTurnInput,image_generation_enabled: bool,+ design_system: str | None = None,) -> Prompt:if input_mode == "image":image_urls = prompt.get("images", [])@@ -20,12 +21,14 @@ def build_create_prompt_from_input(stack=stack,text_prompt=text_prompt,image_generation_enabled=image_generation_enabled,+ design_system=design_system,)if input_mode == "text":return build_text_prompt_messages(text_prompt=prompt["text"],stack=stack,image_generation_enabled=image_generation_enabled,+ design_system=design_system,)if input_mode == "video":video_urls = prompt.get("videos", [])@@ -37,6 +40,7 @@ def build_create_prompt_from_input(stack=stack,text_prompt=prompt.get("text", ""),image_generation_enabled=image_generation_enabled,+ design_system=design_system,)raise ValueError(f"Unsupported input mode: {input_mode}")diff --git a/backend/prompts/create/image.py b/backend/prompts/create/image.pyindex b2e87f58..39bfa886 100644--- a/backend/prompts/create/image.py+++ b/backend/prompts/create/image.py@@ -2,6 +2,7 @@ from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessfrom prompts.prompt_types import Stackfrom prompts import system_prompt+from prompts.design_system import build_design_system_prompt_blockfrom prompts.policies import build_selected_stack_policy, build_user_image_policydef build_image_prompt_messages(@@ -9,13 +10,16 @@ def build_image_prompt_messages(stack: Stack,text_prompt: str,image_generation_enabled: bool,+ design_system: str | None = None,) -> list[ChatCompletionMessageParam]:image_policy = build_user_image_policy(image_generation_enabled)selected_stack = build_selected_stack_policy(stack)+ design_system_block = build_design_system_prompt_block(design_system)user_prompt = f"""Generate code for a web page that looks exactly like the provided screenshot(s).{selected_stack}+{design_system_block}## Replication instructionsdiff --git a/backend/prompts/create/text.py b/backend/prompts/create/text.pyindex 0dce5913..d3ff72e0 100644--- a/backend/prompts/create/text.py+++ b/backend/prompts/create/text.py@@ -2,6 +2,7 @@ from openai.types.chat import ChatCompletionMessageParamfrom prompts.prompt_types import Stackfrom prompts import system_prompt+from prompts.design_system import build_design_system_prompt_blockfrom prompts.policies import build_selected_stack_policy, build_user_image_policy@@ -9,13 +10,16 @@ def build_text_prompt_messages(text_prompt: str,stack: Stack,image_generation_enabled: bool,+ design_system: str | None = None,) -> list[ChatCompletionMessageParam]:image_policy = build_user_image_policy(image_generation_enabled)selected_stack = build_selected_stack_policy(stack)+ design_system_block = build_design_system_prompt_block(design_system)USER_PROMPT = f"""Generate UI for {text_prompt}.{selected_stack}+{design_system_block}# Instructionsdiff --git a/backend/prompts/create/video.py b/backend/prompts/create/video.pyindex b346f14d..061cb2e9 100644--- a/backend/prompts/create/video.py+++ b/backend/prompts/create/video.py@@ -1,6 +1,7 @@from openai.types.chat import ChatCompletionContentPartParam, ChatCompletionMessageParamfrom prompts.prompt_types import Stackfrom prompts import system_prompt+from prompts.design_system import build_design_system_prompt_blockfrom prompts.policies import build_selected_stack_policy, build_user_image_policy@@ -9,9 +10,11 @@ def build_video_prompt_messages(stack: Stack,text_prompt: str,image_generation_enabled: bool,+ design_system: str | None = None,) -> list[ChatCompletionMessageParam]:image_policy = build_user_image_policy(image_generation_enabled)selected_stack = build_selected_stack_policy(stack)+ design_system_block = build_design_system_prompt_block(design_system)user_text = f"""You have been given a video of a user interacting with a web app. You need to re-create the same app exactly such that the same user interactions will produce the same results in the app you build.@@ -27,6 +30,7 @@ def build_video_prompt_messages(Analyze this video and generate the code.{selected_stack}+ {design_system_block}"""if text_prompt.strip():user_text = user_text + "\n\nAdditional instructions: " + text_promptdiff --git a/backend/prompts/design_system.py b/backend/prompts/design_system.pynew file mode 100644index 00000000..d3c918c5--- /dev/null+++ b/backend/prompts/design_system.py@@ -0,0 +1,13 @@+def build_design_system_prompt_block(design_system: str | None) -> str:+ if not design_system or not design_system.strip():+ return ""++ return f"""+## Design system++If the design system conflicts with other instructions, prioritize the design system.++<design_system>+{design_system.strip()}+</design_system>+"""diff --git a/backend/prompts/pipeline.py b/backend/prompts/pipeline.pyindex 3d3b3eba..afdc372f 100644--- a/backend/prompts/pipeline.py+++ b/backend/prompts/pipeline.py@@ -17,6 +17,7 @@ async def build_prompt_messages(history: list[PromptHistoryMessage],file_state: dict[str, str] | None = None,image_generation_enabled: bool = True,+ design_system: str | None = None,) -> Prompt:plan = derive_prompt_construction_plan(stack=stack,@@ -32,6 +33,7 @@ async def build_prompt_messages(stack=stack,history=history,image_generation_enabled=image_generation_enabled,+ design_system=design_system,)if strategy == "update_from_file_snapshot":assert file_state is not None@@ -40,10 +42,12 @@ async def build_prompt_messages(prompt=prompt,file_state=file_state,image_generation_enabled=image_generation_enabled,+ design_system=design_system,)return build_create_prompt_from_input(input_mode,stack,prompt,image_generation_enabled,+ design_system,)diff --git a/backend/prompts/update/from_file_snapshot.py b/backend/prompts/update/from_file_snapshot.pyindex 0ad931ee..cc79be40 100644--- a/backend/prompts/update/from_file_snapshot.py+++ b/backend/prompts/update/from_file_snapshot.py@@ -3,6 +3,7 @@ from typing import castfrom openai.types.chat import ChatCompletionMessageParamfrom prompts import system_prompt+from prompts.design_system import build_design_system_prompt_blockfrom prompts.policies import build_selected_stack_policy, build_user_image_policyfrom prompts.prompt_types import Stack, UserTurnInputfrom prompts.message_builder import Prompt, build_history_message@@ -13,14 +14,18 @@ def build_update_prompt_from_file_snapshot(prompt: UserTurnInput,file_state: dict[str, str],image_generation_enabled: bool,+ design_system: str | None = None,) -> Prompt:path = file_state.get("path", "index.html")request_text = prompt.get("text", "").strip() or "Apply the requested update."selected_stack = build_selected_stack_policy(stack)image_policy = build_user_image_policy(image_generation_enabled)- bootstrap_text = f"""{selected_stack}--{image_policy}+ design_system_block = build_design_system_prompt_block(design_system)+ prompt_parts = [selected_stack, image_policy]+ if design_system_block:+ prompt_parts.append(design_system_block.strip())+ prompt_prefix = "\n\n".join(prompt_parts)+ bootstrap_text = f"""{prompt_prefix}You are editing an existing file.diff --git a/backend/prompts/update/from_history.py b/backend/prompts/update/from_history.pyindex 4fab1129..5ab6e444 100644--- a/backend/prompts/update/from_history.py+++ b/backend/prompts/update/from_history.py@@ -3,6 +3,7 @@ from typing import castfrom openai.types.chat import ChatCompletionMessageParamfrom prompts import system_prompt+from prompts.design_system import build_design_system_prompt_blockfrom prompts.policies import build_selected_stack_policy, build_user_image_policyfrom prompts.prompt_types import PromptHistoryMessage, Stackfrom prompts.message_builder import Prompt, build_history_message@@ -12,6 +13,7 @@ def build_update_prompt_from_history(stack: Stack,history: list[PromptHistoryMessage],image_generation_enabled: bool,+ design_system: str | None = None,) -> Prompt:first_user_index = next((index for index, item in enumerate(history) if item["role"] == "user"),@@ -31,11 +33,13 @@ def build_update_prompt_from_history(]selected_stack = build_selected_stack_policy(stack)image_policy = build_user_image_policy(image_generation_enabled)+ design_system_block = build_design_system_prompt_block(design_system)for index, item in enumerate(history):if index == first_user_index:- stack_prefix = f"""{selected_stack}--{image_policy}"""+ stack_prefix_parts = [selected_stack, image_policy]+ if design_system_block:+ stack_prefix_parts.append(design_system_block.strip())+ stack_prefix = "\n\n".join(stack_prefix_parts)user_text = item.get("text", "")prefixed_text = (f"{stack_prefix}\n\n{user_text}" if user_text.strip() else stack_prefixdiff --git a/backend/routes/design_systems.py b/backend/routes/design_systems.pynew file mode 100644index 00000000..3cf5bc38--- /dev/null+++ b/backend/routes/design_systems.py@@ -0,0 +1,165 @@+import json+import os+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, cast+from uuid import uuid4++from fastapi import APIRouter, HTTPException, Response+from pydantic import BaseModel++router = APIRouter()+++class DesignSystem(BaseModel):+ id: str+ name: str+ content: str+ createdAt: str+ updatedAt: str+++class CreateDesignSystemRequest(BaseModel):+ name: str+ content: str+++class UpdateDesignSystemRequest(BaseModel):+ name: str | None = None+ content: str | None = None+++def get_design_systems_file_path() -> Path:+ data_dir = os.environ.get("SCREENSHOT_TO_CODE_DATA_DIR")+ base_path = Path(data_dir).expanduser() if data_dir else Path.home() / ".screenshot-to-code"+ return base_path / "design-systems.json"+++def utc_timestamp() -> str:+ return datetime.now(timezone.utc).isoformat()+++def normalize_name(name: str) -> str:+ normalized = name.strip()+ if not normalized:+ raise HTTPException(status_code=400, detail="Design system name is required")+ return normalized+++def parse_design_system(raw_item: Any) -> DesignSystem | None:+ if not isinstance(raw_item, dict):+ return None++ try:+ return DesignSystem(+ id=str(raw_item["id"]),+ name=str(raw_item["name"]),+ content=str(raw_item.get("content", "")),+ createdAt=str(raw_item["createdAt"]),+ updatedAt=str(raw_item["updatedAt"]),+ )+ except KeyError:+ return None+++def read_design_systems() -> list[DesignSystem]:+ file_path = get_design_systems_file_path()+ if not file_path.exists():+ return []++ try:+ raw_items = cast(list[Any], json.loads(file_path.read_text(encoding="utf-8")))+ except json.JSONDecodeError as exc:+ raise HTTPException(+ status_code=500,+ detail="Design systems storage is not valid JSON",+ ) from exc++ if not isinstance(raw_items, list):+ raise HTTPException(+ status_code=500,+ detail="Design systems storage must contain a list",+ )++ design_systems: list[DesignSystem] = []+ for raw_item in raw_items:+ design_system = parse_design_system(raw_item)+ if design_system:+ design_systems.append(design_system)+ return design_systems+++def write_design_systems(design_systems: list[DesignSystem]) -> None:+ file_path = get_design_systems_file_path()+ file_path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = file_path.with_suffix(".json.tmp")+ serialized = json.dumps(+ [design_system.model_dump() for design_system in design_systems],+ indent=2,+ )+ tmp_path.write_text(f"{serialized}\n", encoding="utf-8")+ tmp_path.replace(file_path)++[email protected]("/api/design-systems")+async def list_design_systems() -> list[DesignSystem]:+ return read_design_systems()++[email protected]("/api/design-systems")+async def create_design_system(request: CreateDesignSystemRequest) -> DesignSystem:+ design_systems = read_design_systems()+ timestamp = utc_timestamp()+ design_system = DesignSystem(+ id=str(uuid4()),+ name=normalize_name(request.name),+ content=request.content,+ createdAt=timestamp,+ updatedAt=timestamp,+ )+ design_systems.append(design_system)+ write_design_systems(design_systems)+ return design_system++[email protected]("/api/design-systems/{design_system_id}")+async def update_design_system(+ design_system_id: str, request: UpdateDesignSystemRequest+) -> DesignSystem:+ design_systems = read_design_systems()+ for index, design_system in enumerate(design_systems):+ if design_system.id != design_system_id:+ continue++ updated = design_system.model_copy(+ update={+ "name": normalize_name(request.name)+ if request.name is not None+ else design_system.name,+ "content": request.content+ if request.content is not None+ else design_system.content,+ "updatedAt": utc_timestamp(),+ }+ )+ design_systems[index] = updated+ write_design_systems(design_systems)+ return updated++ raise HTTPException(status_code=404, detail="Design system not found")++[email protected]("/api/design-systems/{design_system_id}")+async def delete_design_system(design_system_id: str) -> Response:+ design_systems = read_design_systems()+ remaining = [+ design_system+ for design_system in design_systems+ if design_system.id != design_system_id+ ]++ if len(remaining) == len(design_systems):+ raise HTTPException(status_code=404, detail="Design system not found")++ write_design_systems(remaining)+ return Response(status_code=204)diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.pyindex 77e8337c..c988fd16 100644--- a/backend/routes/generate_code.py+++ b/backend/routes/generate_code.py@@ -236,6 +236,7 @@ class ExtractedParams:history: List[PromptHistoryMessage]file_state: Dict[str, str] | Noneoption_codes: List[str]+ design_system: str | None = Noneclass ParameterExtractionStage:@@ -322,6 +323,13 @@ class ParameterExtractionStage:else:option_codes.append(str(entry))+ raw_design_system = params.get("designSystem")+ design_system = (+ raw_design_system.strip()+ if isinstance(raw_design_system, str) and raw_design_system.strip()+ else None+ )+return ExtractedParams(stack=validated_stack,input_mode=validated_input_mode,@@ -335,6 +343,7 @@ class ParameterExtractionStage:history=history,file_state=file_state,option_codes=option_codes,+ design_system=design_system,)def _get_from_settings_dialog_or_env(@@ -464,6 +473,7 @@ class PromptCreationStage:history=extracted_params.history,file_state=extracted_params.file_state,image_generation_enabled=extracted_params.should_generate_images,+ design_system=extracted_params.design_system,)print_prompt_preview(prompt_messages)diff --git a/backend/tests/test_design_systems.py b/backend/tests/test_design_systems.pynew file mode 100644index 00000000..5accc29a--- /dev/null+++ b/backend/tests/test_design_systems.py@@ -0,0 +1,46 @@+import json+from pathlib import Path++import pytest++from routes.design_systems import (+ CreateDesignSystemRequest,+ UpdateDesignSystemRequest,+ create_design_system,+ delete_design_system,+ get_design_systems_file_path,+ list_design_systems,+ update_design_system,+)+++async def test_design_system_crud_persists_to_backend_file(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("SCREENSHOT_TO_CODE_DATA_DIR", str(tmp_path))++ assert await list_design_systems() == []++ created = await create_design_system(+ CreateDesignSystemRequest(name="Legal SaaS", content="Use .mockup-frame")+ )++ assert created.name == "Legal SaaS"+ assert created.content == "Use .mockup-frame"+ assert get_design_systems_file_path().exists()++ raw_items = json.loads(get_design_systems_file_path().read_text(encoding="utf-8"))+ assert raw_items[0]["id"] == created.id++ updated = await update_design_system(+ created.id,+ UpdateDesignSystemRequest(name="Legal Marketing", content="Use Roboto"),+ )++ assert updated.name == "Legal Marketing"+ assert updated.content == "Use Roboto"++ await delete_design_system(created.id)++ assert await list_design_systems() == []diff --git a/backend/tests/test_parameter_extraction_stage.py b/backend/tests/test_parameter_extraction_stage.pyindex 6486f603..149dfcc5 100644--- a/backend/tests/test_parameter_extraction_stage.py+++ b/backend/tests/test_parameter_extraction_stage.py@@ -37,3 +37,19 @@ async def test_extracts_gemini_api_key_from_env_when_not_in_request(monkeypatch:)assert extracted.gemini_api_key == "gemini-from-env"+++async def test_extracts_design_system_from_request() -> None:+ stage = ParameterExtractionStage(AsyncMock())++ extracted = await stage.extract_and_validate(+ {+ "generatedCodeConfig": "html_css",+ "inputMode": "text",+ "prompt": {"text": "hello"},+ "designSystem": " Reuse .mockup-frame ",+ }+ )++ assert extracted.design_system == "Reuse .mockup-frame"diff --git a/backend/tests/test_prompts.py b/backend/tests/test_prompts.pyindex 5568f700..cd024f1a 100644--- a/backend/tests/test_prompts.py+++ b/backend/tests/test_prompts.py@@ -101,6 +101,35 @@ class TestCreatePrompt:)assert plan["construction_strategy"] == "create_from_input"+ @pytest.mark.asyncio+ async def test_create_prompt_includes_design_system(self) -> None:+ messages = await build_prompt_messages(+ stack="html_css",+ input_mode="image",+ generation_type="create",+ prompt={+ "text": "Make a marketing mockup",+ "images": [self.TEST_IMAGE_URL],+ "videos": [],+ },+ history=[],+ image_generation_enabled=True,+ design_system="Reuse .mockup-frame and keep border radius 0.",+ )++ user_content = messages[1].get("content")+ assert isinstance(user_content, list)+ text_part = next(+ part+ for part in user_content+ if isinstance(part, dict) and part.get("type") == "text"+ )+ text = text_part.get("text")+ assert isinstance(text, str)++ assert "Reusable design system" in text+ assert "Reuse .mockup-frame" in text+def test_plan_update_with_history_uses_history_strategy(self) -> None:plan = derive_prompt_construction_plan(stack=self.TEST_STACK,diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex ae001ac7..1361a3f6 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,6 +1,7 @@-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { generateCode } from "./generateCode";import { AppState, AppTheme, EditorTheme, Settings } from "./types";+import { NEW_DESIGN_SYSTEM_CONTENT } from "./lib/design-systems";import { IS_RUNNING_ON_CLOUD } from "./config";import { PicoBadge } from "./components/messages/PicoBadge";import { OnboardingNote } from "./components/messages/OnboardingNote";@@ -24,6 +25,7 @@ import {// import TipLink from "./components/messages/TipLink";import { useAppStore } from "./store/app-store";import { useProjectStore } from "./store/project-store";+import { useDesignSystems } from "./hooks/useDesignSystems";import { removeHighlight } from "./components/select-and-edit/utils";import Sidebar from "./components/sidebar/Sidebar";import IconStrip from "./components/sidebar/IconStrip";@@ -31,6 +33,7 @@ import HistoryDisplay from "./components/history/HistoryDisplay";import PreviewPane from "./components/preview/PreviewPane";import StartPane from "./components/start-pane/StartPane";import SettingsTab from "./components/settings/SettingsTab";+import DesignSystemsModal from "./components/settings/DesignSystemsModal";import { Commit } from "./components/commits/types";import { createCommit } from "./components/commits/utils";@@ -91,6 +94,7 @@ function App() {editorTheme: EditorTheme.COBALT,generatedCodeConfig: Stack.HTML_TAILWIND,codeGenerationModel: CodeGenerationModel.CLAUDE_4_5_OPUS_2025_11_01,+ selectedDesignSystemId: null,// Only relevant for hosted versionisTermOfServiceAccepted: false,},@@ -109,6 +113,51 @@ function App() {const [isHistoryOpen, setIsHistoryOpen] = useState(false);const [isSettingsOpen, setIsSettingsOpen] = useState(false);const [mobilePane, setMobilePane] = useState<"preview" | "chat">("preview");+ const [isDesignSystemsModalOpen, setIsDesignSystemsModalOpen] =+ useState(false);+ const [designSystemsModalInitialId, setDesignSystemsModalInitialId] =+ useState<string | null>(null);+ const {+ designSystems,+ isLoading: areDesignSystemsLoading,+ createDesignSystem,+ updateDesignSystem,+ deleteDesignSystem,+ } = useDesignSystems();++ const setSelectedDesignSystemId = useCallback(+ (id: string | null) => {+ setSettings((prev) => ({ ...prev, selectedDesignSystemId: id }));+ },+ [setSettings]+ );++ const openDesignSystemsManager = useCallback((focusedId?: string | null) => {+ setDesignSystemsModalInitialId(focusedId ?? null);+ setIsDesignSystemsModalOpen(true);+ }, []);++ const handleAddNewDesignSystem = useCallback(async () => {+ try {+ const isFirst = designSystems.length === 0;+ const created = await createDesignSystem({+ name: `Design system ${designSystems.length + 1}`,+ content: NEW_DESIGN_SYSTEM_CONTENT,+ });+ if (isFirst) {+ setSelectedDesignSystemId(created.id);+ }+ openDesignSystemsManager(created.id);+ } catch (error) {+ console.error("Failed to create design system", error);+ toast.error("Could not create design system.");+ }+ }, [+ createDesignSystem,+ designSystems.length,+ openDesignSystemsManager,+ setSelectedDesignSystemId,+ ]);const showSelectAndEditFeature =settings.generatedCodeConfig === Stack.HTML_TAILWIND ||settings.generatedCodeConfig === Stack.HTML_CSS;@@ -128,6 +177,35 @@ function App() {}}, [settings.generatedCodeConfig, setSettings]);+ useEffect(() => {+ if (!("selectedDesignSystemId" in settings)) {+ setSettings((prev) => ({+ ...prev,+ selectedDesignSystemId: null,+ }));+ }+ }, [settings, setSettings]);++ useEffect(() => {+ if (+ settings.selectedDesignSystemId &&+ !areDesignSystemsLoading &&+ !designSystems.some(+ (designSystem) => designSystem.id === settings.selectedDesignSystemId+ )+ ) {+ setSettings((prev) => ({+ ...prev,+ selectedDesignSystemId: null,+ }));+ }+ }, [+ areDesignSystemsLoading,+ designSystems,+ settings.selectedDesignSystemId,+ setSettings,+ ]);+useEffect(() => {const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");const applyTheme = () => {@@ -230,8 +308,16 @@ function App() {const { variantHistory, ...requestParams } = params;+ const selectedDesignSystem = designSystems.find(+ (designSystem) => designSystem.id === settings.selectedDesignSystemId+ );+// Merge settings with params- const updatedParams = { ...requestParams, ...settings };+ const updatedParams = {+ ...requestParams,+ ...settings,+ designSystem: selectedDesignSystem?.content ?? null,+ };// Use 4 variants for create, 2 for edits to match backend counts// and avoid a flash when the backend sends the actual variant count@@ -764,6 +850,13 @@ function App() {doUpdate={doUpdate}regenerate={regenerate}cancelCodeGeneration={cancelCodeGeneration}+ designSystem={{+ designSystems,+ selectedDesignSystemId: settings.selectedDesignSystemId,+ setSelectedDesignSystemId,+ onAddNew: handleAddNewDesignSystem,+ onManage: () => openDesignSystemsManager(),+ }}onOpenVersions={() => {setIsHistoryOpen(true);setMobilePane("chat");@@ -800,6 +893,9 @@ function App() {importFromCode={importFromCode}settings={settings}setSettings={setSettings}+ designSystems={designSystems}+ onAddNewDesignSystem={handleAddNewDesignSystem}+ onManageDesignSystems={() => openDesignSystemsManager()}/>)}@@ -815,6 +911,18 @@ function App() {</>)}</main>++ <DesignSystemsModal+ open={isDesignSystemsModalOpen}+ onOpenChange={setIsDesignSystemsModalOpen}+ designSystems={designSystems}+ selectedDesignSystemId={settings.selectedDesignSystemId}+ setSelectedDesignSystemId={setSelectedDesignSystemId}+ initialEditingId={designSystemsModalInitialId}+ createDesignSystem={createDesignSystem}+ updateDesignSystem={updateDesignSystem}+ deleteDesignSystem={deleteDesignSystem}+ /></div>);}diff --git a/frontend/src/components/recording/ScreenRecorder.tsx b/frontend/src/components/recording/ScreenRecorder.tsxindex 5fa74cef..34f3c3a1 100644--- a/frontend/src/components/recording/ScreenRecorder.tsx+++ b/frontend/src/components/recording/ScreenRecorder.tsx@@ -5,6 +5,7 @@ import { blobToBase64DataUrl } from "./utils";import fixWebmDuration from "webm-duration-fix";import toast from "react-hot-toast";import OutputSettingsSection from "../settings/OutputSettingsSection";+import { DesignSystemSelectorProps } from "../settings/DesignSystemSelector";import { Stack } from "../../lib/stacks";interface Props {@@ -16,6 +17,7 @@ interface Props {) => void;stack: Stack;setStack: (stack: Stack) => void;+ designSystem?: DesignSystemSelectorProps;}function ScreenRecorder({@@ -24,6 +26,7 @@ function ScreenRecorder({generateCode,stack,setStack,+ designSystem,}: Props) {const [mediaStream, setMediaStream] = useState<MediaStream | null>(null);const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(@@ -135,6 +138,7 @@ function ScreenRecorder({<OutputSettingsSectionstack={stack}setStack={setStack}+ designSystem={designSystem}/></div><div className="flex gap-x-2 w-full">diff --git a/frontend/src/components/settings/DesignSystemSelector.tsx b/frontend/src/components/settings/DesignSystemSelector.tsxnew file mode 100644index 00000000..34e0deaa--- /dev/null+++ b/frontend/src/components/settings/DesignSystemSelector.tsx@@ -0,0 +1,133 @@+import { LuChevronDown, LuPalette } from "react-icons/lu";+import { DesignSystem } from "../../types";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+} from "../ui/select";++const NO_DESIGN_SYSTEM = "__none__";+const ADD_NEW = "__add_new__";+const MANAGE = "__manage__";++export interface DesignSystemSelectorProps {+ designSystems: DesignSystem[];+ selectedDesignSystemId: string | null;+ setSelectedDesignSystemId: (id: string | null) => void;+ onAddNew: () => void;+ onManage: () => void;+ disabled?: boolean;+ compact?: boolean;+}++function DesignSystemSelector({+ designSystems,+ selectedDesignSystemId,+ setSelectedDesignSystemId,+ onAddNew,+ onManage,+ disabled = false,+ compact = false,+}: DesignSystemSelectorProps) {+ const handleValueChange = (value: string) => {+ if (value === ADD_NEW) {+ onAddNew();+ return;+ }+ if (value === MANAGE) {+ onManage();+ return;+ }+ setSelectedDesignSystemId(value === NO_DESIGN_SYSTEM ? null : value);+ };++ const selectedDesignSystem = designSystems.find(+ (item) => item.id === selectedDesignSystemId+ );+ const hasSelection = selectedDesignSystem !== undefined;++ return (+ <Select+ value={selectedDesignSystemId ?? NO_DESIGN_SYSTEM}+ onValueChange={handleValueChange}+ disabled={disabled}+ >+ {compact ? (+ <SelectTrigger+ className={+ hasSelection+ ? "flex h-7 w-auto items-center gap-1.5 rounded-full border border-gray-200 bg-white px-2.5 py-0 text-xs font-medium text-gray-700 shadow-none hover:bg-gray-50 focus:ring-0 focus:ring-offset-0 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-200 dark:hover:bg-zinc-700 [&>svg:last-child]:hidden"+ : "flex h-7 w-7 items-center justify-center rounded-lg border-0 bg-transparent p-0 text-gray-400 shadow-none hover:bg-gray-100 hover:text-gray-600 focus:ring-0 focus:ring-offset-0 dark:text-zinc-500 dark:hover:bg-zinc-800 dark:hover:text-zinc-300 [&>svg:last-child]:hidden"+ }+ data-testid="design-system-select"+ aria-label={+ hasSelection+ ? `Design system: ${selectedDesignSystem.name}`+ : "Add a design system"+ }+ title={+ hasSelection+ ? `Design system: ${selectedDesignSystem.name}`+ : "Add a design system"+ }+ >+ <LuPalette className="h-3.5 w-3.5 shrink-0" />+ {hasSelection && (+ <>+ <span className="max-w-[120px] truncate">+ {selectedDesignSystem.name}+ </span>+ <LuChevronDown className="h-3 w-3 shrink-0 opacity-60" />+ </>+ )}+ </SelectTrigger>+ ) : hasSelection ? (+ <div className="grid grid-cols-3 items-center gap-4 text-sm">+ <span>Design system:</span>+ <SelectTrigger+ className="col-span-2"+ data-testid="design-system-select"+ >+ <SelectValue placeholder="No design system" />+ </SelectTrigger>+ </div>+ ) : (+ <div className="flex justify-end text-xs">+ <SelectTrigger+ className="h-auto w-auto justify-start gap-1 border-0 bg-transparent px-0 py-0 text-gray-500 shadow-none hover:text-gray-700 focus:ring-0 focus:ring-offset-0 dark:text-zinc-400 dark:hover:text-zinc-200 [&>svg]:hidden"+ data-testid="design-system-select"+ >+ <span>+ Add design system</span>+ </SelectTrigger>+ </div>+ )}+ <SelectContent>+ <SelectGroup>+ <SelectItem value={NO_DESIGN_SYSTEM}>No design system</SelectItem>+ {designSystems.map((designSystem) => (+ <SelectItem key={designSystem.id} value={designSystem.id}>+ {designSystem.name}+ </SelectItem>+ ))}+ </SelectGroup>+ <SelectSeparator />+ <SelectGroup>+ <SelectItem value={ADD_NEW} data-testid="design-system-add-new">+ + New design system…+ </SelectItem>+ {designSystems.length > 0 && (+ <SelectItem value={MANAGE} data-testid="design-system-manage">+ Manage design systems…+ </SelectItem>+ )}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+}++export default DesignSystemSelector;diff --git a/frontend/src/components/settings/DesignSystemsManager.tsx b/frontend/src/components/settings/DesignSystemsManager.tsxnew file mode 100644index 00000000..f2ada647--- /dev/null+++ b/frontend/src/components/settings/DesignSystemsManager.tsx@@ -0,0 +1,288 @@+import { useEffect, useMemo, useState } from "react";+import toast from "react-hot-toast";+import { DesignSystem } from "../../types";+import { NEW_DESIGN_SYSTEM_CONTENT } from "../../lib/design-systems";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Textarea } from "../ui/textarea";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "../ui/select";++interface Props {+ designSystems: DesignSystem[];+ selectedDesignSystemId: string | null;+ setSelectedDesignSystemId: (id: string | null) => void;+ initialEditingId?: string | null;+ createDesignSystem: (payload: {+ name: string;+ content: string;+ }) => Promise<DesignSystem>;+ updateDesignSystem: (+ id: string,+ payload: { name?: string; content?: string }+ ) => Promise<DesignSystem>;+ deleteDesignSystem: (id: string) => Promise<void>;+}++function DesignSystemsManager({+ designSystems,+ selectedDesignSystemId,+ setSelectedDesignSystemId,+ initialEditingId,+ createDesignSystem,+ updateDesignSystem,+ deleteDesignSystem,+}: Props) {+ const [editingId, setEditingId] = useState<string | null>(+ initialEditingId ?? null+ );+ const [draftName, setDraftName] = useState("");+ const [draftContent, setDraftContent] = useState("");+ const [isSaving, setIsSaving] = useState(false);++ const editingDesignSystem = useMemo(+ () => designSystems.find((item) => item.id === editingId) ?? null,+ [designSystems, editingId]+ );++ useEffect(() => {+ if (initialEditingId) {+ setEditingId(initialEditingId);+ }+ }, [initialEditingId]);++ useEffect(() => {+ if (!editingId && designSystems.length > 0) {+ setEditingId(selectedDesignSystemId ?? designSystems[0].id);+ }+ }, [designSystems, editingId, selectedDesignSystemId]);++ useEffect(() => {+ if (!editingDesignSystem) {+ setDraftName("");+ setDraftContent("");+ return;+ }++ setDraftName(editingDesignSystem.name);+ setDraftContent(editingDesignSystem.content);+ }, [editingDesignSystem]);++ const isDirty =+ editingDesignSystem !== null &&+ (draftName !== editingDesignSystem.name ||+ draftContent !== editingDesignSystem.content);++ const isDefault =+ editingDesignSystem !== null &&+ selectedDesignSystemId === editingDesignSystem.id;++ async function handleCreate() {+ try {+ setIsSaving(true);+ const created = await createDesignSystem({+ name: `Design system ${designSystems.length + 1}`,+ content: NEW_DESIGN_SYSTEM_CONTENT,+ });+ setEditingId(created.id);+ toast.success("Design system created.");+ } catch (error) {+ console.error("Failed to create design system", error);+ toast.error("Could not create design system.");+ } finally {+ setIsSaving(false);+ }+ }++ async function handleSave() {+ if (!editingDesignSystem) {+ return;+ }++ const name = draftName.trim();+ if (!name) {+ toast.error("Design system name is required.");+ return;+ }++ try {+ setIsSaving(true);+ await updateDesignSystem(editingDesignSystem.id, {+ name,+ content: draftContent,+ });+ toast.success("Design system saved.");+ } catch (error) {+ console.error("Failed to save design system", error);+ toast.error("Could not save design system.");+ } finally {+ setIsSaving(false);+ }+ }++ async function handleDelete() {+ if (!editingDesignSystem) {+ return;+ }++ if (+ !window.confirm(+ `Delete "${editingDesignSystem.name}"? This cannot be undone.`+ )+ ) {+ return;+ }++ try {+ setIsSaving(true);+ await deleteDesignSystem(editingDesignSystem.id);+ if (selectedDesignSystemId === editingDesignSystem.id) {+ setSelectedDesignSystemId(null);+ }+ const next = designSystems.find(+ (item) => item.id !== editingDesignSystem.id+ );+ setEditingId(next?.id ?? null);+ toast.success("Design system deleted.");+ } catch (error) {+ console.error("Failed to delete design system", error);+ toast.error("Could not delete design system.");+ } finally {+ setIsSaving(false);+ }+ }++ return (+ <div className="space-y-5">+ <div className="flex gap-2">+ <Select+ value={editingId ?? ""}+ onValueChange={setEditingId}+ disabled={designSystems.length === 0}+ >+ <SelectTrigger+ className="flex-1"+ data-testid="manage-design-system-select"+ >+ <SelectValue placeholder="No design systems yet" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {designSystems.map((designSystem) => (+ <SelectItem key={designSystem.id} value={designSystem.id}>+ {designSystem.name}+ {selectedDesignSystemId === designSystem.id && (+ <span className="ml-2 text-xs text-violet-600 dark:text-violet-400">+ Default+ </span>+ )}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ <Button+ type="button"+ variant="outline"+ onClick={handleCreate}+ disabled={isSaving}+ >+ + New+ </Button>+ </div>++ {editingDesignSystem ? (+ <div className="space-y-4">+ <div>+ <label+ htmlFor="design-system-name"+ className="mb-1.5 block text-xs font-medium text-gray-700 dark:text-zinc-300"+ >+ Name+ </label>+ <div className="flex items-center gap-2">+ <Input+ id="design-system-name"+ value={draftName}+ onChange={(event) => setDraftName(event.target.value)}+ placeholder="e.g. Marketing site"+ data-testid="design-system-name"+ />+ {isDefault && (+ <span className="shrink-0 rounded-full bg-violet-100 px-2 py-0.5 text-xs font-medium text-violet-700 dark:bg-violet-900/40 dark:text-violet-300">+ Default+ </span>+ )}+ </div>+ </div>++ <div>+ <label+ htmlFor="design-system-content"+ className="mb-1.5 block text-xs font-medium text-gray-700 dark:text-zinc-300"+ >+ Instructions+ </label>+ <Textarea+ id="design-system-content"+ value={draftContent}+ onChange={(event) => setDraftContent(event.target.value)}+ placeholder="Fill in details about colors, fonts, components, and layout preferences..."+ className="min-h-[240px] font-mono text-xs"+ data-testid="design-system-content"+ />+ </div>++ <div className="flex items-center justify-between border-t border-gray-100 pt-4 dark:border-zinc-800">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={handleDelete}+ disabled={isSaving}+ className="text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/40 dark:hover:text-red-300"+ >+ Delete+ </Button>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() =>+ setSelectedDesignSystemId(+ isDefault ? null : editingDesignSystem.id+ )+ }+ disabled={isSaving}+ >+ {isDefault ? "Remove as default" : "Set as default"}+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={handleSave}+ disabled={isSaving || !isDirty}+ >+ {isDirty ? "Save changes" : "Saved"}+ </Button>+ </div>+ </div>+ </div>+ ) : (+ <div className="rounded-md border border-dashed border-gray-200 px-4 py-10 text-center text-sm text-gray-500 dark:border-zinc-700 dark:text-zinc-400">+ No design systems yet. Click <span className="font-medium">+ New</span>{" "}+ to create one.+ </div>+ )}+ </div>+ );+}++export default DesignSystemsManager;diff --git a/frontend/src/components/settings/DesignSystemsModal.tsx b/frontend/src/components/settings/DesignSystemsModal.tsxnew file mode 100644index 00000000..4a74d899--- /dev/null+++ b/frontend/src/components/settings/DesignSystemsModal.tsx@@ -0,0 +1,64 @@+import { DesignSystem } from "../../types";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "../ui/dialog";+import DesignSystemsManager from "./DesignSystemsManager";++interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ designSystems: DesignSystem[];+ selectedDesignSystemId: string | null;+ setSelectedDesignSystemId: (id: string | null) => void;+ initialEditingId: string | null;+ createDesignSystem: (payload: {+ name: string;+ content: string;+ }) => Promise<DesignSystem>;+ updateDesignSystem: (+ id: string,+ payload: { name?: string; content?: string }+ ) => Promise<DesignSystem>;+ deleteDesignSystem: (id: string) => Promise<void>;+}++function DesignSystemsModal({+ open,+ onOpenChange,+ designSystems,+ selectedDesignSystemId,+ setSelectedDesignSystemId,+ initialEditingId,+ createDesignSystem,+ updateDesignSystem,+ deleteDesignSystem,+}: Props) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Design Systems</DialogTitle>+ <DialogDescription>+ Define color, typography, and layout rules applied to every+ generation.+ </DialogDescription>+ </DialogHeader>+ <DesignSystemsManager+ designSystems={designSystems}+ selectedDesignSystemId={selectedDesignSystemId}+ setSelectedDesignSystemId={setSelectedDesignSystemId}+ initialEditingId={initialEditingId}+ createDesignSystem={createDesignSystem}+ updateDesignSystem={updateDesignSystem}+ deleteDesignSystem={deleteDesignSystem}+ />+ </DialogContent>+ </Dialog>+ );+}++export default DesignSystemsModal;diff --git a/frontend/src/components/settings/GenerationSettings.tsx b/frontend/src/components/settings/GenerationSettings.tsxindex 56df5ee1..958e8358 100644--- a/frontend/src/components/settings/GenerationSettings.tsx+++ b/frontend/src/components/settings/GenerationSettings.tsx@@ -1,18 +1,24 @@import React from "react";import { useAppStore } from "../../store/app-store";import { useProjectStore } from "../../store/project-store";-import { AppState, Settings } from "../../types";+import { AppState, DesignSystem, Settings } from "../../types";import OutputSettingsSection from "./OutputSettingsSection";import { Stack } from "../../lib/stacks";interface GenerationSettingsProps {settings: Settings;setSettings: React.Dispatch<React.SetStateAction<Settings>>;+ designSystems?: DesignSystem[];+ onAddNewDesignSystem: () => void;+ onManageDesignSystems: () => void;}export const GenerationSettings: React.FC<GenerationSettingsProps> = ({settings,setSettings,+ designSystems = [],+ onAddNewDesignSystem,+ onManageDesignSystems,}) => {const { appState } = useAppStore();const { inputMode } = useProjectStore();@@ -24,6 +30,13 @@ export const GenerationSettings: React.FC<GenerationSettingsProps> = ({}));}+ function setSelectedDesignSystemId(id: string | null) {+ setSettings((prev: Settings) => ({+ ...prev,+ selectedDesignSystemId: id,+ }));+ }+const shouldDisableUpdates =appState === AppState.CODING || appState === AppState.CODE_READY;@@ -33,12 +46,17 @@ export const GenerationSettings: React.FC<GenerationSettingsProps> = ({}return (- <div className="flex flex-col gap-y-2">- <OutputSettingsSection- stack={settings.generatedCodeConfig}- setStack={setStack}- shouldDisableUpdates={shouldDisableUpdates}- />- </div>+ <OutputSettingsSection+ stack={settings.generatedCodeConfig}+ setStack={setStack}+ shouldDisableUpdates={shouldDisableUpdates}+ designSystem={{+ designSystems,+ selectedDesignSystemId: settings.selectedDesignSystemId,+ setSelectedDesignSystemId,+ onAddNew: onAddNewDesignSystem,+ onManage: onManageDesignSystems,+ }}+ />);};diff --git a/frontend/src/components/settings/OutputSettingsSection.tsx b/frontend/src/components/settings/OutputSettingsSection.tsxindex 0f78cede..001df345 100644--- a/frontend/src/components/settings/OutputSettingsSection.tsx+++ b/frontend/src/components/settings/OutputSettingsSection.tsx@@ -8,12 +8,16 @@ import {} from "../ui/select";import { Stack } from "../../lib/stacks";import StackLabel from "../core/StackLabel";+import DesignSystemSelector, {+ DesignSystemSelectorProps,+} from "./DesignSystemSelector";interface Props {stack: Stack | undefined;setStack: (config: Stack) => void;label?: string;shouldDisableUpdates?: boolean;+ designSystem?: DesignSystemSelectorProps;}function OutputSettingsSection({@@ -21,6 +25,7 @@ function OutputSettingsSection({setStack,label = "Stack:",shouldDisableUpdates = false,+ designSystem,}: Props) {return (<div className="flex flex-col gap-y-2 justify-between text-sm">@@ -51,6 +56,9 @@ function OutputSettingsSection({</SelectContent></Select></div>+ {designSystem && (+ <DesignSystemSelector {...designSystem} />+ )}</div>);}diff --git a/frontend/src/components/sidebar/Sidebar.tsx b/frontend/src/components/sidebar/Sidebar.tsxindex 823d8cb2..85391be7 100644--- a/frontend/src/components/sidebar/Sidebar.tsx+++ b/frontend/src/components/sidebar/Sidebar.tsx@@ -14,6 +14,9 @@ import ImageLightbox from "../ImageLightbox";import { Commit } from "../commits/types";import { removeHighlight } from "../select-and-edit/utils";import { CodeGenerationModel } from "../../lib/models";+import DesignSystemSelector, {+ DesignSystemSelectorProps,+} from "../settings/DesignSystemSelector";interface SidebarProps {showSelectAndEditFeature: boolean;@@ -21,6 +24,7 @@ interface SidebarProps {regenerate: () => void;cancelCodeGeneration: () => void;onOpenVersions: () => void;+ designSystem: DesignSystemSelectorProps;}const MAX_UPDATE_IMAGES = 5;@@ -70,6 +74,7 @@ function Sidebar({regenerate,cancelCodeGeneration,onOpenVersions,+ designSystem,}: SidebarProps) {const textareaRef = useRef<HTMLTextAreaElement>(null);const middlePaneRef = useRef<HTMLDivElement>(null);@@ -241,7 +246,7 @@ function Sidebar({// Reset error expanded state when variant changesuseEffect(() => {setIsErrorExpanded(false);- }, [head, commits[head || ""]?.selectedVariantIndex]);+ }, [head, selectedVariantIndex]);// Reset prompt expanded state when commit changes and detect clampinguseEffect(() => {@@ -566,6 +571,7 @@ function Sidebar({<LuMousePointerClick className="w-[18px] h-[18px]" /></button>)}+ <DesignSystemSelector {...designSystem} compact /></div><buttononClick={() => doUpdate(updateInstruction)}diff --git a/frontend/src/components/start-pane/StartPane.tsx b/frontend/src/components/start-pane/StartPane.tsxindex 3f79c117..36c831b5 100644--- a/frontend/src/components/start-pane/StartPane.tsx+++ b/frontend/src/components/start-pane/StartPane.tsx@@ -1,5 +1,5 @@import React from "react";-import { Settings } from "../../types";+import { DesignSystem, Settings } from "../../types";import { Stack } from "../../lib/stacks";import UnifiedInputPane from "../unified-input/UnifiedInputPane";@@ -13,6 +13,9 @@ interface Props {importFromCode: (code: string, stack: Stack) => void;settings: Settings;setSettings: React.Dispatch<React.SetStateAction<Settings>>;+ designSystems: DesignSystem[];+ onAddNewDesignSystem: () => void;+ onManageDesignSystems: () => void;}const StartPane: React.FC<Props> = ({@@ -21,6 +24,9 @@ const StartPane: React.FC<Props> = ({importFromCode,settings,setSettings,+ designSystems,+ onAddNewDesignSystem,+ onManageDesignSystems,}) => {return (<div className="flex flex-col justify-center items-center py-8">@@ -30,6 +36,9 @@ const StartPane: React.FC<Props> = ({importFromCode={importFromCode}settings={settings}setSettings={setSettings}+ designSystems={designSystems}+ onAddNewDesignSystem={onAddNewDesignSystem}+ onManageDesignSystems={onManageDesignSystems}/></div>);diff --git a/frontend/src/components/unified-input/UnifiedInputPane.tsx b/frontend/src/components/unified-input/UnifiedInputPane.tsxindex 186b70f0..203ea290 100644--- a/frontend/src/components/unified-input/UnifiedInputPane.tsx+++ b/frontend/src/components/unified-input/UnifiedInputPane.tsx@@ -1,11 +1,12 @@import React, { useState } from "react";import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";import { Stack } from "../../lib/stacks";-import { Settings } from "../../types";+import { DesignSystem, Settings } from "../../types";import UploadTab from "./tabs/UploadTab";import UrlTab from "./tabs/UrlTab";import TextTab from "./tabs/TextTab";import ImportTab from "./tabs/ImportTab";+import { DesignSystemSelectorProps } from "../settings/DesignSystemSelector";interface Props {doCreate: (@@ -17,6 +18,9 @@ interface Props {importFromCode: (code: string, stack: Stack) => void;settings: Settings;setSettings: React.Dispatch<React.SetStateAction<Settings>>;+ designSystems: DesignSystem[];+ onAddNewDesignSystem: () => void;+ onManageDesignSystems: () => void;}type InputTab = "upload" | "url" | "text" | "import";@@ -27,6 +31,9 @@ function UnifiedInputPane({importFromCode,settings,setSettings,+ designSystems,+ onAddNewDesignSystem,+ onManageDesignSystems,}: Props) {const [activeTab, setActiveTab] = useState<InputTab>("upload");@@ -37,6 +44,21 @@ function UnifiedInputPane({}));}+ function setSelectedDesignSystemId(id: string | null) {+ setSettings((prev: Settings) => ({+ ...prev,+ selectedDesignSystemId: id,+ }));+ }++ const designSystemSelectorProps: DesignSystemSelectorProps = {+ designSystems,+ selectedDesignSystemId: settings.selectedDesignSystemId,+ setSelectedDesignSystemId,+ onAddNew: onAddNewDesignSystem,+ onManage: onManageDesignSystems,+ };+return (<div className="w-full max-w-4xl mx-auto px-4"><Tabs@@ -84,6 +106,7 @@ function UnifiedInputPane({doCreate={doCreate}stack={settings.generatedCodeConfig}setStack={setStack}+ designSystem={designSystemSelectorProps}/></TabsContent>@@ -93,6 +116,7 @@ function UnifiedInputPane({screenshotOneApiKey={settings.screenshotOneApiKey}stack={settings.generatedCodeConfig}setStack={setStack}+ designSystem={designSystemSelectorProps}/></TabsContent>@@ -101,6 +125,7 @@ function UnifiedInputPane({doCreateFromText={doCreateFromText}stack={settings.generatedCodeConfig}setStack={setStack}+ designSystem={designSystemSelectorProps}/></TabsContent>diff --git a/frontend/src/components/unified-input/tabs/TextTab.tsx b/frontend/src/components/unified-input/tabs/TextTab.tsxindex 4d162a21..1c7c249f 100644--- a/frontend/src/components/unified-input/tabs/TextTab.tsx+++ b/frontend/src/components/unified-input/tabs/TextTab.tsx@@ -3,12 +3,14 @@ import { Button } from "../../ui/button";import { Textarea } from "../../ui/textarea";import toast from "react-hot-toast";import OutputSettingsSection from "../../settings/OutputSettingsSection";+import { DesignSystemSelectorProps } from "../../settings/DesignSystemSelector";import { Stack } from "../../../lib/stacks";interface Props {doCreateFromText: (text: string) => void;stack: Stack;setStack: (stack: Stack) => void;+ designSystem: DesignSystemSelectorProps;}const EXAMPLE_PROMPTS = [@@ -18,7 +20,7 @@ const EXAMPLE_PROMPTS = ["A music streaming app with now-playing, recommended playlists, and recent listens",];-function TextTab({ doCreateFromText, stack, setStack }: Props) {+function TextTab({ doCreateFromText, stack, setStack, designSystem }: Props) {const [text, setText] = useState("");const textareaRef = useRef<HTMLTextAreaElement>(null);@@ -106,6 +108,7 @@ function TextTab({ doCreateFromText, stack, setStack }: Props) {<OutputSettingsSectionstack={stack}setStack={setStack}+ designSystem={designSystem}/><Buttondiff --git a/frontend/src/components/unified-input/tabs/UploadTab.tsx b/frontend/src/components/unified-input/tabs/UploadTab.tsxindex 7096f15e..3c848908 100644--- a/frontend/src/components/unified-input/tabs/UploadTab.tsx+++ b/frontend/src/components/unified-input/tabs/UploadTab.tsx@@ -6,6 +6,7 @@ import { Button } from "../../ui/button";import { ScreenRecorderState } from "../../../types";import ScreenRecorder from "../../recording/ScreenRecorder";import OutputSettingsSection from "../../settings/OutputSettingsSection";+import { DesignSystemSelectorProps } from "../../settings/DesignSystemSelector";import { Stack } from "../../../lib/stacks";function fileToDataURL(file: File): Promise<string> {@@ -48,9 +49,10 @@ interface Props {) => void;stack: Stack;setStack: (stack: Stack) => void;+ designSystem: DesignSystemSelectorProps;}-function UploadTab({ doCreate, stack, setStack }: Props) {+function UploadTab({ doCreate, stack, setStack, designSystem }: Props) {const [files, setFiles] = useState<FileWithPreview[]>([]);const [uploadedDataUrls, setUploadedDataUrls] = useState<string[]>([]);const [uploadedInputMode, setUploadedInputMode] = useState<@@ -466,6 +468,7 @@ function UploadTab({ doCreate, stack, setStack }: Props) {<OutputSettingsSectionstack={stack}setStack={setStack}+ designSystem={designSystem}/></div>@@ -498,6 +501,7 @@ function UploadTab({ doCreate, stack, setStack }: Props) {generateCode={handleScreenRecorderGenerate}stack={stack}setStack={setStack}+ designSystem={designSystem}/></div>)}diff --git a/frontend/src/components/unified-input/tabs/UrlTab.tsx b/frontend/src/components/unified-input/tabs/UrlTab.tsxindex 815e7ff5..dde31171 100644--- a/frontend/src/components/unified-input/tabs/UrlTab.tsx+++ b/frontend/src/components/unified-input/tabs/UrlTab.tsx@@ -4,6 +4,7 @@ import { Button } from "../../ui/button";import { Input } from "../../ui/input";import { toast } from "react-hot-toast";import OutputSettingsSection from "../../settings/OutputSettingsSection";+import { DesignSystemSelectorProps } from "../../settings/DesignSystemSelector";import { Stack } from "../../../lib/stacks";interface Props {@@ -15,13 +16,20 @@ interface Props {) => void;stack: Stack;setStack: (stack: Stack) => void;+ designSystem: DesignSystemSelectorProps;}function isFigmaUrl(url: string): boolean {return /^https?:\/\/([\w.-]*\.)?figma\.com\//i.test(url.trim());}-function UrlTab({ doCreate, screenshotOneApiKey, stack, setStack }: Props) {+function UrlTab({+ doCreate,+ screenshotOneApiKey,+ stack,+ setStack,+ designSystem,+}: Props) {const [isLoading, setIsLoading] = useState(false);const [referenceUrl, setReferenceUrl] = useState("");@@ -129,7 +137,11 @@ function UrlTab({ doCreate, screenshotOneApiKey, stack, setStack }: Props) {tab.</p>)}- <OutputSettingsSection stack={stack} setStack={setStack} />+ <OutputSettingsSection+ stack={stack}+ setStack={setStack}+ designSystem={designSystem}+ /><ButtononClick={takeScreenshot}diff --git a/frontend/src/hooks/useDesignSystems.ts b/frontend/src/hooks/useDesignSystems.tsnew file mode 100644index 00000000..eefc4053--- /dev/null+++ b/frontend/src/hooks/useDesignSystems.ts@@ -0,0 +1,66 @@+import { useCallback, useEffect, useState } from "react";+import toast from "react-hot-toast";+import {+ createDesignSystem,+ deleteDesignSystem,+ DesignSystemPayload,+ fetchDesignSystems,+ updateDesignSystem,+} from "../lib/design-systems";+import { DesignSystem } from "../types";++export function useDesignSystems() {+ const [designSystems, setDesignSystems] = useState<DesignSystem[]>([]);+ const [isLoading, setIsLoading] = useState(true);++ const refreshDesignSystems = useCallback(async () => {+ try {+ setIsLoading(true);+ setDesignSystems(await fetchDesignSystems());+ } catch (error) {+ console.error("Failed to load design systems", error);+ toast.error("Could not load design systems from the backend.");+ } finally {+ setIsLoading(false);+ }+ }, []);++ useEffect(() => {+ refreshDesignSystems();+ }, [refreshDesignSystems]);++ const create = useCallback(async (payload: DesignSystemPayload) => {+ const created = await createDesignSystem(payload);+ setDesignSystems((current) => [...current, created]);+ return created;+ }, []);++ const update = useCallback(+ async (id: string, payload: Partial<DesignSystemPayload>) => {+ const updated = await updateDesignSystem(id, payload);+ setDesignSystems((current) =>+ current.map((designSystem) =>+ designSystem.id === updated.id ? updated : designSystem+ )+ );+ return updated;+ },+ []+ );++ const remove = useCallback(async (id: string) => {+ await deleteDesignSystem(id);+ setDesignSystems((current) =>+ current.filter((designSystem) => designSystem.id !== id)+ );+ }, []);++ return {+ designSystems,+ isLoading,+ createDesignSystem: create,+ updateDesignSystem: update,+ deleteDesignSystem: remove,+ refreshDesignSystems,+ };+}diff --git a/frontend/src/lib/design-systems.ts b/frontend/src/lib/design-systems.tsnew file mode 100644index 00000000..1cd9dc71--- /dev/null+++ b/frontend/src/lib/design-systems.ts@@ -0,0 +1,57 @@+import { HTTP_BACKEND_URL } from "../config";+import { DesignSystem } from "../types";++export interface DesignSystemPayload {+ name: string;+ content: string;+}++export const NEW_DESIGN_SYSTEM_CONTENT = "";++async function parseJsonResponse<T>(response: Response): Promise<T> {+ if (!response.ok) {+ const message = await response.text();+ throw new Error(message || "Failed to update design systems");+ }++ return response.json() as Promise<T>;+}++export async function fetchDesignSystems(): Promise<DesignSystem[]> {+ const response = await fetch(`${HTTP_BACKEND_URL}/api/design-systems`);+ return parseJsonResponse<DesignSystem[]>(response);+}++export async function createDesignSystem(+ payload: DesignSystemPayload+): Promise<DesignSystem> {+ const response = await fetch(`${HTTP_BACKEND_URL}/api/design-systems`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ return parseJsonResponse<DesignSystem>(response);+}++export async function updateDesignSystem(+ id: string,+ payload: Partial<DesignSystemPayload>+): Promise<DesignSystem> {+ const response = await fetch(`${HTTP_BACKEND_URL}/api/design-systems/${id}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ return parseJsonResponse<DesignSystem>(response);+}++export async function deleteDesignSystem(id: string): Promise<void> {+ const response = await fetch(`${HTTP_BACKEND_URL}/api/design-systems/${id}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ const message = await response.text();+ throw new Error(message || "Failed to delete design system");+ }+}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 3d88698c..1c715ba0 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -20,12 +20,21 @@ export interface Settings {editorTheme: EditorTheme;generatedCodeConfig: Stack;codeGenerationModel: CodeGenerationModel;+ selectedDesignSystemId: string | null;// Only relevant for hosted versionisTermOfServiceAccepted: boolean;anthropicApiKey: string | null;geminiApiKey: string | null;}+export interface DesignSystem {+ id: string;+ name: string;+ content: string;+ createdAt: string;+ updatedAt: string;+}+export enum AppState {INITIAL = "INITIAL",CODING = "CODING",@@ -73,4 +82,7 @@ export interface CodeGenerationParams {optionCodes?: string[];}-export type FullGenerationSettings = CodeGenerationParams & Settings;+export type FullGenerationSettings = CodeGenerationParams &+ Settings & {+ designSystem?: string | null;+ };