Skip to content

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

Python

Support regenerating all generated versions

Abi Raja7474da4b42a0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 773c2023..956da176 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -15,11 +15,11 @@ import useBrowserTabIndicator from "./hooks/useBrowserTabIndicator";
import { LuChevronLeft } from "react-icons/lu";
import {
buildAssistantHistoryMessage,
+ buildUpdateGenerationRequest,
buildUserHistoryMessage,
cloneVariantHistory,
GenerationRequest,
registerAssetIds,
- toRequestHistory,
} from "./lib/prompt-history";
// import TipLink from "./components/messages/TipLink";
import { useAppStore } from "./store/app-store";
@@ -37,7 +37,7 @@ 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 { AiEditCommit, Commit } from "./components/commits/types";
import { createCommit } from "./components/commits/utils";
function App() {
@@ -262,18 +262,26 @@ function App() {
throw new Error("Regenerate called with no head");
}
- // Retrieve the previous command
const currentCommit = commits[head];
- if (currentCommit.type !== "ai_create") {
- toast.error("Only the first version can be regenerated.");
+ if (!currentCommit) {
+ toast.error("The selected version could not be found.");
return;
}
- // Re-run the create
+ if (currentCommit.type === "ai_edit") {
+ regenerateUpdate(currentCommit);
+ return;
+ }
+
+ if (currentCommit.type === "code_create") {
+ toast.error("Imported code cannot be regenerated.");
+ return;
+ }
+
+ // Re-run the initial create request.
if (inputMode === "image" || inputMode === "video") {
doCreate(referenceImages, inputMode);
} else {
- // TODO: Fix this
doCreateFromText(initialPrompt);
}
};
@@ -304,7 +312,10 @@ function App() {
}
};
- function doGenerateCode(params: GenerationRequest) {
+ function doGenerateCode(
+ params: GenerationRequest,
+ generationParentHash: string | null = head
+ ) {
// Reset the execution console
resetExecutionConsoles();
@@ -348,7 +359,7 @@ function App() {
: {
...baseCommitObject,
type: "ai_edit" as const,
- parentHash: head,
+ parentHash: generationParentHash,
inputs: requestParams.prompt,
};
@@ -622,6 +633,41 @@ function App() {
});
}
+ function regenerateUpdate(commit: AiEditCommit) {
+ const parentHash = commit.parentHash;
+ const parentCommit = parentHash ? commits[parentHash] : null;
+ if (!parentHash || !parentCommit) {
+ toast.error("The previous version needed to retry this edit was not found.");
+ return;
+ }
+
+ const parentVariant =
+ parentCommit.variants[parentCommit.selectedVariantIndex];
+ if (!parentVariant) {
+ toast.error("The selected option from the previous version was not found.");
+ return;
+ }
+
+ const imageAssetIds = registerAssetIds(
+ "image",
+ commit.inputs.images,
+ getAssetsById,
+ upsertPromptAssets,
+ nanoid
+ );
+
+ doGenerateCode(
+ buildUpdateGenerationRequest({
+ inputMode,
+ prompt: commit.inputs,
+ parentCommit,
+ imageAssetIds,
+ getAssetsById,
+ }),
+ parentHash
+ );
+ }
+
// Subsequent updates
async function doUpdate(updateInstruction: string) {
if (updateInstruction.trim() === "") {
@@ -637,11 +683,10 @@ function App() {
}
const currentCommit = commits[head];
- const currentCode =
- currentCommit?.variants[currentCommit.selectedVariantIndex]?.code || "";
- const optionCodes = currentCommit?.variants.map(
- (variant) => variant.code || ""
- );
+ if (!currentCommit) {
+ toast.error("The selected version could not be found.");
+ return;
+ }
let modifiedUpdateInstruction = updateInstruction;
let selectedElementHtml: string | undefined;
@@ -661,8 +706,6 @@ function App() {
setSelectedElement(null);
}
- const selectedVariant = currentCommit.variants[currentCommit.selectedVariantIndex];
- const baseVariantHistory = selectedVariant.history;
const updateImageAssetIds = registerAssetIds(
"image",
updateImages,
@@ -670,36 +713,22 @@ function App() {
upsertPromptAssets,
nanoid
);
- const updatedVariantHistory = [
- ...cloneVariantHistory(baseVariantHistory),
- buildUserHistoryMessage(modifiedUpdateInstruction, updateImageAssetIds),
- ];
- const shouldBootstrapFromFileState =
- baseVariantHistory.length === 0 && currentCode.trim().length > 0;
- const updatedHistory = shouldBootstrapFromFileState
- ? []
- : toRequestHistory(updatedVariantHistory, getAssetsById);
- doGenerateCode({
- generationType: "update",
- inputMode,
- prompt: {
- text: updateInstruction,
- fullText: modifiedUpdateInstruction,
- images: updateImages,
- videos: [],
- selectedElementHtml,
- },
- history: updatedHistory,
- optionCodes,
- variantHistory: updatedVariantHistory,
- fileState: currentCode
- ? {
- path: "index.html",
- content: currentCode,
- }
- : undefined,
- });
+ doGenerateCode(
+ buildUpdateGenerationRequest({
+ inputMode,
+ prompt: {
+ text: updateInstruction,
+ fullText: modifiedUpdateInstruction,
+ images: updateImages,
+ videos: [],
+ selectedElementHtml,
+ },
+ parentCommit: currentCommit,
+ imageAssetIds: updateImageAssetIds,
+ getAssetsById,
+ })
+ );
}
const handleTermDialogOpenChange = (open: boolean) => {
diff --git a/frontend/src/components/sidebar/Sidebar.tsx b/frontend/src/components/sidebar/Sidebar.tsx
index 4555b9df..dcbcc349 100644
--- a/frontend/src/components/sidebar/Sidebar.tsx
+++ b/frontend/src/components/sidebar/Sidebar.tsx
@@ -174,7 +174,8 @@ function Sidebar({
? Math.max(1, Math.round((nowMs - requestStartMs) / 1000))
: undefined;
- const isFirstGeneration = currentCommit?.type === "ai_create";
+ const canRegenerate =
+ currentCommit?.type === "ai_create" || currentCommit?.type === "ai_edit";
const isViewingOlderVersion = head !== null && head !== latestCommitHash;
// Compute version number for the current head
@@ -401,22 +402,17 @@ function Sidebar({
<AgentActivity />
)}
- {/* Regenerate button for first generation.
- Scenarios:
- 1) `appState === CODE_READY`: request fully ended and user can retry.
- 2) `isSelectedVariantComplete`: selected option completed even if app state
- has not yet fully transitioned.
- 3) `isSelectedVariantError`: selected option failed; keep retry visible so
- users can rerun create without losing uploaded inputs. */}
- {isFirstGeneration &&
- head === latestCommitHash &&
+ {/* Retry any AI-generated version. A completed older version can be
+ retried once no other request is running; the regenerated edit
+ branches from that version's original parent. */}
+ {canRegenerate &&
(appState === AppState.CODE_READY ||
- isSelectedVariantComplete ||
- isSelectedVariantError) && (
+ (head === latestCommitHash &&
+ (isSelectedVariantComplete || isSelectedVariantError))) && (
<div className="flex justify-end mb-3">
<button
onClick={regenerate}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-zinc-800 transition-colors"
+ className="regenerate-btn flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-zinc-800 transition-colors"
>
<LuRefreshCw className="w-3.5 h-3.5" />
Retry
@@ -461,8 +457,8 @@ function Sidebar({
</div>
)}
<div>
- {isFirstGeneration
- ? "Click Retry to run the create request again."
+ {canRegenerate
+ ? "Click Retry to run this version's request again."
: "Switch to another option above to make updates."}
</div>
</div>
diff --git a/frontend/src/lib/prompt-history.test.ts b/frontend/src/lib/prompt-history.test.ts
index e2791915..0a244a67 100644
--- a/frontend/src/lib/prompt-history.test.ts
+++ b/frontend/src/lib/prompt-history.test.ts
@@ -1,10 +1,12 @@
import {
buildAssistantHistoryMessage,
+ buildUpdateGenerationRequest,
buildUserHistoryMessage,
cloneVariantHistory,
registerAssetIds,
toRequestHistory,
} from "./prompt-history";
+import { Commit } from "../components/commits/types";
import { PromptAsset } from "../types";
describe("prompt-history helpers", () => {
@@ -120,4 +122,86 @@ describe("prompt-history helpers", () => {
videoAssetIds: [],
});
});
+
+ test("buildUpdateGenerationRequest reruns an edit from the selected parent option", () => {
+ const parentCommit: Commit = {
+ hash: "parent",
+ parentHash: null,
+ dateCreated: new Date(),
+ isCommitted: true,
+ type: "ai_create",
+ inputs: { text: "Create", images: [] },
+ selectedVariantIndex: 1,
+ variants: [
+ { code: "<html>option one</html>", history: [] },
+ {
+ code: "<html>option two</html>",
+ history: [
+ buildUserHistoryMessage("Create"),
+ buildAssistantHistoryMessage("<html>option two</html>"),
+ ],
+ },
+ ],
+ };
+ const assetsById: Record<string, PromptAsset> = {
+ editImage: {
+ id: "editImage",
+ type: "image",
+ dataUrl: "data:image/edit",
+ },
+ };
+
+ const request = buildUpdateGenerationRequest({
+ inputMode: "image",
+ prompt: {
+ text: "Make it red",
+ fullText: "Make the selected button red",
+ images: ["data:image/edit"],
+ videos: [],
+ selectedElementHtml: "<button>Option two</button>",
+ },
+ parentCommit,
+ imageAssetIds: ["editImage"],
+ getAssetsById: () => assetsById,
+ });
+
+ expect(request.fileState?.content).toBe("<html>option two</html>");
+ expect(request.optionCodes).toEqual([
+ "<html>option one</html>",
+ "<html>option two</html>",
+ ]);
+ expect(request.variantHistory[request.variantHistory.length - 1]).toEqual(
+ buildUserHistoryMessage("Make the selected button red", ["editImage"])
+ );
+ expect(request.history?.[request.history.length - 1]).toEqual({
+ role: "user",
+ text: "Make the selected button red",
+ images: ["data:image/edit"],
+ videos: [],
+ });
+ });
+
+ test("buildUpdateGenerationRequest bootstraps imported code without history", () => {
+ const parentCommit: Commit = {
+ hash: "import",
+ parentHash: null,
+ dateCreated: new Date(),
+ isCommitted: true,
+ type: "code_create",
+ inputs: null,
+ selectedVariantIndex: 0,
+ variants: [{ code: "<html>imported</html>", history: [] }],
+ };
+
+ const request = buildUpdateGenerationRequest({
+ inputMode: "image",
+ prompt: { text: "Add a footer", images: [], videos: [] },
+ parentCommit,
+ imageAssetIds: [],
+ getAssetsById: () => ({}),
+ });
+
+ expect(request.history).toEqual([]);
+ expect(request.fileState?.content).toBe("<html>imported</html>");
+ });
});
diff --git a/frontend/src/lib/prompt-history.ts b/frontend/src/lib/prompt-history.ts
index 9cf7cdc5..dd4a4dea 100644
--- a/frontend/src/lib/prompt-history.ts
+++ b/frontend/src/lib/prompt-history.ts
@@ -1,8 +1,12 @@
-import { VariantHistoryMessage } from "../components/commits/types";
+import {
+ Commit,
+ VariantHistoryMessage,
+} from "../components/commits/types";
import {
CodeGenerationParams,
PromptAsset,
PromptAssetType,
+ PromptContent,
PromptHistoryMessage,
} from "../types";
@@ -107,3 +111,52 @@ export function buildAssistantHistoryMessage(
videoAssetIds: [],
};
}
+
+export function buildUpdateGenerationRequest({
+ inputMode,
+ prompt,
+ parentCommit,
+ imageAssetIds,
+ getAssetsById,
+}: {
+ inputMode: GenerationRequest["inputMode"];
+ prompt: PromptContent;
+ parentCommit: Commit;
+ imageAssetIds: string[];
+ getAssetsById: GetAssetsById;
+}): GenerationRequest {
+ const parentVariant =
+ parentCommit.variants[parentCommit.selectedVariantIndex];
+ if (!parentVariant) {
+ throw new Error("The selected option from the previous version was not found");
+ }
+
+ const fullInstruction = prompt.fullText ?? prompt.text;
+ const variantHistory = [
+ ...cloneVariantHistory(parentVariant.history),
+ buildUserHistoryMessage(fullInstruction, imageAssetIds),
+ ];
+ const shouldBootstrapFromFileState =
+ parentVariant.history.length === 0 && parentVariant.code.trim().length > 0;
+
+ return {
+ generationType: "update",
+ inputMode,
+ prompt: {
+ ...prompt,
+ images: [...prompt.images],
+ videos: [...(prompt.videos ?? [])],
+ },
+ history: shouldBootstrapFromFileState
+ ? []
+ : toRequestHistory(variantHistory, getAssetsById),
+ optionCodes: parentCommit.variants.map((variant) => variant.code || ""),
+ variantHistory,
+ fileState: parentVariant.code
+ ? {
+ path: "index.html",
+ content: parentVariant.code,
+ }
+ : undefined,
+ };
+}