Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

initial version of non-blocking updates

Abi Raja4002c0082330
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index d6a92d2c..5a4a6470 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -16,10 +16,24 @@ from config import (
)
from custom_types import InputMode
from llm import Completion, Llm
-from models import stream_claude_response, stream_claude_response_native, stream_openai_response, stream_gemini_response
+from models import (
+ stream_claude_response,
+ stream_claude_response_native,
+ stream_openai_response,
+ stream_gemini_response,
+)
from fs_logging.core import write_logs
from mock_llm import mock_completion
-from typing import Any, Callable, Coroutine, Dict, List, Literal, cast, get_args
+from typing import (
+ Any,
+ Callable,
+ Coroutine,
+ Dict,
+ List,
+ Literal,
+ cast,
+ get_args,
+)
from image_generation.core import generate_images
from prompts import create_prompt
from prompts.claude_prompts import VIDEO_PROMPT
@@ -164,7 +178,9 @@ async def stream_code(websocket: WebSocket):
await websocket.close(APP_ERROR_WEB_SOCKET_CODE)
async def send_message(
- type: Literal["chunk", "status", "setCode", "error"],
+ type: Literal[
+ "chunk", "status", "setCode", "error", "variantComplete", "variantError"
+ ],
value: str,
variantIndex: int,
):
@@ -173,6 +189,10 @@ async def stream_code(websocket: WebSocket):
print(f"Error (variant {variantIndex}): {value}")
elif type == "status":
print(f"Status (variant {variantIndex}): {value}")
+ elif type == "variantComplete":
+ print(f"Variant {variantIndex} complete")
+ elif type == "variantError":
+ print(f"Variant {variantIndex} error: {value}")
await websocket.send_json(
{"type": type, "value": value, "variantIndex": variantIndex}
@@ -223,6 +243,10 @@ async def stream_code(websocket: WebSocket):
await mock_completion(process_chunk, input_mode=input_mode)
]
completions = [result["code"] for result in completion_results]
+
+ # Send the complete variant back to the client
+ await send_message("setCode", completions[0], 0)
+ await send_message("variantComplete", "Variant generation complete", 0)
else:
try:
if input_mode == "video":
@@ -243,6 +267,10 @@ async def stream_code(websocket: WebSocket):
)
]
completions = [result["code"] for result in completion_results]
+
+ # Send the complete variant back to the client
+ await send_message("setCode", completions[0], 0)
+ await send_message("variantComplete", "Variant generation complete", 0)
else:
# Depending on the presence and absence of various keys,
@@ -346,39 +374,82 @@ async def stream_code(websocket: WebSocket):
)
)
- # Run the models in parallel and capture exceptions if any
- completions = await asyncio.gather(*tasks, return_exceptions=True)
+ # Dictionary to track variant tasks and their status
+ variant_tasks: Dict[int, asyncio.Task[Completion]] = {}
+ variant_completions: Dict[int, str] = {}
- # If all generations failed, throw an error
- all_generations_failed = all(
- isinstance(completion, BaseException) for completion in completions
- )
- if all_generations_failed:
- await throw_error("Error generating code. Please contact support.")
+ # Process each variant independently
+ for index, task in enumerate(tasks):
+ variant_task = asyncio.create_task(task)
+ variant_tasks[index] = variant_task
- # Print the all the underlying exceptions for debugging
- for completion in completions:
- if isinstance(completion, BaseException):
- traceback.print_exception(completion)
- raise Exception("All generations failed")
+ # Function to process each variant completion
+ async def process_variant_completion(
+ index: int, task: asyncio.Task[Completion]
+ ):
+ try:
+ completion = await task
- # If some completions failed, replace them with empty strings
- for index, completion in enumerate(completions):
- if isinstance(completion, BaseException):
- completions[index] = Completion(duration=0, code="")
- print("Generation failed for variant", index)
- print(completion)
- else:
print(
f"{variant_models[index].value} completion took {completion['duration']:.2f} seconds"
)
+ variant_completions[index] = completion["code"]
+
+ try:
+ # Process images for this variant
+ processed_html = await perform_image_generation(
+ completion["code"],
+ should_generate_images,
+ openai_api_key,
+ openai_base_url,
+ image_cache,
+ )
+
+ # Extract HTML content
+ processed_html = extract_html_content(processed_html)
+
+ # Send the complete variant back to the client
+ await send_message("setCode", processed_html, index)
+ await send_message(
+ "variantComplete",
+ "Variant generation complete",
+ index,
+ )
+ except Exception as inner_e:
+ # If websocket is closed or other error during post-processing
+ print(
+ f"Post-processing error for variant {index}: {inner_e}"
+ )
+ # We still keep the completion in variant_completions
- completions = [
- result["code"]
- for result in completions
- if not isinstance(result, BaseException)
+ except Exception as e:
+ # Handle any errors that occurred during generation
+ print(f"Error in variant {index}: {e}")
+ traceback.print_exception(type(e), e, e.__traceback__)
+
+ # Start processing all variants
+ variant_processors = [
+ process_variant_completion(index, task)
+ for index, task in variant_tasks.items()
]
+ # Wait for all variants to complete
+ await asyncio.gather(*variant_processors, return_exceptions=True)
+
+ # Check if all variants failed
+ if len(variant_completions) == 0:
+ await throw_error("Error generating code. Please contact support.")
+ raise Exception("All generations failed")
+
+ # Prepare completions list for further processing
+ completions: list[str] = []
+ for i in range(len(tasks)):
+ if i in variant_completions:
+ completions.append(variant_completions[i])
+ else:
+ # Add empty string for cancelled/failed variants
+ completions.append("")
+
except openai.AuthenticationError as e:
print("[GENERATE_CODE] Authentication failed", e)
error_message = (
@@ -416,32 +487,14 @@ async def stream_code(websocket: WebSocket):
## Post-processing
- # Strip the completion of everything except the HTML content
- completions = [extract_html_content(completion) for completion in completions]
-
- # Write the messages dict into a log so that we can debug later
- write_logs(prompt_messages, completions[0])
-
- ## Image Generation
-
- for index, _ in enumerate(completions):
- await send_message("status", "Generating images...", index)
-
- image_generation_tasks = [
- perform_image_generation(
- completion,
- should_generate_images,
- openai_api_key,
- openai_base_url,
- image_cache,
- )
- for completion in completions
- ]
-
- updated_completions = await asyncio.gather(*image_generation_tasks)
+ # Only process non-empty completions
+ valid_completions = [comp for comp in completions if comp]
- for index, updated_html in enumerate(updated_completions):
- await send_message("setCode", updated_html, index)
- await send_message("status", "Code generation complete.", index)
+ # Write the first valid completion to logs for debugging
+ if valid_completions:
+ # Strip the completion of everything except the HTML content
+ html_content = extract_html_content(valid_completions[0])
+ write_logs(prompt_messages, html_content)
+ # Close the websocket connection
await websocket.close()
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ed4b2868..f27b789f 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -43,6 +43,7 @@ function App() {
setCommitCode,
resetCommits,
resetHead,
+ updateVariantStatus,
// Outputs
appendExecutionConsole,
@@ -170,7 +171,7 @@ function App() {
// Reset the execution console
resetExecutionConsoles();
- // Set the app state
+ // Set the app state to coding during generation
setAppState(AppState.CODING);
// Merge settings with params
@@ -213,10 +214,39 @@ function App() {
},
// On set code
(code, variantIndex) => {
+ // When we receive the final code, also update status to complete
+ // This ensures status is set even if variantComplete event is missed
setCommitCode(commit.hash, variantIndex, code);
+ // TODO: Remove
+ // updateVariantStatus(commit.hash, variantIndex, "complete");
},
// On status update
(line, variantIndex) => appendExecutionConsole(variantIndex, line),
+ // On variant complete
+ (variantIndex) => {
+ console.log(`Variant ${variantIndex} complete event received`);
+
+ // Update variant status to variantComplete
+ updateVariantStatus(commit.hash, variantIndex, "complete");
+
+ // TODO: Remove
+ // // Force UI update by creating a small delay before state change
+ // setTimeout(() => {
+ // // If this is the selected variant, immediately set app state to ready
+ // if (commits[commit.hash].selectedVariantIndex === variantIndex) {
+ // console.log(
+ // `Selected variant ${variantIndex} complete, setting app state to ready`
+ // );
+ // setAppState(AppState.CODE_READY);
+ // }
+ // }, 100);
+ },
+ // On variant error
+ (variantIndex, error) => {
+ console.error(`Error in variant ${variantIndex}:`, error);
+ updateVariantStatus(commit.hash, variantIndex, "cancelled");
+ toast.error(`Error in option ${variantIndex + 1}: ${error}`);
+ },
// On cancel
() => {
cancelCodeGenerationAndReset(commit);
diff --git a/frontend/src/components/commits/types.ts b/frontend/src/components/commits/types.ts
index eb9ea123..e50ffc55 100644
--- a/frontend/src/components/commits/types.ts
+++ b/frontend/src/components/commits/types.ts
@@ -1,7 +1,10 @@
export type CommitHash = string;
+export type VariantStatus = "generating" | "complete" | "cancelled";
+
export type Variant = {
code: string;
+ status?: VariantStatus;
};
export type BaseCommit = {
diff --git a/frontend/src/components/sidebar/Sidebar.tsx b/frontend/src/components/sidebar/Sidebar.tsx
index bf0230cd..90a9ca57 100644
--- a/frontend/src/components/sidebar/Sidebar.tsx
+++ b/frontend/src/components/sidebar/Sidebar.tsx
@@ -3,7 +3,6 @@ import { useAppStore } from "../../store/app-store";
import { useProjectStore } from "../../store/project-store";
import { AppState } from "../../types";
import CodePreview from "../preview/CodePreview";
-import Spinner from "../core/Spinner";
import KeyboardShortcutBadge from "../core/KeyboardShortcutBadge";
// import TipLink from "../messages/TipLink";
import SelectAndEditModeToggleButton from "../select-and-edit/SelectAndEditModeToggleButton";
@@ -30,30 +29,36 @@ function Sidebar({
const { appState, updateInstruction, setUpdateInstruction } = useAppStore();
- const { inputMode, referenceImages, executionConsoles, head, commits } =
- useProjectStore();
+ const { inputMode, referenceImages, head, commits } = useProjectStore();
const viewedCode =
head && commits[head]
? commits[head].variants[commits[head].selectedVariantIndex].code
: "";
- const executionConsole =
- (head && executionConsoles[commits[head].selectedVariantIndex]) || [];
+ // Check if the currently selected variant is complete
+ const isSelectedVariantComplete =
+ head &&
+ commits[head] &&
+ commits[head].variants[commits[head].selectedVariantIndex].status ===
+ "complete";
- // When coding is complete, focus on the update instruction textarea
+ // Focus on the update instruction textarea when a variant is complete
useEffect(() => {
- if (appState === AppState.CODE_READY && textareaRef.current) {
+ if (
+ (appState === AppState.CODE_READY || isSelectedVariantComplete) &&
+ textareaRef.current
+ ) {
textareaRef.current.focus();
}
- }, [appState]);
+ }, [appState, isSelectedVariantComplete]);
return (
<>
<Variants />
- {/* Show code preview only when coding */}
- {appState === AppState.CODING && (
+ {/* Show code preview when coding and the selected variant is not complete */}
+ {appState === AppState.CODING && !isSelectedVariantComplete && (
<div className="flex flex-col">
{/* Speed disclaimer for video mode */}
{inputMode === "video" && (
@@ -66,11 +71,6 @@ function Sidebar({
</div>
)}
- <div className="flex items-center gap-x-1">
- <Spinner />
- {executionConsole.slice(-1)[0]}
- </div>
-
<CodePreview code={viewedCode} />
<div className="flex w-full">
@@ -78,13 +78,14 @@ function Sidebar({
onClick={cancelCodeGeneration}
className="w-full dark:text-white dark:bg-gray-700"
>
- Cancel
+ Cancel All Generations
</Button>
</div>
</div>
)}
- {appState === AppState.CODE_READY && (
+ {/* Show update UI when app state is ready OR the selected variant is complete */}
+ {(appState === AppState.CODE_READY || isSelectedVariantComplete) && (
<div>
<div className="grid w-full gap-2">
<Textarea
@@ -151,24 +152,6 @@ function Sidebar({
</div>
</div>
)}
- <div className="bg-gray-400 px-4 py-2 rounded text-sm hidden">
- <h2 className="text-lg mb-4 border-b border-gray-800">Console</h2>
- {Object.entries(executionConsoles).map(([index, lines]) => (
- <div key={index}>
- {lines.map((line, lineIndex) => (
- <div
- key={`${index}-${lineIndex}`}
- className="border-b border-gray-400 mb-2 text-gray-600 font-mono"
- >
- <span className="font-bold mr-2">{`${index}:${
- lineIndex + 1
- }`}</span>
- {line}
- </div>
- ))}
- </div>
- ))}
- </div>
</div>
<HistoryDisplay shouldDisableReverts={appState === AppState.CODING} />
diff --git a/frontend/src/components/variants/Variants.tsx b/frontend/src/components/variants/Variants.tsx
index 9f97f0be..7bd17420 100644
--- a/frontend/src/components/variants/Variants.tsx
+++ b/frontend/src/components/variants/Variants.tsx
@@ -1,9 +1,19 @@
import { useProjectStore } from "../../store/project-store";
+import Spinner from "../core/Spinner";
function Variants() {
const { inputMode, head, commits, updateSelectedVariantIndex } =
useProjectStore();
+ // TODO: Remove
+ // Force a re-render when the variants status changes
+ // const [, forceUpdate] = React.useState({});
+ // React.useEffect(() => {
+ // // Trigger re-render every second to catch status changes
+ // const timer = setInterval(() => forceUpdate({}), 1000);
+ // return () => clearInterval(timer);
+ // }, []);
+
// If there is no head, don't show the variants
if (head === null) {
return null;
@@ -18,22 +28,65 @@ function Variants() {
return <div className="mt-2"></div>;
}
+ const handleVariantClick = (index: number) => {
+ // Don't do anything if this is already the selected variant
+ if (index === selectedVariantIndex) return;
+
+ // First update the UI to show we're switching variants
+ updateSelectedVariantIndex(head, index);
+ };
+
return (
<div className="mt-4 mb-4">
<div className="grid grid-cols-2 gap-2">
- {variants.map((_, index) => (
- <div
- key={index}
- className={`p-2 border rounded-md cursor-pointer ${
- index === selectedVariantIndex
- ? "bg-blue-100 dark:bg-blue-900"
- : "bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700"
- }`}
- onClick={() => updateSelectedVariantIndex(head, index)}
- >
- <h3 className="font-medium mb-1">Option {index + 1}</h3>
- </div>
- ))}
+ {variants.map((variant, index) => {
+ // Determine the status indicator
+ let statusIndicator = null;
+ if (variant.status === "complete") {
+ statusIndicator = (
+ <span
+ className="inline-block w-2 h-2 bg-green-500 rounded-full ml-2"
+ title="Complete"
+ ></span>
+ );
+ } else if (variant.status === "cancelled") {
+ statusIndicator = (
+ <span
+ className="inline-block w-2 h-2 bg-red-500 rounded-full ml-2"
+ title="Cancelled"
+ ></span>
+ );
+ }
+
+ return (
+ <div
+ key={index}
+ className={`p-2 border rounded-md cursor-pointer ${
+ index === selectedVariantIndex
+ ? "bg-blue-100 dark:bg-blue-900"
+ : "bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700"
+ }`}
+ onClick={() => handleVariantClick(index)}
+ >
+ <div className="flex justify-between items-center">
+ <h3 className="font-medium flex items-center">
+ Option {index + 1}
+ {variant.status === "generating" && (
+ <div className="scale-75 ml-2">
+ <Spinner />
+ </div>
+ )}
+ {statusIndicator}
+ </h3>
+ </div>
+ <div className="text-xs mt-1 flex items-center">
+ {variant.status === "cancelled" && (
+ <span className="text-gray-500">Cancelled</span>
+ )}
+ </div>
+ </div>
+ );
+ })}
</div>
</div>
);
diff --git a/frontend/src/generateCode.ts b/frontend/src/generateCode.ts
index b3737022..e0a689ee 100644
--- a/frontend/src/generateCode.ts
+++ b/frontend/src/generateCode.ts
@@ -12,7 +12,13 @@ const ERROR_MESSAGE =
const CANCEL_MESSAGE = "Code generation cancelled";
type WebSocketResponse = {
- type: "chunk" | "status" | "setCode" | "error";
+ type:
+ | "chunk"
+ | "status"
+ | "setCode"
+ | "error"
+ | "variantComplete"
+ | "variantError";
value: string;
variantIndex: number;
};
@@ -23,6 +29,8 @@ export function generateCode(
onChange: (chunk: string, variantIndex: number) => void,
onSetCode: (code: string, variantIndex: number) => void,
onStatusUpdate: (status: string, variantIndex: number) => void,
+ onVariantComplete: (variantIndex: number) => void,
+ onVariantError: (variantIndex: number, error: string) => void,
onCancel: () => void,
onComplete: () => void
) {
@@ -44,6 +52,10 @@ export function generateCode(
onStatusUpdate(response.value, response.variantIndex);
} else if (response.type === "setCode") {
onSetCode(response.value, response.variantIndex);
+ } else if (response.type === "variantComplete") {
+ onVariantComplete(response.variantIndex);
+ } else if (response.type === "variantError") {
+ onVariantError(response.variantIndex, response.value);
} else if (response.type === "error") {
console.error("Error generating code", response.value);
toast.error(response.value);
diff --git a/frontend/src/store/project-store.ts b/frontend/src/store/project-store.ts
index b9e26a9c..e45c52b5 100644
--- a/frontend/src/store/project-store.ts
+++ b/frontend/src/store/project-store.ts
@@ -1,5 +1,5 @@
import { create } from "zustand";
-import { Commit, CommitHash } from "../components/commits/types";
+import { Commit, CommitHash, VariantStatus } from "../components/commits/types";
// Store for app-wide state
interface ProjectStore {
@@ -26,6 +26,11 @@ interface ProjectStore {
) => void;
setCommitCode: (hash: CommitHash, numVariant: number, code: string) => void;
updateSelectedVariantIndex: (hash: CommitHash, index: number) => void;
+ updateVariantStatus: (
+ hash: CommitHash,
+ numVariant: number,
+ status: VariantStatus
+ ) => void;
setHead: (hash: CommitHash) => void;
resetHead: () => void;
@@ -49,6 +54,15 @@ export const useProjectStore = create<ProjectStore>((set) => ({
head: null,
addCommit: (commit: Commit) => {
+ // Initialize variant statuses as 'generating'
+ const commitsWithStatus = {
+ ...commit,
+ variants: commit.variants.map((variant) => ({
+ ...variant,
+ status: variant.status || ("generating" as VariantStatus),
+ })),
+ };
+
// When adding a new commit, make sure all existing commits are marked as committed
set((state) => ({
commits: {
@@ -58,7 +72,7 @@ export const useProjectStore = create<ProjectStore>((set) => ({
{ ...existingCommit, isCommitted: true },
])
),
- [commit.hash]: commit,
+ [commitsWithStatus.hash]: commitsWithStatus,
},
}));
},
@@ -120,6 +134,9 @@ export const useProjectStore = create<ProjectStore>((set) => ({
"Attempted to update selected variant index of a committed commit"
);
}
+
+ // Just update the selected variant index without canceling other variants
+ // This allows users to switch between variants even while they're still generating
return {
commits: {
...state.commits,
@@ -130,6 +147,27 @@ export const useProjectStore = create<ProjectStore>((set) => ({
},
};
}),
+ updateVariantStatus: (
+ hash: CommitHash,
+ numVariant: number,
+ status: VariantStatus
+ ) =>
+ set((state) => {
+ const commit = state.commits[hash];
+ if (!commit) return state; // No change if commit doesn't exist
+
+ return {
+ commits: {
+ ...state.commits,
+ [hash]: {
+ ...commit,
+ variants: commit.variants.map((variant, index) =>
+ index === numVariant ? { ...variant, status } : variant
+ ),
+ },
+ },
+ };
+ }),
setHead: (hash: CommitHash) => set({ head: hash }),
resetHead: () => set({ head: null }),