Skip to content

Automate browser based workflows with AI

SKY-15844: Publish blog categories and unblock content builds (#8529)

Shuchang Zheng76ea4ee8800f
diff --git a/skyvern-frontend/src/components/KeyValueInput.test.tsx b/skyvern-frontend/src/components/KeyValueInput.test.tsx
new file mode 100644
index 000000000..2d632d057
--- /dev/null
+++ b/skyvern-frontend/src/components/KeyValueInput.test.tsx
@@ -0,0 +1,155 @@
+// @vitest-environment jsdom
+
+import {
+ cleanup,
+ fireEvent,
+ render as rtlRender,
+ screen,
+} from "@testing-library/react";
+import { StrictMode } from "react";
+import { afterEach, describe, expect, test, vi } from "vitest";
+
+import { KeyValueInput, type KeyValueInputProps } from "./KeyValueInput";
+
+// Both app entrypoints mount under StrictMode, which double-invokes render and
+// state updaters — the conditions these assertions have to hold under.
+function render(props: KeyValueInputProps) {
+ return rtlRender(
+ <StrictMode>
+ <KeyValueInput {...props} />
+ </StrictMode>,
+ );
+}
+
+const toastMock = vi.hoisted(() => vi.fn());
+vi.mock("./ui/use-toast", () => ({ toast: toastMock }));
+
+afterEach(() => {
+ cleanup();
+ toastMock.mockReset();
+});
+
+function pairIds(): string[] {
+ return Array.from(document.querySelectorAll("[data-pair-id]")).map(
+ (el) => el.getAttribute("data-pair-id") ?? "",
+ );
+}
+
+function blurOutside() {
+ fireEvent.blur(screen.getAllByPlaceholderText("Header")[0]!, {
+ relatedTarget: null,
+ });
+}
+
+describe("KeyValueInput", () => {
+ // Mounting used to hand the parent a re-serialized value ("{}" became ""),
+ // so merely opening a settings panel wrote to the form it lives in.
+ test.each([
+ ["an empty object", {} as Record<string, string>],
+ ["an empty JSON string", "{}"],
+ ["null", null],
+ ["a populated object", { "X-Trace": "1" }],
+ ["a populated JSON string", '{"X-Trace":"1"}'],
+ ])("mounting with %s does not notify the parent", (_label, value) => {
+ const onChange = vi.fn();
+ render({ value, onChange });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ test("a user edit still propagates, matching the value's shape", () => {
+ const onChange = vi.fn();
+ render({ value: '{"X-Trace":"1"}', onChange });
+
+ fireEvent.change(screen.getByPlaceholderText("Value"), {
+ target: { value: "2" },
+ });
+
+ expect(onChange).toHaveBeenCalledWith('{"X-Trace":"2"}');
+ });
+
+ test("an object-shaped value emits an object", () => {
+ const onChange = vi.fn();
+ render({ value: { "X-Trace": "1" }, onChange });
+
+ fireEvent.change(screen.getByPlaceholderText("Value"), {
+ target: { value: "2" },
+ });
+
+ expect(onChange).toHaveBeenCalledWith({ "X-Trace": "2" });
+ });
+
+ // Rebuilding every row (new nanoid = new React key) on focus-out remounted
+ // the inputs, dropping the caret and re-firing this same handler for the
+ // input being removed.
+ test("leaving the component keeps existing rows mounted", () => {
+ const onChange = vi.fn();
+ render({ value: '{"X-Trace":"1"}', onChange });
+ const before = pairIds();
+
+ blurOutside();
+
+ expect(pairIds()).toEqual(before);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ test("leaving the component resolves a duplicate key, last one winning", () => {
+ const onChange = vi.fn();
+ render({ value: '{"X-Trace":"1"}', onChange });
+
+ fireEvent.click(screen.getByRole("button", { name: /Add/ }));
+ const keys = screen.getAllByPlaceholderText("Header");
+ fireEvent.change(keys[1]!, { target: { value: "X-Trace" } });
+ fireEvent.change(screen.getAllByPlaceholderText("Value")[1]!, {
+ target: { value: "2" },
+ });
+ onChange.mockReset();
+
+ blurOutside();
+
+ expect(screen.getAllByPlaceholderText("Header")).toHaveLength(1);
+ expect(onChange).toHaveBeenCalledWith('{"X-Trace":"2"}');
+ expect(toastMock).toHaveBeenCalledTimes(1);
+ });
+
+ // Walking the rows in reverse compared each loser against the previous row
+ // rather than the survivor, so the first toast named a value the user never
+ // ends up with.
+ test("every duplicate toast names the value that survives", () => {
+ const onChange = vi.fn();
+ render({ value: '{"X-Trace":"1"}', onChange });
+
+ for (const suffix of ["2", "3"]) {
+ fireEvent.click(screen.getByRole("button", { name: /Add/ }));
+ const rows = screen.getAllByPlaceholderText("Header");
+ fireEvent.change(rows[rows.length - 1]!, {
+ target: { value: "X-Trace" },
+ });
+ const values = screen.getAllByPlaceholderText("Value");
+ fireEvent.change(values[values.length - 1]!, {
+ target: { value: suffix },
+ });
+ }
+
+ blurOutside();
+
+ expect(onChange).toHaveBeenCalledWith('{"X-Trace":"3"}');
+ expect(toastMock).toHaveBeenCalledTimes(2);
+ for (const call of toastMock.mock.calls) {
+ expect(call[0].description).toContain("to '3'");
+ }
+ });
+
+ test("leaving the component drops a row the user never named", () => {
+ const onChange = vi.fn();
+ render({ value: '{"X-Trace":"1"}', onChange });
+
+ fireEvent.click(screen.getByRole("button", { name: /Add/ }));
+ expect(screen.getAllByPlaceholderText("Header")).toHaveLength(2);
+ onChange.mockReset();
+
+ blurOutside();
+
+ expect(screen.getAllByPlaceholderText("Header")).toHaveLength(1);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/skyvern-frontend/src/components/KeyValueInput.tsx b/skyvern-frontend/src/components/KeyValueInput.tsx
index b4dd59ac4..3693862ff 100644
--- a/skyvern-frontend/src/components/KeyValueInput.tsx
+++ b/skyvern-frontend/src/components/KeyValueInput.tsx
@@ -1,5 +1,5 @@
import { PlusIcon, Cross2Icon } from "@radix-ui/react-icons";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { nanoid } from "nanoid";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
@@ -41,6 +41,41 @@ function parsePairs(value: Record<string, string> | string | null): KV[] {
return [];
}
+/** The rows that actually make it into the emitted map: keyed, first-wins. */
+function effectiveEntries(pairs: Array<Pair | KV>): KV[] {
+ const seen = new Set<string>();
+ const entries: KV[] = [];
+ for (const { key, value } of pairs) {
+ if (!key || seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ entries.push({ key, value });
+ }
+ return entries;
+}
+
+function sameEntries(a: KV[], b: KV[]): boolean {
+ return (
+ a.length === b.length &&
+ a.every((entry, index) => {
+ const other = b[index];
+ return other?.key === entry.key && other?.value === entry.value;
+ })
+ );
+}
+
+function serialize(
+ entries: KV[],
+ asString: boolean,
+): Record<string, string> | string | null {
+ if (entries.length === 0) {
+ return asString ? "" : null;
+ }
+ const obj = Object.fromEntries(entries.map(({ key, value }) => [key, value]));
+ return asString ? JSON.stringify(obj) : obj;
+}
+
function KeyValueInput({
value,
onChange,
@@ -52,32 +87,31 @@ function KeyValueInput({
parsePairs(value).map((p) => ({ id: nanoid(), ...p })),
);
+ // `value` is read at emit time rather than tracked as a dependency: this
+ // component owns the rows once mounted, and re-deriving them from the prop
+ // would fight the parent that renders the value we just emitted.
+ const valueRef = useRef(value);
useEffect(() => {
- const obj: Record<string, string> = {};
- let hasDuplicateKey = false;
+ valueRef.current = value;
+ });
- for (const { key, value } of pairs) {
- if (!key) {
- continue;
- }
- if (key in obj) {
- hasDuplicateKey = true;
- continue;
- }
- obj[key] = value;
+ useEffect(() => {
+ const hasDuplicateKey =
+ new Set(pairs.filter((p) => p.key).map((p) => p.key)).size !==
+ pairs.filter((p) => p.key).length;
+ if (hasDuplicateKey) {
+ return;
}
- if (!hasDuplicateKey) {
- const output =
- typeof value === "string"
- ? Object.keys(obj).length
- ? JSON.stringify(obj)
- : ""
- : Object.keys(obj).length
- ? obj
- : null;
- onChange(output);
+ const entries = effectiveEntries(pairs);
+ // Mounting must not dirty the form. Serializing `{}` to `""` (or `null` to
+ // `null`) and handing that up on mount made merely opening a settings panel
+ // write to the parent's form state, re-rendering every field in it.
+ if (sameEntries(entries, effectiveEntries(parsePairs(valueRef.current)))) {
+ return;
}
+
+ onChange(serialize(entries, typeof valueRef.current === "string"));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pairs]);
@@ -110,52 +144,47 @@ function KeyValueInput({
*/
const handleBlurCapture = (e: React.FocusEvent<HTMLDivElement>) => {
if (
- e.relatedTarget === null ||
- (e.currentTarget &&
- e.relatedTarget &&
- !e.currentTarget.contains(e.relatedTarget as Node))
+ !(
+ e.relatedTarget === null ||
+ (e.currentTarget &&
+ e.relatedTarget &&
+ !e.currentTarget.contains(e.relatedTarget as Node))
+ )
) {
- const obj: Record<string, string> = {};
- const reversedPairs = [...pairs].reverse();
- for (const { key, value } of reversedPairs) {
- if (!key && !value) {
- continue;
- }
- if (key) {
- if (key in obj) {
- const oldValue = value;
- const newValue = obj[key];
- toast({
- variant: "warning",
- title: `Duplicate Header ('${key}')`,
- description: `Header '${key}' already existed. It was changed from '${oldValue}' to '${newValue}'.`,
- });
- continue;
- }
- obj[key] = value;
- }
+ return;
+ }
+
+ // Resolved before anything is toasted so every loser is reported against
+ // the value that actually survives, and outside the state updater, which
+ // React is free to invoke more than once.
+ const winners = new Map<string, Pair>();
+ for (const pair of pairs) {
+ if (pair.key) {
+ winners.set(pair.key, pair);
+ }
+ }
+
+ for (const pair of pairs) {
+ const winner = pair.key ? winners.get(pair.key) : undefined;
+ if (!winner || winner === pair) {
+ continue;
}
+ toast({
+ variant: "warning",
+ title: `Duplicate Header ('${pair.key}')`,
+ description: `Header '${pair.key}' already existed. It was changed from '${pair.value}' to '${winner.value}'.`,
+ });
+ }
- const reversedObj = Object.fromEntries(Object.entries(obj).reverse());
-
- const output =
- typeof value === "string"
- ? Object.keys(reversedObj).length
- ? JSON.stringify(reversedObj)
- : ""
- : Object.keys(reversedObj).length
- ? reversedObj
- : null;
-
- onChange(output);
-
- setPairs(
- Object.entries(reversedObj).map(([key, value]) => ({
- id: nanoid(),
- key,
- value,
- })),
- );
+ const next = Array.from(winners.values());
+ // Row ids are React keys. Handing back a new array of rows on every
+ // focus-out remounted every input, which drops the caret and — when the
+ // focused input is the one being removed — re-enters this handler.
+ const unchanged =
+ next.length === pairs.length &&
+ next.every((pair, index) => pair.id === pairs[index]?.id);
+ if (!unchanged) {
+ setPairs(next);
}
};
diff --git a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx
index 85cdb6aa9..ca884b83d 100644
--- a/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx
+++ b/skyvern-frontend/src/routes/workflows/RunWorkflowForm.tsx
@@ -4,7 +4,7 @@ import {
PlayIcon,
ReloadIcon,
} from "@radix-ui/react-icons";
-import { type ReactNode, useEffect, useMemo, useState } from "react";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { type FieldErrors, useForm } from "react-hook-form";
import { Link, useLocation, useNavigate, useParams } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
@@ -135,6 +135,27 @@ function validateWorkflowForRun(
return getLoginBlocksWithoutCredentials(workflow.workflow_definition.blocks);
}
+/**
+ * Compares the raw form values, not the parsed ones: parsing a json parameter
+ * mints a fresh object every call, so comparing after the parse would report
+ * "changed" on every keystroke for any workflow that has one.
+ */
+function isSameRunParameters(
+ previous: Record<string, unknown> | null,
+ next: Record<string, unknown>,
+): boolean {
+ if (previous === null) {
+ return false;
+ }
+ const previousKeys = Object.keys(previous);
+ return (
+ previousKeys.length === Object.keys(next).length &&
+ previousKeys.every(
+ (key) => key in next && Object.is(previous[key], next[key]),
+ )
+ );
+}
+
// Utility function to omit specified keys from an object
function omit<T extends Record<string, unknown>, K extends keyof T>(
obj: T,
@@ -683,6 +704,7 @@ function RunWorkflowForm({
string,
unknown
> | null>(null);
+ const rawRunParametersRef = useRef<Record<string, unknown> | null>(null);
const [cacheKeyValue, setCacheKeyValue] = useState<string>("");
const [isFormReset, setIsFormReset] = useState(false);
const cacheKey = workflow?.cache_key ?? "default";
@@ -819,14 +841,18 @@ function RunWorkflowForm({
"cdpConnectHeaders",
"cdpAddress",
"runWith",
+ "aiFallback",
]);
- const parsedParameters = parseValuesForWorkflowRun(
- parameters,
- workflowParameters,
- );
+ // A settings-only edit still fires this subscription, and a fresh object
+ // would re-render the whole form (every CodeMirror editor in it included)
+ // for a parameter set that did not move.
+ if (isSameRunParameters(rawRunParametersRef.current, parameters)) {
+ return;
+ }
+ rawRunParametersRef.current = parameters;
- setRunParameters(parsedParameters);
+ setRunParameters(parseValuesForWorkflowRun(parameters, workflowParameters));
}
const handleInvalid = (errors: FieldErrors<RunWorkflowFormType>) => {