Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Update prompt handling behavior
Abi Raja2119a7f2ce06
diff --git a/backend/prompts/__init__.py b/backend/prompts/__init__.pyindex 0ed98cad..6c72b83e 100644--- a/backend/prompts/__init__.py+++ b/backend/prompts/__init__.py@@ -1,8 +1,7 @@-from typing import Union, Any, cast+from typing import Any, castfrom openai.types.chat import ChatCompletionMessageParam, ChatCompletionContentPartParamfrom custom_types import InputMode-from prompts.imported_code_prompts import IMPORTED_CODE_SYSTEM_PROMPTSfrom prompts.screenshot_system_prompts import SYSTEM_PROMPTfrom prompts.video_prompts import GEMINI_VIDEO_PROMPTfrom prompts.types import Stack, PromptContent@@ -19,6 +18,14 @@ For mobile screenshots, do not include the device frame or browser chrome; focusthe actual UI mockups."""+IMPORTED_CODE_INSTRUCTIONS = """+You are continuing from an imported codebase. Follow these instructions while updating it:++- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" or "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.+- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.+- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.+"""+async def create_prompt(stack: Stack,@@ -33,12 +40,13 @@ async def create_prompt(# If this generation started off with imported code, we need to assemble the prompt differentlyif is_imported_from_code:- original_imported_code = history[0]["text"]- prompt_messages = assemble_imported_code_prompt(original_imported_code, stack)- for index, item in enumerate(history[1:]):- role = "user" if index % 2 == 0 else "assistant"- message = create_message_from_history_item(item, role)- prompt_messages.append(message)+ original_imported_code = history[0]["text"] if history else ""+ imported_user_prompt = get_imported_code_user_prompt(prompt, history)+ prompt_messages = assemble_imported_code_prompt(+ original_imported_code,+ stack,+ imported_user_prompt,+ )else:# Assemble the prompt for non-imported codeif input_mode == "image":@@ -133,19 +141,84 @@ def create_message_from_history_item(def assemble_imported_code_prompt(- code: str, stack: Stack+ code: str,+ stack: Stack,+ user_prompt: PromptContent,) -> list[ChatCompletionMessageParam]:- system_content = IMPORTED_CODE_SYSTEM_PROMPTS[stack]- user_content = "Here is the code of the app: " + code+ system_content = (+ SYSTEM_PROMPT.strip()+ + "\n\n"+ + IMPORTED_CODE_INSTRUCTIONS.strip()+ + f"\n\nSelected stack: {stack}."+ + "\n\nThe current app code is provided below. Update it per the request."+ + f"\n\n{code}"+ )return [{"role": "system",- "content": system_content + "\n " + user_content,- }+ "content": system_content,+ },+ create_message_from_history_item(+ {+ "text": user_prompt.get("text", ""),+ "images": user_prompt.get("images", []),+ },+ "user",+ ),]+def get_imported_code_user_prompt(+ prompt: PromptContent,+ history: list[dict[str, Any]],+) -> PromptContent:+ prompt_text = prompt.get("text", "")+ prompt_images = prompt.get("images", [])+ normalized_prompt_images: list[str] = []+ if isinstance(prompt_images, list):+ raw_prompt_images = cast(list[object], prompt_images)+ for image in raw_prompt_images:+ if isinstance(image, str):+ normalized_prompt_images.append(image)++ # Preferred path: if prompt has text, treat it as the latest user instruction.+ if prompt_text.strip():+ return {+ "text": prompt_text,+ "images": normalized_prompt_images,+ }++ # Backward-compatibility path: recover latest user turn from imported-code history.+ for index in range(len(history) - 1, 0, -1):+ if index % 2 == 1:+ item = history[index]+ text = item.get("text", "")+ images = item.get("images", [])+ normalized_images: list[str] = []+ if isinstance(images, list):+ raw_images = cast(list[object], images)+ for image in raw_images:+ if isinstance(image, str):+ normalized_images.append(image)+ return {+ "text": text if isinstance(text, str) else "",+ "images": normalized_images,+ }++ # Final fallback: if prompt only has images, keep them so visual references are not lost.+ if normalized_prompt_images:+ return {+ "text": "",+ "images": normalized_prompt_images,+ }++ return {+ "text": "Update the imported code according to the latest request.",+ "images": [],+ }++def assemble_prompt(image_data_urls: list[str],stack: Stack,diff --git a/backend/prompts/imported_code_prompts.py b/backend/prompts/imported_code_prompts.pydeleted file mode 100644index 013700b4..00000000--- a/backend/prompts/imported_code_prompts.py+++ /dev/null@@ -1,133 +0,0 @@-from prompts.types import SystemPrompts---IMPORTED_CODE_TAILWIND_SYSTEM_PROMPT = """-You are an expert Tailwind developer.--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- Use this script to include Tailwind: <script src="https://cdn.tailwindcss.com"></script>-- You can use Google Fonts-- Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>--Follow the tool instructions in the system prompt.-"""--IMPORTED_CODE_HTML_CSS_SYSTEM_PROMPT = """-You are an expert CSS developer.--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- You can use Google Fonts-- Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>--Follow the tool instructions in the system prompt.-"""--IMPORTED_CODE_REACT_TAILWIND_SYSTEM_PROMPT = """-You are an expert React/Tailwind developer--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- Use these script to include React so that it can run on a standalone page:- <script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react.development.js"></script>- <script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.development.js"></script>- <script src="https://cdn.jsdelivr.net/npm/@babel/standalone/babel.js"></script>-- Use this script to include Tailwind: <script src="https://cdn.tailwindcss.com"></script>-- You can use Google Fonts-- Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>--Follow the tool instructions in the system prompt.-"""--IMPORTED_CODE_BOOTSTRAP_SYSTEM_PROMPT = """-You are an expert Bootstrap developer.--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- Use this script to include Bootstrap: <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">-- You can use Google Fonts-- Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>--Follow the tool instructions in the system prompt.-"""--IMPORTED_CODE_IONIC_TAILWIND_SYSTEM_PROMPT = """-You are an expert Ionic/Tailwind developer.--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- Use these script to include Ionic so that it can run on a standalone page:- <script type="module" src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js"></script>- <script nomodule src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js"></script>- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css" />-- Use this script to include Tailwind: <script src="https://cdn.tailwindcss.com"></script>-- You can use Google Fonts-- ionicons for icons, add the following <script > tags near the end of the page, right before the closing </body> tag:- <script type="module">- import ionicons from 'https://cdn.jsdelivr.net/npm/ionicons/+esm'- </script>- <script nomodule src="https://cdn.jsdelivr.net/npm/ionicons/dist/esm/ionicons.min.js"></script>- <link href="https://cdn.jsdelivr.net/npm/ionicons/dist/collection/components/icon/icon.min.css" rel="stylesheet">--Follow the tool instructions in the system prompt.-"""--IMPORTED_CODE_VUE_TAILWIND_SYSTEM_PROMPT = """-You are an expert Vue/Tailwind developer.--- Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE.-- Repeat elements as needed. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen.-- For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later.--In terms of libraries,--- Use these script to include Vue so that it can run on a standalone page:- <script src="https://registry.npmmirror.com/vue/3.3.11/files/dist/vue.global.js"></script>-- Use Vue using the global build like so:- <div id="app">{{ message }}</div>- <script>- const { createApp, ref } = Vue- createApp({- setup() {- const message = ref('Hello vue!')- return {- message- }- }- }).mount('#app')- </script>-- Use this script to include Tailwind: <script src="https://cdn.tailwindcss.com"></script>-- You can use Google Fonts-- Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>--Follow the tool instructions in the system prompt."""--IMPORTED_CODE_SYSTEM_PROMPTS = SystemPrompts(- html_tailwind=IMPORTED_CODE_TAILWIND_SYSTEM_PROMPT,- html_css=IMPORTED_CODE_HTML_CSS_SYSTEM_PROMPT,- react_tailwind=IMPORTED_CODE_REACT_TAILWIND_SYSTEM_PROMPT,- bootstrap=IMPORTED_CODE_BOOTSTRAP_SYSTEM_PROMPT,- ionic_tailwind=IMPORTED_CODE_IONIC_TAILWIND_SYSTEM_PROMPT,- vue_tailwind=IMPORTED_CODE_VUE_TAILWIND_SYSTEM_PROMPT,-)diff --git a/backend/tests/test_prompts.py b/backend/tests/test_prompts.pyindex b0993045..f2a6b43a 100644--- a/backend/tests/test_prompts.py+++ b/backend/tests/test_prompts.py@@ -219,7 +219,7 @@ class TestCreatePrompt:},{"role": "user",- "content": f"Generate UI for {text_description}"+ "content": f"<CONTAINS:Generate UI for {text_description}>"}],}@@ -266,7 +266,7 @@ class TestCreatePrompt:},{"role": "user",- "content": f"Generate UI for {text_description}"+ "content": f"<CONTAINS:Generate UI for {text_description}>"},{"role": "assistant",@@ -566,12 +566,7 @@ class TestCreatePrompt:]}- # Mock the imported code system prompts- mock_imported_prompts: Dict[str, str] = {- self.TEST_STACK: "Mock Imported Code System Prompt"- }-- with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):+ with patch("prompts.SYSTEM_PROMPT", self.MOCK_SYSTEM_PROMPT):# Call the functionmessages = await create_prompt(stack=self.TEST_STACK,@@ -587,7 +582,7 @@ class TestCreatePrompt:"messages": [{"role": "system",- "content": "Mock Imported Code System Prompt\n Here is the code of the app: <html>Original imported code</html>",+ "content": "<CONTAINS:continuing from an imported codebase>",},{"role": "user",@@ -605,10 +600,48 @@ class TestCreatePrompt:},],},- {"role": "assistant", "content": "<html>Updated code</html>"},],}# Assert the structure matchesactual: ExpectedResult = {"messages": messages}assert_structure_match(actual, expected)++ @pytest.mark.asyncio+ async def test_imported_code_update_prefers_history_text_over_prompt_images(self) -> None:+ """Imported-code updates should not lose text instructions when prompt only has images."""+ params: Dict[str, Any] = {+ "isImportedFromCode": True,+ "generationType": "update",+ "prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},+ "history": [+ {"text": "<html>Original imported code</html>", "images": []},+ {"text": "Make the header blue", "images": []},+ ],+ }++ with patch("prompts.SYSTEM_PROMPT", self.MOCK_SYSTEM_PROMPT):+ messages = await create_prompt(+ stack=self.TEST_STACK,+ input_mode="image",+ generation_type=params["generationType"],+ prompt=params["prompt"],+ history=params.get("history", []),+ is_imported_from_code=params.get("isImportedFromCode", False),+ )++ expected: ExpectedResult = {+ "messages": [+ {+ "role": "system",+ "content": "<CONTAINS:continuing from an imported codebase>",+ },+ {+ "role": "user",+ "content": "Make the header blue",+ },+ ],+ }++ actual: ExpectedResult = {"messages": messages}+ assert_structure_match(actual, expected)diff --git a/backend/tests/test_prompts_additional.py b/backend/tests/test_prompts_additional.pyindex a7cd1b5e..a293b74e 100644--- a/backend/tests/test_prompts_additional.py+++ b/backend/tests/test_prompts_additional.py@@ -230,12 +230,7 @@ class TestCreatePromptImageSupport:]}- # Mock the imported code system prompts- mock_imported_prompts: Dict[str, str] = {- self.TEST_STACK: "Mock Imported Code System Prompt"- }-- with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):+ with patch("prompts.SYSTEM_PROMPT", self.MOCK_SYSTEM_PROMPT):# Call the functionmessages = await create_prompt(stack=self.TEST_STACK,@@ -251,7 +246,7 @@ class TestCreatePromptImageSupport:"messages": [{"role": "system",- "content": "Mock Imported Code System Prompt\n Here is the code of the app: <html>Original imported code</html>",+ "content": "<CONTAINS:continuing from an imported codebase>",},{"role": "user",@@ -269,7 +264,6 @@ class TestCreatePromptImageSupport:},],},- {"role": "assistant", "content": "<html>Updated code</html>"},],}