Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: ai instance deletion (#2468)

Giuseppe70cccfd0d391
diff --git a/apps/builder/app/builder/features/ai/ai-fetch-result.ts b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
index 3fa242dc7b..8bfa1b932d 100644
--- a/apps/builder/app/builder/features/ai/ai-fetch-result.ts
+++ b/apps/builder/app/builder/features/ai/ai-fetch-result.ts
@@ -30,9 +30,9 @@ import {
} from "~/shared/nano-states";
import { applyOperations, patchTextInstance } from "./apply-operations";
import { restAi } from "~/shared/router-utils";
-import { RequestParamsSchema } from "~/routes/rest.ai._index";
import untruncateJson from "untruncate-json";
import { traverseTemplate } from "@webstudio-is/jsx-utils";
+import { RequestParamsSchema } from "~/routes/rest.ai._index";
const unknownArray = z.array(z.unknown());
@@ -40,30 +40,10 @@ export const fetchResult = async (
prompt: string,
abortSignal: AbortSignal
): Promise<string[]> => {
- const project = projectStore.get();
- const selectedInstanceSelector = selectedInstanceSelectorStore.get();
- const availableComponentsNames = $availableComponentsNames.get();
- const [styles, jsx] = $jsx.get() || [];
-
- const requestParams = {
- jsx: `${styles}${jsx}`,
- components: availableComponentsNames,
- projectId: project?.id,
- instanceId: selectedInstanceSelector?.[0] ?? "",
- prompt,
- };
-
- if (
- RequestParamsSchema.omit({ command: true }).safeParse(requestParams)
- .success === false
- ) {
- return ["Invalid prompt data"];
- }
-
const commandsResponse = await handleAiRequest<commandDetect.Response>(
fetch(restAi("detect"), {
method: "POST",
- body: JSON.stringify({ prompt: requestParams.prompt }),
+ body: JSON.stringify({ prompt }),
signal: abortSignal,
}),
{ signal: abortSignal }
@@ -87,7 +67,33 @@ export const fetchResult = async (
return ["Something went wrong."];
}
+ const project = projectStore.get();
+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ const availableComponentsNames = $availableComponentsNames.get();
+ const [styles, jsx] = $jsx.get() || ["", ""];
+
+ const requestParams = {
+ jsx: `${styles}${jsx}`,
+ components: availableComponentsNames,
+ projectId: project?.id,
+ instanceId: selectedInstanceSelector?.[0],
+ prompt,
+ };
+
+ // @todo Future commands might not require all the requestParams above.
+ // When that will be the case, we should revisit the validatin below.
+ if (requestParams.instanceId === undefined) {
+ return ["Please select an instance on the canvas."];
+ }
+ if (
+ RequestParamsSchema.omit({ command: true }).safeParse(requestParams)
+ .success === false
+ ) {
+ return ["Invalid prompt data"];
+ }
+
const appliedOperations = new Set<string>();
+
const promises = await Promise.allSettled(
commandsResponse.data.map((command) =>
handleAiRequest<operations.Response>(
diff --git a/apps/builder/app/builder/features/ai/apply-operations.ts b/apps/builder/app/builder/features/ai/apply-operations.ts
index 02f3e19fc9..c2d2442fd0 100644
--- a/apps/builder/app/builder/features/ai/apply-operations.ts
+++ b/apps/builder/app/builder/features/ai/apply-operations.ts
@@ -10,13 +10,14 @@ import {
breakpointsStore,
instancesStore,
registeredComponentMetasStore,
+ selectedInstanceSelectorStore,
selectedInstanceStore,
styleSourceSelectionsStore,
styleSourcesStore,
stylesStore,
} from "~/shared/nano-states";
-import type { DroppableTarget } from "~/shared/tree-utils";
-import { getStyleDeclKey, type StyleSource } from "@webstudio-is/sdk";
+import type { DroppableTarget, InstanceSelector } from "~/shared/tree-utils";
+import { getStyleDeclKey, Instance, type StyleSource } from "@webstudio-is/sdk";
import { nanoid } from "nanoid";
export const applyOperations = (operations: operations.WsOperations) => {
@@ -86,7 +87,44 @@ const insertTemplateByOp = (
const deleteInstanceByOp = (
operation: operations.deleteInstanceWsOperation
) => {
- _deleteInstance([operation.wsId]);
+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+
+ // For a given instance to delete we compute the subtree selector between
+ // that instance and the selected instance (a parent).
+ let subtreeSelector: InstanceSelector = [];
+ const parentInstancesById = new Map<Instance["id"], Instance["id"]>();
+ for (const instance of instancesStore.get().values()) {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ parentInstancesById.set(child.value, instance.id);
+ }
+ }
+ }
+ const selector: InstanceSelector = [];
+ let currentInstanceId: undefined | Instance["id"] = operation.wsId;
+ while (currentInstanceId) {
+ selector.push(currentInstanceId);
+ currentInstanceId = parentInstancesById.get(currentInstanceId);
+ if (currentInstanceId === selectedInstanceSelector[0]) {
+ subtreeSelector = [...selector, ...selectedInstanceSelector];
+ break;
+ }
+ }
+
+ if (subtreeSelector.length === 0) {
+ return;
+ }
+
+ const parentSelector = selectedInstanceSelector.slice(1);
+ // Combine the subtree selector with the selected instance one
+ // to get the full and final selector.
+ const combinedSelector = [...subtreeSelector, ...parentSelector];
+
+ // Finally delete the instance by selector.
+ _deleteInstance(combinedSelector);
};
const applyStylesByOp = (operation: operations.editStylesWsOperation) => {
diff --git a/apps/builder/app/routes/rest.ai._index.ts b/apps/builder/app/routes/rest.ai._index.ts
index 9f95cacba6..69789d69fe 100644
--- a/apps/builder/app/routes/rest.ai._index.ts
+++ b/apps/builder/app/routes/rest.ai._index.ts
@@ -20,11 +20,11 @@ import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
import { loadBuildByProjectId } from "@webstudio-is/project-build/index.server";
export const RequestParamsSchema = z.object({
- projectId: z.string(),
- instanceId: z.string(),
- prompt: z.string().max(1200),
+ projectId: z.string().min(1, "nonempty"),
+ instanceId: z.string().min(1, "nonempty"),
+ prompt: z.string().min(1, "nonempty").max(1200),
components: z.array(z.string()),
- jsx: z.string(),
+ jsx: z.string().min(1, "nonempty"),
command: z.union([
// Using client* friendly imports because RequestParamsSchema
// is used to parse the form data on the client too.
@@ -55,33 +55,33 @@ export const action = async ({ request }: ActionArgs) => {
};
}
- if (env.PEXELS_API_KEY === undefined) {
+ if (
+ env.OPENAI_ORG === undefined ||
+ env.OPENAI_ORG.startsWith("org-") === false
+ ) {
return {
id: "ai",
...createErrorResponse({
- error: "ai.invalidApiKey",
+ error: "ai.invalidOrg",
status: 401,
- debug: "Invalid Pexels api key",
+ debug: "Invalid OpenAI API organization",
}),
llmMessages: [],
};
}
- const PEXELS_API_KEY = env.PEXELS_API_KEY;
- if (
- env.OPENAI_ORG === undefined ||
- env.OPENAI_ORG.startsWith("org-") === false
- ) {
+ if (env.PEXELS_API_KEY === undefined) {
return {
id: "ai",
...createErrorResponse({
- error: "ai.invalidOrg",
+ error: "ai.invalidApiKey",
status: 401,
- debug: "Invalid OpenAI API organization",
+ debug: "Invalid Pexels api key",
}),
llmMessages: [],
};
}
+ const PEXELS_API_KEY = env.PEXELS_API_KEY;
const parsed = RequestParamsSchema.safeParse(await request.json());