Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(prompts): save editor state to sessionStorage and restore on remount (#11618)

Nimar3f77e7a09181
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index a7c0a8f411..3dddc0ea16 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -1,6 +1,6 @@
import { capitalize } from "lodash";
import router from "next/router";
-import { useState, useEffect } from "react";
+import { useState, useEffect, useRef } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/src/components/ui/button";
import { Checkbox } from "@/src/components/ui/checkbox";
@@ -49,6 +49,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";
import { useQueryParam } from "use-query-params";
import { usePromptNameValidation } from "@/src/features/prompts/hooks/usePromptNameValidation";
+import { useFormPersistence } from "@/src/hooks/useFormPersistence";
type NewPromptFormProps = {
initialPrompt?: Prompt | null;
@@ -165,6 +166,7 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
createPromptMutation
.mutateAsync(newPrompt)
.then((newPrompt) => {
+ clearDraft();
onFormSuccess?.();
form.reset();
if ("name" in newPrompt) {
@@ -178,10 +180,13 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
});
}
+ const hasInitializedMessages = useRef(false);
useEffect(() => {
+ if (hasInitializedMessages.current) return;
+ hasInitializedMessages.current = true;
+
if (shouldLoadPlaygroundCache && playgroundCache) {
form.setValue("type", PromptType.Chat);
-
setInitialMessages(playgroundCache.messages);
} else if (initialPrompt?.type === PromptType.Chat) {
setInitialMessages(initialPrompt.prompt);
@@ -194,6 +199,27 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
form,
});
+ const formId = initialPrompt
+ ? `prompt-edit:${initialPrompt.id}`
+ : "prompt-new";
+
+ const { hadDraft, clearDraft } = useFormPersistence({
+ formId,
+ projectId: projectId ?? "",
+ form,
+ enabled: Boolean(projectId),
+ onDraftRestored: (draft) => {
+ // Restore chat messages if present
+ if (
+ draft.chatPrompt &&
+ Array.isArray(draft.chatPrompt) &&
+ draft.chatPrompt.length > 0
+ ) {
+ setInitialMessages(draft.chatPrompt);
+ }
+ },
+ });
+
return (
<Form {...form}>
<form
@@ -293,6 +319,26 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
</TabsTrigger>
</TabsList>
) : null}
+ {hadDraft && (
+ <p className="-mt-2 mb-1 text-right text-xs text-muted-foreground">
+ Draft restored.{" "}
+ <button
+ type="button"
+ className="underline hover:text-foreground"
+ onClick={() => {
+ clearDraft();
+ form.reset(defaultValues);
+ setInitialMessages(
+ initialPrompt?.type === PromptType.Chat
+ ? initialPrompt.prompt
+ : [],
+ );
+ }}
+ >
+ Discard
+ </button>
+ </p>
+ )}
<TabsContent value={PromptType.Text}>
<FormField
control={form.control}
diff --git a/web/src/hooks/useFormPersistence.ts b/web/src/hooks/useFormPersistence.ts
new file mode 100644
index 0000000000..b1ab1e755e
--- /dev/null
+++ b/web/src/hooks/useFormPersistence.ts
@@ -0,0 +1,95 @@
+import { useEffect, useRef, useCallback, useState } from "react";
+import { type UseFormReturn } from "react-hook-form";
+import { useDebounce } from "./useDebounce";
+
+const getStorageKey = (projectId: string, formId: string) =>
+ `langfuse:form-draft:${projectId}:${formId}`;
+
+export interface UseFormPersistenceOptions<T extends Record<string, unknown>> {
+ formId: string;
+ projectId: string;
+ form: UseFormReturn<T>;
+ debounceMs?: number;
+ enabled?: boolean;
+ onDraftRestored?: (draft: Partial<T>) => void;
+}
+
+export interface UseFormPersistenceReturn {
+ hadDraft: boolean;
+ hasDraft: boolean;
+ clearDraft: () => void;
+}
+
+export function useFormPersistence<T extends Record<string, unknown>>({
+ formId,
+ projectId,
+ form,
+ debounceMs = 350,
+ enabled = true,
+ onDraftRestored,
+}: UseFormPersistenceOptions<T>): UseFormPersistenceReturn {
+ const storageKey = getStorageKey(projectId, formId);
+ const [hadDraft, setHadDraft] = useState(false);
+ const [hasDraft, setHasDraft] = useState(false);
+ const isInitialized = useRef(false);
+ const lastSaved = useRef<string | null>(null);
+ const onDraftRestoredRef = useRef(onDraftRestored);
+ onDraftRestoredRef.current = onDraftRestored;
+
+ // Restore on mount (once)
+ useEffect(() => {
+ if (!enabled || isInitialized.current) return;
+ isInitialized.current = true;
+
+ try {
+ const saved = sessionStorage.getItem(storageKey);
+ if (saved) {
+ const draft = JSON.parse(saved) as Partial<T>;
+ const current = form.getValues();
+ form.reset({ ...current, ...draft } as T, {
+ keepDirty: true,
+ keepTouched: true,
+ });
+ setHadDraft(true);
+ setHasDraft(true);
+ onDraftRestoredRef.current?.(draft);
+ }
+ } catch {
+ sessionStorage.removeItem(storageKey);
+ }
+ }, [enabled, storageKey, form]);
+
+ // Save on change (debounced)
+ const saveDraft = useDebounce(
+ (values: T) => {
+ const serialized = JSON.stringify(values);
+ if (serialized === lastSaved.current) return;
+ try {
+ sessionStorage.setItem(storageKey, serialized);
+ lastSaved.current = serialized;
+ setHasDraft(true);
+ } catch {
+ /* storage full - ignore */
+ }
+ },
+ debounceMs,
+ false,
+ );
+
+ useEffect(() => {
+ if (!enabled) return;
+ const sub = form.watch((values) => {
+ if (form.formState.isDirty) saveDraft(values as T);
+ });
+ return () => sub.unsubscribe();
+ }, [form, enabled, saveDraft]);
+
+ const clearDraft = useCallback(() => {
+ sessionStorage.removeItem(storageKey);
+ lastSaved.current = null;
+ setHasDraft(false);
+ setHadDraft(false);
+ }, [storageKey]);
+
+ return { hadDraft, hasDraft, clearDraft };
+}