Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

fix(prompt storage): rework prompt storage into a master-detail layout (#8692)

Leo Borcherding0be140dbd458
diff --git a/studio/frontend/src/features/chat/prompt-storage/mutation-lock.ts b/studio/frontend/src/features/chat/prompt-storage/mutation-lock.ts
new file mode 100644
index 00000000000..6226c0d4faa
--- /dev/null
+++ b/studio/frontend/src/features/chat/prompt-storage/mutation-lock.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// One in-flight mutation per row, tracked by id.
+//
+// The detail panes are keyed by row id, so selecting another row unmounts them.
+// A lock held in the pane comes back false on return, and since the save is an
+// unconditional PUT it can then land after a DELETE and write the deleted row
+// straight back. The set therefore lives above the key, and these are its two
+// transitions, kept here so they can be tested without a renderer.
+
+export type LockSet = ReadonlySet<string>;
+
+/** Returns the next set, and whether this caller took the lock. */
+export function acquire(held: LockSet, id: string): [LockSet, boolean] {
+ if (held.has(id)) return [held, false];
+ return [new Set(held).add(id), true];
+}
+
+// Prompts and prompt lists are separate tables with independent ids, so the same
+// id can name one of each and an import can produce that. One set keyed on the
+// raw id would then let a prompt's save disable the unrelated list's controls.
+export function lockKey(kind: "prompt" | "list", id: string): string {
+ return `${kind}:${id}`;
+}
+
+/** Releasing an id nobody holds returns the same set, so React skips the render. */
+export function release(held: LockSet, id: string): LockSet {
+ if (!held.has(id)) return held;
+ const next = new Set(held);
+ next.delete(id);
+ return next;
+}
+
+// A save is async and the editor stays usable while it runs, so by the time the
+// PUT resolves the draft may have moved on. Clearing it unconditionally throws
+// away whatever was typed meanwhile, which is newer than the server's copy and
+// is the user's most recent intent. Only clear what was actually sent.
+
+export function samePromptDraft(
+ a: { name: string; text: string },
+ b: { name: string; text: string },
+): boolean {
+ return a.name === b.name && a.text === b.text;
+}
+
+export function sameListDraft(
+ a: { name: string; items: readonly string[] },
+ b: { name: string; items: readonly string[] },
+): boolean {
+ return (
+ a.name === b.name &&
+ a.items.length === b.items.length &&
+ a.items.every((item, i) => item === b.items[i])
+ );
+}
diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
index f126cbc97bd..3ba2337e544 100644
--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx
@@ -1,6 +1,16 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -18,15 +28,25 @@ import { HugeiconsIcon } from "@hugeicons/react";
import {
BookmarkIcon,
DownloadIcon,
- GripVerticalIcon,
+ EyeIcon,
LayoutListIcon,
PencilIcon,
PlayIcon,
PlusIcon,
+ RotateCcwIcon,
Trash2Icon,
UploadIcon,
XIcon,
} from "lucide-react";
+import { MarkdownPreview } from "@/components/markdown/markdown-preview";
+import { SortablePromptItems } from "./sortable-prompt-items";
+import {
+ acquire,
+ lockKey,
+ release,
+ sameListDraft,
+ samePromptDraft,
+} from "./mutation-lock";
import { Tick02Icon } from "@/lib/tick-icon";
import {
type ReactElement,
@@ -1323,170 +1343,473 @@ function ExportModal({
);
}
-function PromptCard({
+// Unsaved edits live in the parent keyed by entry id, so switching rows in the
+// rail never silently throws away what you typed.
+type PromptDraft = { name: string; text: string };
+type ListDraft = { name: string; items: string[] };
+
+// Factories, not shared constants: every reset would otherwise hand back the
+// same `items` array, one in-place edit from corrupting it for good.
+const emptyPromptDraft = (): PromptDraft => ({ name: "", text: "" });
+const emptyListDraft = (): ListDraft => ({ name: "", items: ["", ""] });
+
+// Selecting the Lists tab auto-selects its first row, so the detail pane mounts
+// the editor with no click, and one controlled textarea per item makes that cost
+// grow faster than the item count: measured in Chromium, 100 items settle in
+// 247ms, 200 in 568ms, 500 in 2.5s and 2000 in 36s, against a flat 80ms on the
+// collapsed card this replaced. The backend accepts 10000 items in one list
+// (studio/backend/routes/prompts.py), which an import can produce, so past this
+// many the editor waits to be asked for. Nothing else does: save, run and export
+// all read the full items.
+const EDITOR_ROW_LIMIT = 100;
+
+function relativeTime(ts: number): string {
+ const secs = Math.max(0, Math.round((Date.now() - ts) / 1000));
+ if (secs < 60) return "just now";
+ const mins = Math.round(secs / 60);
+ if (mins < 60) return `${mins}m ago`;
+ const hours = Math.round(mins / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.round(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return new Date(ts).toLocaleDateString();
+}
+
+// `current` drives the roving tabindex and stays true while a New form covers
+// the pane: without it every row is tabbable, so reaching the editor means
+// tabbing through the whole library.
+function RailRow({
+ title,
+ preview,
+ selected,
+ current,
+ dirty,
+ badge,
+ leading,
+ onSelect,
+}: {
+ title: string;
+ preview: string;
+ selected: boolean;
+ current: boolean;
+ dirty: boolean;
+ badge?: string;
+ leading?: ReactElement | null;
+ onSelect: () => void;
+}): ReactElement {
+ return (
+ <button
+ type="button"
+ data-rail-row=""
+ tabIndex={current ? 0 : -1}
+ aria-current={selected ? "true" : undefined}
+ onClick={onSelect}
+ className={cn(
+ "w-full rounded-lg px-2.5 py-2 text-left transition-colors border",
+ "focus-visible:ring-1 focus-visible:ring-ring outline-none",
+ selected
+ ? "bg-muted/70 border-border"
+ : "border-transparent hover:bg-muted/40",
+ )}
+ >
+ <div className="flex items-center gap-1.5">
+ {leading}
+ <span className="flex-1 truncate text-xs font-medium tracking-tight">{title}</span>
+ {dirty && (
+ <span className="size-1.5 shrink-0 rounded-full bg-primary" title="Unsaved changes" />
+ )}
+ {badge && (
+ <span className="shrink-0 rounded-full bg-muted px-1.5 text-ui-11 tabular-nums text-muted-foreground">
+ {badge}
+ </span>
+ )}
+ </div>
+ <p className="mt-0.5 truncate text-ui-11 text-muted-foreground/70">{preview}</p>
+ </button>
+ );
+}
+
+function EmptyDetail({
+ icon,
+ title,
+ hint,
+ onClearSearch,
+}: {
+ icon: ReactElement;
+ title: string;
+ hint?: string;
+ onClearSearch?: () => void;
+}): ReactElement {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
+ <div className="flex size-12 items-center justify-center rounded-2xl bg-muted/60">{icon}</div>
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-medium text-muted-foreground">{title}</p>
+ {hint && <p className="text-xs text-muted-foreground/60">{hint}</p>}
+ {onClearSearch && (
+ <button type="button" onClick={onClearSearch} className="text-xs text-primary hover:underline">
+ Clear search
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// Deleting a dirty entry destroys the stored copy and the only copy of the
+// unsaved draft at once, so that case asks first.
+function UnsavedDeleteConfirm({
+ open,
+ onOpenChange,
+ kind,
+ name,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ kind: "prompt" | "list";
+ name: string;
+ onConfirm: () => void;
+}): ReactElement {
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Delete {kind} with unsaved changes
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ <span className="font-medium text-foreground">&quot;{name}&quot;</span> has
+ unsaved edits. Deleting discards the saved {kind} and those edits together.
+ This cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="destructive" onClick={onConfirm}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
+
+function PromptDetail({
entry,
+ draft,
+ onDraftChange,
onUse,
onExport,
onRefresh,
+ onDeleted,
+ onSaved,
+ pending,
+ runMutation,
}: {
entry: PromptEntry;
+ draft: PromptDraft | undefined;
+ onDraftChange: (draft: PromptDraft | undefined) => void;
onUse: (text: string) => void;
onExport: (entry: PromptEntry) => void;
- onRefresh: () => void;
+ onRefresh: () => Promise<void>;
+ onDeleted: (deletedId: string) => void;
+ onSaved: (submitted: PromptDraft) => void;
+ pending: boolean;
+ runMutation: (id: string, fn: () => Promise<void>) => Promise<void>;
}): ReactElement {
- const [editing, setEditing] = useState(false);
- const [name, setName] = useState(entry.name);
- const [text, setText] = useState(entry.text);
const pinnedPromptIds = usePlusMenuPrefsStore((s) => s.pinnedPromptIds);
const togglePinnedPrompt = usePlusMenuPrefsStore((s) => s.togglePinnedPrompt);
const isPinned = pinnedPromptIds.includes(entry.id);
+ const [preview, setPreview] = useState(false);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+
+ const name = draft?.name ?? entry.name;
+ const text = draft?.text ?? entry.text;
+ const dirty = draft !== undefined;
+
+ const update = useCallback(
+ (patch: Partial<PromptDraft>) => {
+ const next = { name, text, ...patch };
+ if (next.name === entry.name && next.text === entry.text) onDraftChange(undefined);
+ else onDraftChange(next);
+ },
+ [name, text, entry.name, entry.text, onDraftChange],
+ );
+ // One mutation at a time, and the lock lives in the parent: this pane is
+ // keyed by row id, so selecting another row unmounts it and a local lock
+ // would come back false. PUT is an unconditional upsert, so a Save still in
+ // flight can land after a DELETE and write the deleted row straight back.
const handleSave = useCallback(async () => {
- const trimName = name.trim();
const trimText = text.trim();
if (!trimText) return;
- await savePromptEntry({ ...entry, name: trimName || "Untitled Prompt", text: trimText, updatedAt: now() });
- setEditing(false);
- onRefresh();
- }, [entry, name, text, onRefresh]);
+ // Snapshot what is going to the server. The editor stays usable while the
+ // request is in flight, so the draft can move on before it resolves.
+ const submitted: PromptDraft = { name, text };
+ await runMutation(lockKey("prompt", entry.id), async () => {
+ try {
+ await savePromptEntry({
+ ...entry,
+ name: name.trim() || "Untitled Prompt",
+ text: trimText,
+ updatedAt: now(),
+ });
+ // Refresh before dropping the draft. Dropping it first uncovers the
+ // entry this pane still holds, which is the pre-save copy, so the
+ // editor flashes the old text until the fetch lands.
+ await onRefresh();
+ onSaved(submitted);
+ } catch (err) {
+ toast.error("Could not save prompt", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ }
+ });
+ }, [entry, name, text, onSaved, onRefresh, runMutation]);
const handleDelete = useCallback(async () => {
- await deletePromptEntry(entry.id);
- onRefresh();
- }, [entry.id, onRefresh]);
-
- if (editing) {
- return (
- <div className="rounded-xl border border-border/50 bg-muted/30 p-4 flex flex-col gap-3">
- <input
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="Prompt name..."
- className="w-full rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
+ await runMutation(lockKey("prompt", entry.id), async () => {
+ try {
+ await deletePromptEntry(entry.id);
+ } catch (err) {
+ toast.error("Could not delete prompt", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ return;
+ }
+ onDraftChange(undefined);
+ // Refresh before clearing, or the keep-a-row-selected pass runs against a
+ // list that still holds this row and can select the deleted entry back.
+ await onRefresh();
+ // Id goes up so the parent only clears if this row is still selected: the
+ // delete is awaited, and a click elsewhere meanwhile would be undone.
+ onDeleted(entry.id);
+ });
+ }, [entry.id, onDraftChange, onDeleted, onRefresh, runMutation]);
+
+ // Export what the pane shows, normalised as saving would, or a dirty entry
+ // writes a file that does not match the screen.
+ const exportValue: PromptEntry = dirty
+ ? { ...entry, name: name.trim() || "Untitled Prompt", text: text.trim() }
+ : entry;
+
+ return (
+ <>
+ <div className="flex h-full min-h-0 flex-col gap-3">
+ <input
+ value={name}
+ onChange={(e) => update({ name: e.target.value })}
+ placeholder="Prompt name..."
+ className="w-full shrink-0 rounded-lg border-0 bg-background/80 px-3 py-2 text-sm font-medium ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
+ />
+ {preview ? (
+ <MarkdownPreview
+ markdown={text}
+ className="min-h-0 max-h-none flex-1 rounded-lg border-border/60 bg-background/40 p-3 text-sm"
/>
+ ) : (
<textarea
value={text}
- onChange={(e) => setText(e.target.value)}
- rows={4}
+ onChange={(e) => update({ text: e.target.value })}
placeholder="Prompt text..."
- className="w-full resize-y rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
+ className="min-h-0 flex-1 w-full resize-none rounded-lg border-0 bg-background/80 px-3 py-2.5 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
/>
- <div className="flex gap-2 justify-end">
- <Button size="sm" variant="ghost" onClick={() => { setName(entry.name); setText(entry.text); setEditing(false); }}>
- <XIcon className="size-3.5 mr-1" />Cancel
- </Button>
- <Button size="sm" onClick={handleSave}>
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save
- </Button>
- </div>
+ )}
+ <div className="flex shrink-0 items-center gap-2 text-ui-11 text-muted-foreground/70">
+ <span className="tabular-nums">{text.length.toLocaleString()} characters</span>
+ <span className="text-muted-foreground/30">·</span>
+ <span>updated {relativeTime(entry.updatedAt)}</span>
+ {dirty && (
+ <>
+ <span className="text-muted-foreground/30">·</span>
+ <span className="text-primary">unsaved changes</span>
+ </>
+ )}
</div>
- );
- }
-
- return (
- <div className="group rounded-xl border border-border/60 bg-card p-4 flex flex-col gap-2 hover:border-border hover:shadow-sm transition-all">
- <div className="flex items-center gap-2">
- {isPinned ? (
- <BookmarkIcon className="size-3.5 shrink-0 fill-primary text-primary" />
- ) : null}
- <span className="font-semibold text-sm flex-1 truncate tracking-tight">{entry.name}</span>
- <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 transition-opacity">
- <button
- type="button"
- onClick={() => onUse(entry.text)}
- className="flex items-center gap-1.5 rounded-lg bg-primary px-2.5 py-1 text-xs font-semibold text-primary-foreground hover:bg-primary/90 transition-colors"
- title="Load into composer"
- >
- <PlayIcon className="size-3" />Use
- </button>
- <div className="mx-1 h-4 w-px bg-border/60" />
- <button
- type="button"
- onClick={() => togglePinnedPrompt(entry.id)}
- className={cn(
- "flex h-7 w-7 items-center justify-center rounded-lg transition-colors",
- isPinned
- ? "text-primary hover:bg-primary/10"
- : "text-muted-foreground hover:bg-muted hover:text-foreground",
- )}
- title={isPinned ? "Unpin from + menu" : "Pin to + menu"}
- >
- <BookmarkIcon
- className={cn("size-3.5", isPinned && "fill-primary")}
- />
- </button>
- <button
- type="button"
- onClick={() => onExport(entry)}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title="Export"
- >
- <DownloadIcon className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={() => setEditing(true)}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title="Edit"
- >
- <PencilIcon className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={handleDelete}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
- title="Delete"
- >
- <Trash2Icon className="size-3.5" />
- </button>
- </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-1 border-t border-border/50 pt-3">
+ <button
+ type="button"
+ onClick={() => togglePinnedPrompt(entry.id)}
+ className={cn(
+ "flex h-8 w-8 items-center justify-center rounded-lg transition-colors",
+ isPinned
+ ? "text-primary hover:bg-primary/10"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground",
+ )}
+ title={isPinned ? "Unpin from + menu" : "Pin to + menu"}
+ >
+ <BookmarkIcon className={cn("size-4", isPinned && "fill-primary")} />
+ </button>
+ <button
+ type="button"
+ onClick={() => onExport(exportValue)}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title="Export"
+ >
+ <DownloadIcon className="size-4" />
+ </button>
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => (dirty ? setConfirmingDelete(true) : void handleDelete())}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-muted-foreground"
+ title="Delete"
+ >
+ <Trash2Icon className="size-4" />
+ </button>
+ <div className="flex-1" />
+ {dirty && (
+ <Button size="sm" variant="ghost" onClick={() => onDraftChange(undefined)}>
+ <RotateCcwIcon className="size-3.5 mr-1" />Revert
+ </Button>
+ )}
+ <Button size="sm" variant="outline" onClick={() => setPreview((v) => !v)}>
+ {preview ? (
+ <><PencilIcon className="size-3.5 mr-1" />Edit</>
+ ) : (
+ <><EyeIcon className="size-3.5 mr-1" />Preview</>
+ )}
+ </Button>
+ <Button size="sm" variant="outline" disabled={pending || !dirty || !text.trim()} onClick={handleSave}>
+ <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save
+ </Button>
+ <Button size="sm" onClick={() => onUse(text)} disabled={!text.trim()}>
+ <PlayIcon className="size-3 mr-1" />Use
+ </Button>
</div>
- <p className="text-xs text-muted-foreground line-clamp-3 leading-relaxed">{entry.text}</p>
</div>
+ <UnsavedDeleteConfirm
+ open={confirmingDelete}
+ onOpenChange={setConfirmingDelete}
+ kind="prompt"
+ name={name.trim() || "Untitled Prompt"}
+ onConfirm={() => {
+ setConfirmingDelete(false);
+ void handleDelete();
+ }}
+ />
+ </>
);
}
-function NewPromptForm({ onClose, onRefresh }: { onClose: () => void; onRefresh: () => void }): ReactElement {
- const [name, setName] = useState("");
- const [text, setText] = useState("");
+// A create has no row id yet, so it cannot use the by-id mutation lock above.
+// The ref is the authority for the same reason it is there: React state is not
+// readable straight after scheduling it. Call this above the New forms, never
+// inside one: selecting a rail row unmounts the form, and a guard that dies with
+// it comes back false while its request is still out.
+function useCreateGuard(): {
+ creating: boolean;
+ create: (fn: () => Promise<void>) => Promise<void>;
+} {
+ const creatingRef = useRef(false);
+ const [creating, setCreating] = useState(false);
+ const create = useCallback(async (fn: () => Promise<void>) => {
+ if (creatingRef.current) return;
+ creatingRef.current = true;
+ setCreating(true);
+ try {
+ await fn();
+ } finally {
+ creatingRef.current = false;
+ setCreating(false);
+ }
+ }, []);
+ return { creating, create };
+}
- const handleSave = useCallback(async () => {
- const trimText = text.trim();
- if (!trimText) return;
- const ts = now();
- await savePromptEntry({
- id: newId(),
- name: name.trim() || "Untitled Prompt",
- text: trimText,
- createdAt: ts,
- updatedAt: ts,
- });
- onRefresh();
- onClose();
- }, [name, text, onClose, onRefresh]);
+// Draft lives in the parent, like the edit drafts: selecting a row hides this
+// form, and local state would be discarded with it.
+function NewPromptForm({
+ draft,
+ onDraftChange,
+ onClose,
+ onRefresh,
+ onCreated,
+ creating,
+ create,
+}: {
+ draft: PromptDraft;
+ onDraftChange: (draft: PromptDraft) => void;
+ onClose: () => void;
+ onRefresh: () => Promise<void>;
+ onCreated: (id: string, submitted: PromptDraft, fromOpenForm: boolean) => void;
+ creating: boolean;
+ create: (fn: () => Promise<void>) => Promise<void>;
+}): ReactElement {
+ const { name, text } = draft;
+ const setName = (value: string) => onDraftChange({ ...draft, name: value });
+ const setText = (value: string) => onDraftChange({ ...draft, text: value });
+ // A create outlives the form that started it. Selecting a row, switching tabs
+ // or reopening New all unmount this one, and reopening mounts a different one,
+ // so this answers "is the form the user is looking at still mine". Set in
+ // setup, not just at the ref: StrictMode replays setup, cleanup, setup, and
+ // the flag would stay false from that first cleanup for the pane's whole life.
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+
+ const handleSave = useCallback(
+ () =>
+ create(async () => {
+ const trimText = text.trim();
+ if (!trimText) return;
+ const ts = now();
+ const id = newId();
+ // What the request carries. The fields stay editable while it is out,
+ // so the draft can move on before it resolves.
+ const submitted: PromptDraft = { name, text };
+ try {
+ await savePromptEntry({
+ id,
+ name: name.trim() || "Untitled Prompt",
+ text: trimText,
+ createdAt: ts,
+ updatedAt: ts,
+ });
+ } catch (err) {
+ // Without this the rejection is unhandled and the form just sits
+ // there, so the prompt looks saved until the dialog is reopened.
+ toast.error("Could not create prompt", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ return;
+ }
+ // Await the refresh first, or the keep-a-row-selected effect runs
+ // against a list without the new id and bounces the selection off it.
+ await onRefresh();
+ // The parent resets the draft if it still holds what was sent, and moves
+ // the view to the new row only while this form is still the one on screen.
+ onCreated(id, submitted, mounted.current);
+ }),
+ [name, text, create, onRefresh, onCreated],
+ );
return (
- <div className="rounded-xl border border-border/50 bg-muted/30 p-4 flex flex-col gap-3">
- <p className="text-xs font-semibold text-muted-foreground">New Prompt</p>
+ <div className="flex h-full min-h-0 flex-col gap-3">
+ <p className="shrink-0 text-xs font-semibold text-muted-foreground">New Prompt</p>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Prompt name (optional)..."
autoFocus
- className="w-full rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
+ className="w-full shrink-0 rounded-lg border-0 bg-background/80 px-3 py-2 text-sm font-medium ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
/>
<textarea
value={text}
onChange={(e) => setText(e.target.value)}
- rows={4}
placeholder="Write your prompt here..."
- className="w-full resize-y rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
+ className="min-h-0 flex-1 w-full resize-none rounded-lg border-0 bg-background/80 px-3 py-2.5 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
/>
- <div className="flex gap-2 justify-end">
+ <div className="flex shrink-0 flex-wrap gap-2 justify-end border-t border-border/50 pt-3">
<Button size="sm" variant="ghost" onClick={onClose}>
<XIcon className="size-3.5 mr-1" />Cancel
</Button>
- <Button size="sm" onClick={handleSave} disabled={!text.trim()}>
+ <Button size="sm" onClick={handleSave} disabled={creating || !text.trim()}>
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save Prompt
</Button>
</div>
@@ -1494,248 +1817,333 @@ function NewPromptForm({ onClose, onRefresh }: { onClose: () => void; onRefresh:
);
}
-function PromptListCard({
+function PromptListDetail({
entry,
+ draft,
+ onDraftChange,
onRunList,
onExport,
onRefresh,
+ onDeleted,
+ onSaved,
+ pending,
+ runMutation,
}: {
entry: PromptListEntry;
+ draft: ListDraft | undefined;
+ onDraftChange: (draft: ListDraft | undefined) => void;
onRunList?: (items: string[]) => void;
onExport: (entry: PromptListEntry) => void;
- onRefresh: () => void;
+ onRefresh: () => Promise<void>;
+ onDeleted: (deletedId: string) => void;
+ onSaved: (submitted: ListDraft) => void;
+ pending: boolean;
+ runMutation: (id: string, fn: () => Promise<void>) => Promise<void>;
}): ReactElement {
- const [editing, setEditing] = useState(false);
- const [name, setName] = useState(entry.name);
- const [items, setItems] = useState<string[]>(entry.items);
+ const [preview, setPreview] = useState(false);
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+
+ const name = draft?.name ?? entry.name;
+ const items = draft?.items ?? entry.items;
+ // Decided once per list and latched: this pane is keyed by row id, so selecting
+ // another list re-decides it, but Add prompt taking a 100-item list to 101 must
+ // not unmount the editor out from under the caret.
+ const [editorMounted, setEditorMounted] = useState(
+ () => items.length <= EDITOR_ROW_LIMIT,
+ );
+ const dirty = draft !== undefined;
+ const savable = items.filter((t) => t.trim()).length > 0;
+
+ const update = useCallback(
+ (patch: Partial<ListDraft>) => {
+ const next = { name, items, ...patch };
+ const same =
+ next.name === entry.name &&
+ next.items.length === entry.items.length &&
+ next.items.every((v, i) => v === entry.items[i]);
+ if (same) onDraftChange(undefined);
+ else onDraftChange(next);
+ },
+ [name, items, entry.name, entry.items, onDraftChange],
+ );
+ // See PromptDetail: a Save landing after a DELETE would upsert the row back.
+ // See PromptDetail: the lock is the parent's because this pane is keyed by
+ // row id and unmounts on a row switch.
const handleSave = useCallback(async () => {
const filtered = items.filter((t) => t.trim());
if (filtered.length === 0) return;
- await savePromptList({ ...entry, name: name.trim() || "Untitled List", items: filtered, updatedAt: now() });
- setEditing(false);
- onRefresh();
- }, [entry, name, items, onRefresh]);
+ // See PromptDetail: the editor stays usable while the request is in flight.
+ const submitted: ListDraft = { name, items };
+ await runMutation(lockKey("list", entry.id), async () => {
+ try {
+ await savePromptList({
+ ...entry,
+ name: name.trim() || "Untitled List",
+ items: filtered,
+ updatedAt: now(),
+ });
+ // See PromptDetail: the draft is what covers the pre-save entry.
+ await onRefresh();
+ onSaved(submitted);
+ } catch (err) {
+ toast.error("Could not save list", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ }
+ });
+ }, [entry, name, items, onSaved, onRefresh, runMutation]);
const handleDelete = useCallback(async () => {
- await deletePromptList(entry.id);
- onRefresh();
- }, [entry.id, onRefresh]);
-
- const addItem = useCallback(() => setItems((prev) => [...prev, ""]), []);
- const removeItem = useCallback(
- (i: number) => setItems((prev) => prev.filter((_, idx) => idx !== i)),
- [],
- );
- const updateItem = useCallback(
- (i: number, val: string) =>
- setItems((prev) => prev.map((v, idx) => (idx === i ? val : v))),
- [],
- );
+ await runMutation(lockKey("list", entry.id), async () => {
+ try {
+ await deletePromptList(entry.id);
+ } catch (err) {
+ toast.error("Could not delete list", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ return;
+ }
+ onDraftChange(undefined);
+ // See PromptDetail: clearing first can reselect the row being deleted.
+ await onRefresh();
+ // See PromptDetail: only the parent knows whether this row is still current.
+ onDeleted(entry.id);
+ });
+ }, [entry.id, onDraftChange, onDeleted, onRefresh, runMutation]);
+
+ // Run what the editor shows. Off entry.items, deleting every draft item left
+ // the button enabled on the stored length and ran the old list.
+ const runnableItems = items.filter((t) => t.trim());
+
+ // See PromptDetail: export the visible draft, not the last saved copy.
+ const exportValue: PromptListEntry = dirty
+ ? {
+ ...entry,
+ name: name.trim() || "Untitled List",
+ items: items.filter((t) => t.trim()),
+ }
+ : entry;
- if (editing) {
- return (
- <div className="rounded-xl border border-border/50 bg-muted/30 p-4 flex flex-col gap-3">
- <input
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="List name..."
- className="w-full rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
- />
- <p className="text-xs font-semibold text-muted-foreground">Prompts (sent in order)</p>
- <div className="flex flex-col gap-2">
- {items.map((item, i) => (
- <div key={i} className="flex items-start gap-2">
- <GripVerticalIcon className="size-4 mt-2.5 shrink-0 text-muted-foreground/30 cursor-grab" />
- <span className="text-xs font-medium text-muted-foreground/60 mt-2.5 w-5 shrink-0 text-right">{i + 1}.</span>
- <textarea
- value={item}
- onChange={(e) => updateItem(i, e.target.value)}
- rows={2}
- placeholder={`Prompt ${i + 1}...`}
- className="flex-1 resize-y rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
- />
+ return (
+ <>
+ <div className="flex h-full min-h-0 flex-col gap-3">
+ <input
+ value={name}
+ onChange={(e) => update({ name: e.target.value })}
+ placeholder="List name..."
+ className="w-full shrink-0 rounded-lg border-0 bg-background/80 px-3 py-2 text-sm font-medium ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
+ />
+ <p className="shrink-0 text-xs font-semibold text-muted-foreground">
+ Prompts, loaded into the composer one at a time
+ </p>
+ <div className="min-h-0 flex-1 overflow-y-auto pr-1 flex flex-col gap-2">
+ {editorMounted ? (
+ <>
+ <SortablePromptItems
+ items={items}
+ onChange={(next) => update({ items: next })}
+ preview={preview}
+ />
+ {preview ? null : (
<button
type="button"
- onClick={() => removeItem(i)}
- className="flex h-7 w-7 mt-1 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors shrink-0"
- title="Remove"
+ onClick={() => update({ items: [...items, ""] })}
+ className="flex items-center gap-1.5 self-start text-xs font-medium text-primary hover:text-primary/80 transition-colors"
>
- <XIcon className="size-3.5" />
+ <PlusIcon className="size-3.5" />Add prompt
</button>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1.5">
+ {items.slice(0, 5).map((item, i) => (
+ <p key={i} className="flex gap-2 text-xs leading-relaxed text-muted-foreground">
+ <span className="shrink-0 tabular-nums text-muted-foreground/40">{i + 1}.</span>
+ <span className="line-clamp-1">{item}</span>
+ </p>
+ ))}
</div>
- ))}
- </div>
+ <p className="text-ui-11 text-muted-foreground/60">
+ {items.length - 5} more. Opening the editor for a list this long takes a
+ while, so it waits for you.
+ </p>
+ <button
+ type="button"
+ onClick={() => setEditorMounted(true)}
+ className="flex items-center gap-1.5 self-start text-xs font-medium text-primary hover:text-primary/80 transition-colors"
+ >
+ <PencilIcon className="size-3.5" />Edit all {items.length} prompts
+ </button>
+ </>
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-2 text-ui-11 text-muted-foreground/70">
+ <span className="tabular-nums">{items.length} prompts</span>
+ <span className="text-muted-foreground/30">·</span>
+ <span>updated {relativeTime(entry.updatedAt)}</span>
+ {dirty && (
+ <>
+ <span className="text-muted-foreground/30">·</span>
+ <span className="text-primary">unsaved changes</span>
+ </>
+ )}
+ </div>
+ <div className="flex shrink-0 flex-wrap items-center gap-1 border-t border-border/50 pt-3">
<button
type="button"
- onClick={addItem}
- className="flex items-center gap-1.5 text-xs font-medium text-primary hover:text-primary/80 transition-colors"
+ onClick={() => onExport(exportValue)}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
+ title="Export"
>
- <PlusIcon className="size-3.5" />Add prompt
+ <DownloadIcon className="size-4" />
</button>
- <div className="flex gap-2 justify-end">
- <Button
- size="sm"
- variant="ghost"
- onClick={() => { setName(entry.name); setItems(entry.items); setEditing(false); }}
- >
- <XIcon className="size-3.5 mr-1" />Cancel
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => (dirty ? setConfirmingDelete(true) : void handleDelete())}
+ className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-muted-foreground"
+ title="Delete"
+ >
+ <Trash2Icon className="size-4" />
+ </button>
+ <div className="flex-1" />
+ {dirty && (
+ <Button size="sm" variant="ghost" onClick={() => onDraftChange(undefined)}>
+ <RotateCcwIcon className="size-3.5 mr-1" />Revert
</Button>
- <Button
- size="sm"
- onClick={handleSave}
- disabled={items.filter((t) => t.trim()).length === 0}
- >
- <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save List
+ )}
+ {/* The deferred summary renders neither editor nor preview, so the toggle
+ would only relabel itself. */}
+ {editorMounted && (
+ <Button size="sm" variant="outline" onClick={() => setPreview((v) => !v)}>
+ {preview ? (
+ <><PencilIcon className="size-3.5 mr-1" />Edit</>
+ ) : (
+ <><EyeIcon className="size-3.5 mr-1" />Preview</>
+ )}
+ </Button>
+ )}
+ <Button size="sm" variant="outline" disabled={pending || !dirty || !savable} onClick={handleSave}>
+ <HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save
+ </Button>
+ {onRunList && (
+ <Button size="sm" onClick={() => onRunList(runnableItems)} disabled={runnableItems.length === 0}>
+ <PlayIcon className="size-3 mr-1" />Run
</Button>
- </div>
- </div>
- );
- }
-
- return (
- <div className="group rounded-xl border border-border/60 bg-card p-4 flex flex-col gap-2.5 hover:border-border hover:shadow-sm transition-all">
- <div className="flex items-center gap-2">
- <span className="font-semibold text-sm flex-1 truncate tracking-tight">{entry.name}</span>
- <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-ui-11 font-medium text-muted-foreground">
- {entry.items.length}
- </span>
- <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 pointer-coarse:opacity-100 transition-opacity">
- {onRunList && (
- <button
- type="button"
- onClick={() => onRunList(entry.items)}
- className="flex h-7 items-center gap-1.5 rounded-lg px-2.5 text-xs font-semibold text-primary hover:bg-primary/10 transition-colors"
- title="Run list"
- >
- <PlayIcon className="size-3" />Run
- </button>
- )}
- <div className="mx-1 h-4 w-px bg-border/60" />
- <button
- type="button"
- onClick={() => onExport(entry)}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title="Export"
- >
- <DownloadIcon className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={() => setEditing(true)}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
- title="Edit"
- >
- <PencilIcon className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={handleDelete}
- className="flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
- title="Delete"
- >
- <Trash2Icon className="size-3.5" />
- </button>
- </div>
- </div>
- <div className="flex flex-col gap-1">
- {entry.items.slice(0, 3).map((item, i) => (
- <p key={i} className="text-xs text-muted-foreground flex gap-2 leading-relaxed">
- <span className="text-muted-foreground/40 shrink-0 tabular-nums">{i + 1}.</span>
- <span className="line-clamp-1">{item}</span>
- </p>
- ))}
- {entry.items.length > 3 && (
- <p className="text-ui-11 text-muted-foreground/50 ml-5">
- +{entry.items.length - 3} more
- </p>
)}
</div>
</div>
+ <UnsavedDeleteConfirm
+ open={confirmingDelete}
+ onOpenChange={setConfirmingDelete}
+ kind="list"
+ name={name.trim() || "Untitled List"}
+ onConfirm={() => {
+ setConfirmingDelete(false);
+ void handleDelete();
+ }}
+ />
+ </>
);
}
-function NewPromptListForm({ onClose, onRefresh }: { onClose: () => void; onRefresh: () => void }): ReactElement {
- const [name, setName] = useState("");
- const [items, setItems] = useState<string[]>(["", ""]);
-
- const handleSave = useCallback(async () => {
- const filtered = items.filter((t) => t.trim());
- if (filtered.length === 0) return;
- const ts = now();
- await savePromptList({
- id: newId(),
- name: name.trim() || "Untitled List",
- items: filtered,
- createdAt: ts,
- updatedAt: ts,
- });
- onRefresh();
- onClose();
- }, [name, items, onClose, onRefresh]);
+// See NewPromptForm: the in-progress list lives in the parent so clicking a row
+// in the rail cannot silently discard a partially authored list.
+function NewPromptListForm({
+ draft,
+ onDraftChange,
+ onClose,
+ onRefresh,
+ onCreated,
+ creating,
+ create,
+}: {
+ draft: ListDraft;
+ onDraftChange: (draft: ListDraft) => void;
+ onClose: () => void;
+ onRefresh: () => Promise<void>;
+ onCreated: (id: string, submitted: ListDraft, fromOpenForm: boolean) => void;
+ creating: boolean;
+ create: (fn: () => Promise<void>) => Promise<void>;
+}): ReactElement {
+ const { name, items } = draft;
+ const setName = (value: string) => onDraftChange({ ...draft, name: value });
+ const setItems = (value: string[]) => onDraftChange({ ...draft, items: value });
+ // See NewPromptForm, including why the flag is set in setup.
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
- const addItem = useCallback(() => setItems((prev) => [...prev, ""]), []);
- const removeItem = useCallback(
- (i: number) => setItems((prev) => prev.filter((_, idx) => idx !== i)),
- [],
- );
- const updateItem = useCallback(
- (i: number, val: string) =>
- setItems((prev) => prev.map((v, idx) => (idx === i ? val : v))),
- [],
+ const handleSave = useCallback(
+ () =>
+ create(async () => {
+ const filtered = items.filter((t) => t.trim());
+ if (filtered.length === 0) return;
+ const ts = now();
+ const id = newId();
+ // See NewPromptForm: the editor stays usable while the request is out.
+ const submitted: ListDraft = { name, items };
+ try {
+ await savePromptList({
+ id,
+ name: name.trim() || "Untitled List",
+ items: filtered,
+ createdAt: ts,
+ updatedAt: ts,
+ });
+ } catch (err) {
+ // See NewPromptForm: an unhandled rejection reads as a saved list.
+ toast.error("Could not create list", {
+ description: err instanceof Error ? err.message : "Please try again.",
+ });
+ return;
+ }
+ // See NewPromptForm: select only once the refreshed list contains the id.
+ await onRefresh();
+ onCreated(id, submitted, mounted.current);
+ }),
+ [name, items, create, onRefresh, onCreated],
);
+ const addItem = () => setItems([...items, ""]);
+
return (
- <div className="rounded-xl border border-border/50 bg-muted/30 p-4 flex flex-col gap-3">
- <p className="text-xs font-semibold text-muted-foreground">New Prompt List</p>
+ <div className="flex h-full min-h-0 flex-col gap-3">
+ <p className="shrink-0 text-xs font-semibold text-muted-foreground">New Prompt List</p>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="List name..."
autoFocus
- className="w-full rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
+ className="w-full shrink-0 rounded-lg border-0 bg-background/80 px-3 py-2 text-sm font-medium ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow"
/>
- <p className="text-xs font-semibold text-muted-foreground">
- Prompts — loaded into the composer one at a time
+ <p className="shrink-0 text-xs font-semibold text-muted-foreground">
+ Prompts, loaded into the composer one at a time
</p>
- <div className="flex flex-col gap-2">
- {items.map((item, i) => (
- <div key={i} className="flex items-start gap-2">
- <span className="text-xs font-medium text-muted-foreground/60 mt-2.5 w-5 shrink-0 text-right">{i + 1}.</span>
- <textarea
- value={item}
- onChange={(e) => updateItem(i, e.target.value)}
- rows={2}
- placeholder={`Prompt ${i + 1}...`}
- className="flex-1 resize-y rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed"
- />
- <button
- type="button"
- onClick={() => removeItem(i)}
- disabled={items.length <= 1}
- className="flex h-7 w-7 mt-1 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors shrink-0 disabled:opacity-30 disabled:cursor-not-allowed"
- title="Remove"
- >
- <XIcon className="size-3.5" />
- </button>
- </div>
- ))}
+ <div className="min-h-0 flex-1 overflow-y-auto pr-1 flex flex-col gap-2">
+ <SortablePromptItems items={items} onChange={setItems} minItems={1} />
+ <button
+ type="button"
+ onClick={addItem}
+ className="flex items-center gap-1.5 self-start text-xs font-medium text-primary hover:text-primary/80 transition-colors"
+ >
+ <PlusIcon className="size-3.5" />Add another prompt
+ </button>
</div>
- <button
- type="button"
- onClick={addItem}
- className="flex items-center gap-1.5 text-xs font-medium text-primary hover:text-primary/80 transition-colors"
- >
- <PlusIcon className="size-3.5" />Add another prompt
- </button>
- <div className="flex gap-2 justify-end">
+ <div className="flex shrink-0 flex-wrap gap-2 justify-end border-t border-border/50 pt-3">
<Button size="sm" variant="ghost" onClick={onClose}>
<XIcon className="size-3.5 mr-1" />Cancel
</Button>
<Button
size="sm"
onClick={handleSave}
- disabled={items.filter((t) => t.trim()).length === 0}
+ disabled={creating || items.filter((t) => t.trim()).length === 0}
>
<HugeiconsIcon icon={Tick02Icon} strokeWidth={2} className="size-3.5 mr-1" />Save Prompt List
</Button>
@@ -1764,9 +2172,118 @@ export function PromptStorageDialog({
const [showSuggestions, setShowSuggestions] = useState(false);
const [exportCtx, setExportCtx] = useState<ExportModalCtx | null>(null);
const importRef = useRef<HTMLInputElement>(null);
+ const pinnedPromptIds = usePlusMenuPrefsStore((s) => s.pinnedPromptIds);
const [promptEntries, setPromptEntries] = useState<PromptEntry[]>([]);
const [promptLists, setPromptLists] = useState<PromptListEntry[]>([]);
+ const [selectedPromptId, setSelectedPromptId] = useState<string | null>(null);
+ const [selectedListId, setSelectedListId] = useState<string | null>(null);
+ // Maps, not plain objects: ids are arbitrary strings, so one named
+ // "constructor" would resolve to an inherited prototype member.
+ const [promptDrafts, setPromptDrafts] = useState<Map<string, PromptDraft>>(
+ () => new Map(),
+ );
+ const [listDrafts, setListDrafts] = useState<Map<string, ListDraft>>(
+ () => new Map(),
+ );
+
+ // In-progress new entries, held here rather than inside the forms so that
+ // hiding a form (by selecting a row in the rail) does not destroy the work.
+ const [newPromptDraft, setNewPromptDraft] = useState<PromptDraft>(emptyPromptDraft);
+ const [newListDraft, setNewListDraft] = useState<ListDraft>(emptyListDraft);
+ const newPromptStarted =
+ newPromptDraft.name.trim() !== "" || newPromptDraft.text.trim() !== "";
+ const newListStarted =
+ newListDraft.name.trim() !== "" || newListDraft.items.some((t) => t.trim() !== "");
+
+ const setPromptDraft = useCallback((id: string, draft: PromptDraft | undefined) => {
+ setPromptDrafts((prev) => {
+ if (!draft) {
+ if (!prev.has(id)) return prev;
+ const next = new Map(prev);
+ next.delete(id);
+ return next;
+ }
+ return new Map(prev).set(id, draft);
+ });
+ }, []);
+
+ const setListDraft = useCallback((id: string, draft: ListDraft | undefined) => {
+ setListDrafts((prev) => {
+ if (!draft) {
+ if (!prev.has(id)) return prev;
+ const next = new Map(prev);
+ next.delete(id);
+ return next;
+ }
+ return new Map(prev).set(id, draft);
+ });
+ }, []);
+
+ // Mutation locks live here rather than in the detail panes, which are keyed by
+ // row id and so unmount the moment another row is selected. Held by id until
+ // the request settles, or a Save in flight during a row switch comes back
+ // unlocked and its unconditional PUT can land after a DELETE.
+ const [mutatingIds, setMutatingIds] = useState<ReadonlySet<string>>(
+ () => new Set<string>(),
+ );
+ // The ref is the authority, not the state. A functional updater is not
+ // guaranteed to run during setState, so reading the outcome straight after
+ // scheduling one can see a stale answer, skip the request, and still acquire
+ // the id later during render with nothing left to release it. The state
+ // exists only so the buttons re-render.
+ const mutatingRef = useRef<ReadonlySet<string>>(new Set<string>());
+ const runMutation = useCallback(
+ async (id: string, fn: () => Promise<void>) => {
+ const [held, started] = acquire(mutatingRef.current, id);
+ // The buttons are disabled while locked, but a second caller reaching here
+ // anyway must not run and must not clear the first one's lock.
+ if (!started) return;
+ mutatingRef.current = held;
+ setMutatingIds(held);
+ try {
+ await fn();
+ } finally {
+ mutatingRef.current = release(mutatingRef.current, id);
+ setMutatingIds(mutatingRef.current);
+ }
+ },
+ [],
+ );
+
+ // Above the New forms, not inside them: selecting a rail row unmounts the
+ // form while its create is still out, and a guard mounted with it would let
+ // reopening New mint a second id for the same draft.
+ const promptCreate = useCreateGuard();
+ const listCreate = useCreateGuard();
+
+ // Only drop the draft if it still holds what the request carried. Anything
+ // typed while the save was in flight is newer than the server's copy and is
+ // the user's most recent intent, so it stays and the row stays dirty.
+ const clearPromptDraftIfSaved = useCallback(
+ (id: string, submitted: PromptDraft) => {
+ setPromptDrafts((prev) => {
+ const current = prev.get(id);
+ if (!current || !samePromptDraft(current, submitted)) return prev;
+ const next = new Map(prev);
+ next.delete(id);
+ return next;
+ });
+ },
+ [],
+ );
+ const clearListDraftIfSaved = useCallback(
+ (id: string, submitted: ListDraft) => {
+ setListDrafts((prev) => {
+ const current = prev.get(id);
+ if (!current || !sameListDraft(current, submitted)) return prev;
+ const next = new Map(prev);
+ next.delete(id);
+ return next;
+ });
+ },
+ [],
+ );
const refreshEntries = useCallback(async () => {
try { setPromptEntries(await listPromptEntries()); } catch {}
@@ -1782,12 +2299,50 @@ export function PromptStorageDialog({
}
}, [open, refreshEntries, refreshLists]);
- useEffect(() => {
+ // In the handler, not an effect keyed to activeTab. An effect leaves one render
+ // of the new tab still holding the old query, and the keep-a-row-selected pass
+ // runs in it and drops the row that tab had selected.
+ const selectTab = useCallback((tab: Tab) => {
+ setActiveTab(tab);
setSearchQuery("");
setShowSuggestions(false);
setShowNewPrompt(false);
setShowNewList(false);
- }, [activeTab]);
+ }, []);
+
+ // Clear the search too: an active one the new entry does not match keeps it
+ // out of the filtered rail, and the effect below bounces the selection off it.
+ //
+ // The draft resets only when it still holds what was sent. The fields stay
+ // editable while the create is out, and Cancel can start a fresh one, so an
+ // unconditional reset discards text that never reached the server.
+ const selectCreatedPrompt = useCallback(
+ (id: string, submitted: PromptDraft, fromOpenForm: boolean) => {
+ setNewPromptDraft((prev) =>
+ samePromptDraft(prev, submitted) ? emptyPromptDraft() : prev,
+ );
+ // The user left the form while the request was out, so they are looking at
+ // something else on purpose. Take the refresh, leave the view alone.
+ if (!fromOpenForm) return;
+ setSearchQuery("");
+ setSelectedPromptId(id);
+ setShowNewPrompt(false);
+ },
+ [],
+ );
+
+ const selectCreatedList = useCallback(
+ (id: string, submitted: ListDraft, fromOpenForm: boolean) => {
+ setNewListDraft((prev) =>
+ sameListDraft(prev, submitted) ? emptyListDraft() : prev,
+ );
+ if (!fromOpenForm) return;
+ setSearchQuery("");
+ setSelectedListId(id);
+ setShowNewList(false);
+ },
+ [],
+ );
const filteredPrompts = useMemo(() => {
const all = promptEntries ?? [];
@@ -1805,6 +2360,33 @@ export function PromptStorageDialog({
return all.filter((e) => e.name.toLowerCase().includes(q));
}, [promptLists, searchQuery]);
+ // Keep a row selected whenever the filtered rail is non-empty, so the detail
+ // pane never sits blank next to a list full of prompts. During render, not in
+ // an effect: an effect paints the blank pane once before correcting it.
+ // The visible tab only. searchQuery is shared, so filtering one collection also
+ // filters the hidden one, and correcting against that dropped the row selected
+ // there: switching back cleared the query and landed on the first row instead.
+ if (activeTab === "prompts") {
+ if (filteredPrompts.length === 0) {
+ if (selectedPromptId !== null) setSelectedPromptId(null);
+ } else if (!filteredPrompts.some((e) => e.id === selectedPromptId)) {
+ setSelectedPromptId(filteredPrompts[0].id);
+ }
+ } else if (filteredLists.length === 0) {
+ if (selectedListId !== null) setSelectedListId(null);
+ } else if (!filteredLists.some((e) => e.id === selectedListId)) {
+ setSelectedListId(filteredLists[0].id);
+ }
+
+ const selectedPrompt = useMemo(
+ () => promptEntries.find((e) => e.id === selectedPromptId) ?? null,
+ [promptEntries, selectedPromptId],
+ );
+ const selectedList = useMemo(
+ () => promptLists.find((e) => e.id === selectedListId) ?? null,
+ [promptLists, selectedListId],
+ );
+
const suggestions = useMemo(() => {
if (!searchQuery.trim()) return [];
const q = searchQuery.toLowerCase();
@@ -1824,6 +2406,22 @@ export function PromptStorageDialog({
[onUse, onOpenChange],
);
+ // The rail is one tab stop; arrows move within it. Clicking rather than
+ // setting the id keeps the two tabs on one handler.
+ const handleRailKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
+ const rows = Array.from(
+ e.currentTarget.querySelectorAll<HTMLButtonElement>("[data-rail-row]"),
+ );
+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);
+ if (at < 0) return;
+ const next = rows[at + (e.key === "ArrowDown" ? 1 : -1)];
+ if (!next) return;
+ e.preventDefault();
+ next.focus();
+ next.click();
+ }, []);
+
const handleImportFile = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
@@ -1965,7 +2563,7 @@ export function PromptStorageDialog({
<button
key={tab}
type="button"
- onClick={() => setActiveTab(tab)}
+ onClick={() => selectTab(tab)}
className={cn(
"rounded-md px-4 py-1.5 text-xs font-medium transition-all",
activeTab === tab
@@ -2009,134 +2607,179 @@ export function PromptStorageDialog({
</div>
{/* */}
- <div className="flex-1 min-h-0 overflow-y-auto px-6 pb-6 flex flex-col gap-2.5">
- {activeTab === "prompts" && (
- <>
- {!showNewPrompt ? (
- <button
- type="button"
- onClick={() => setShowNewPrompt(true)}
- className="flex items-center gap-2.5 rounded-xl border-2 border-dashed border-border/40 px-4 py-3 text-sm font-medium text-muted-foreground hover:border-border hover:text-foreground hover:bg-muted/50 transition-all"
- >
- <PlusIcon className="size-4" />New Prompt
- </button>
- ) : (
- <NewPromptForm onClose={() => setShowNewPrompt(false)} onRefresh={refreshEntries} />
+ {/* min-h-0, not a floor: the grid rows below already carry the minimum
+ each pane's chrome needs, and the body scrolls to them. A floor
+ here has to guess the height of the header and search above it,
+ which grows when their text wraps on a narrow dialog, and the
+ excess lands in DialogContent's overflow-hidden. */}
+ <div className="flex-1 min-h-0 overflow-y-auto px-4 sm:px-6 pb-4 sm:pb-6 grid gap-2 sm:gap-4 grid-cols-1 grid-rows-[minmax(132px,30%)_minmax(272px,1fr)] sm:grid-cols-[200px_minmax(0,1fr)] sm:grid-rows-1 lg:grid-cols-[248px_minmax(0,1fr)]">
+ {/* */}
+ <div className="flex min-h-[132px] flex-col gap-2 rounded-xl border border-border/50 bg-muted/20 p-2">
+ <button
+ type="button"
+ onClick={() => {
+ if (activeTab === "prompts") setShowNewPrompt(true);
+ else setShowNewList(true);
+ }}
+ className="flex shrink-0 items-center justify-center gap-1.5 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs font-medium text-muted-foreground hover:border-border hover:bg-muted/50 hover:text-foreground transition-all"
+ >
+ <PlusIcon className="size-3.5" />
+ {activeTab === "prompts" ? "New prompt" : "New prompt list"}
+ {(activeTab === "prompts" ? newPromptStarted : newListStarted) && (
+ <span
+ className="size-1.5 shrink-0 rounded-full bg-primary"
+ title="Unsaved draft"
+ />
)}
+ </button>
- {filteredPrompts.length > 0 ? (
+ <div
+ role="group"
+ aria-label={activeTab === "prompts" ? "Saved prompts" : "Prompt lists"}
+ onKeyDown={handleRailKeyDown}
+ className="min-h-0 flex-1 overflow-y-auto flex flex-col gap-0.5"
+ >
+ {activeTab === "prompts" &&
filteredPrompts.map((entry) => (
- <PromptCard
+ <RailRow
key={entry.id}
- entry={entry}
- onUse={handleUsePrompt}
- onExport={(e) => setExportCtx({ kind: "prompt", entry: e })}
- onRefresh={refreshEntries}
+ title={entry.name}
+ preview={entry.text.replace(/\s+/g, " ").trim()}
+ selected={!showNewPrompt && entry.id === selectedPromptId}
+ current={entry.id === selectedPromptId}
+ dirty={promptDrafts.has(entry.id)}
+ leading={
+ pinnedPromptIds.includes(entry.id) ? (
+ <BookmarkIcon className="size-3 shrink-0 fill-primary text-primary" />
+ ) : null
+ }
+ onSelect={() => {
+ setShowNewPrompt(false);
+ setSelectedPromptId(entry.id);
+ }}
/>
- ))
- ) : (
- !showNewPrompt && (
- <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
- {searchQuery.trim() ? (
- <>
- <div className="flex size-12 items-center justify-center rounded-2xl bg-muted/60">
- <HugeiconsIcon icon={Search01Icon} strokeWidth={1.75} className="size-5 text-muted-foreground/40" />
- </div>
- <div className="flex flex-col gap-1">
- <p className="text-sm font-medium text-muted-foreground">
- No prompts match &ldquo;{searchQuery}&rdquo;
- </p>
- <button
- type="button"
- onClick={() => setSearchQuery("")}
- className="text-xs text-primary hover:underline"
- >
- Clear search
- </button>
- </div>
- </>
- ) : (
- <>
- <div className="flex size-12 items-center justify-center rounded-2xl bg-muted/60">
- <BookmarkIcon className="size-5 text-muted-foreground/40" />
- </div>
- <div className="flex flex-col gap-1">
- <p className="text-sm font-medium text-muted-foreground">No saved prompts yet</p>
- <p className="text-xs text-muted-foreground/60">
- Save prompts you use often for quick reuse
- </p>
- </div>
- </>
- )}
- </div>
- )
- )}
- </>
- )}
-
- {activeTab === "lists" && (
- <>
- {!showNewList ? (
- <button
- type="button"
- onClick={() => setShowNewList(true)}
- className="flex items-center gap-2.5 rounded-xl border-2 border-dashed border-border/40 px-4 py-3 text-sm font-medium text-muted-foreground hover:border-border hover:text-foreground hover:bg-muted/50 transition-all"
- >
- <PlusIcon className="size-4" />New Prompt List
- </button>
- ) : (
- <NewPromptListForm onClose={() => setShowNewList(false)} onRefresh={refreshLists} />
- )}
+ ))}
- {filteredLists.length > 0 ? (
+ {activeTab === "lists" &&
filteredLists.map((entry) => (
- <PromptListCard
+ <RailRow
key={entry.id}
- entry={entry}
- onRunList={onRunList}
- onExport={(e) => setExportCtx({ kind: "list", entry: e })}
- onRefresh={refreshLists}
+ title={entry.name}
+ preview={(entry.items[0] ?? "").replace(/\s+/g, " ").trim()}
+ badge={String(entry.items.length)}
+ selected={!showNewList && entry.id === selectedListId}
+ current={entry.id === selectedListId}
+ dirty={listDrafts.has(entry.id)}
+ onSelect={() => {
+ setShowNewList(false);
+ setSelectedListId(entry.id);
+ }}
/>
- ))
- ) : (
- !showNewList && (
- <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
- {searchQuery.trim() ? (
- <>
- <div className="flex size-12 items-center justify-center rounded-2xl bg-muted/60">
- <HugeiconsIcon icon={Search01Icon} strokeWidth={1.75} className="size-5 text-muted-foreground/40" />
- </div>
- <div className="flex flex-col gap-1">
- <p className="text-sm font-medium text-muted-foreground">
- No prompt lists match &ldquo;{searchQuery}&rdquo;
- </p>
- <button
- type="button"
- onClick={() => setSearchQuery("")}
- className="text-xs text-primary hover:underline"
- >
- Clear search
- </button>
- </div>
- </>
- ) : (
- <>
- <div className="flex size-12 items-center justify-center rounded-2xl bg-muted/60">
- <LayoutListIcon className="size-5 text-muted-foreground/40" />
- </div>
- <div className="flex flex-col gap-1">
- <p className="text-sm font-medium text-muted-foreground">No prompt lists yet</p>
- <p className="text-xs text-muted-foreground/60">
- A prompt list queues a sequence of prompts for quick reuse
- </p>
- </div>
- </>
- )}
- </div>
- )
+ ))}
+
+ {activeTab === "prompts" && filteredPrompts.length === 0 && (
+ <p className="px-2 py-6 text-center text-ui-11 text-muted-foreground/60">
+ {searchQuery.trim() ? "No prompts match" : "No saved prompts yet"}
+ </p>
)}
- </>
- )}
+ {activeTab === "lists" && filteredLists.length === 0 && (
+ <p className="px-2 py-6 text-center text-ui-11 text-muted-foreground/60">
+ {searchQuery.trim() ? "No lists match" : "No prompt lists yet"}
+ </p>
+ )}
+ </div>
+
+ <p className="shrink-0 px-1 pb-0.5 text-ui-11 tabular-nums text-muted-foreground/50">
+ {activeTab === "prompts"
+ ? `${filteredPrompts.length} of ${promptEntries.length} prompts`
+ : `${filteredLists.length} of ${promptLists.length} lists`}
+ </p>
+ </div>
+
+ {/* */}
+ <div className="min-h-[272px] rounded-xl border border-border/60 bg-card p-4">
+ {activeTab === "prompts" &&
+ (showNewPrompt ? (
+ <NewPromptForm
+ draft={newPromptDraft}
+ onDraftChange={setNewPromptDraft}
+ onClose={() => {
+ setNewPromptDraft(emptyPromptDraft());
+ setShowNewPrompt(false);
+ }}
+ onRefresh={refreshEntries}
+ onCreated={selectCreatedPrompt}
+ creating={promptCreate.creating}
+ create={promptCreate.create}
+ />
+ ) : selectedPrompt ? (
+ <PromptDetail
+ key={selectedPrompt.id}
+ entry={selectedPrompt}
+ draft={promptDrafts.get(selectedPrompt.id)}
+ onDraftChange={(d) => setPromptDraft(selectedPrompt.id, d)}
+ onUse={handleUsePrompt}
+ onExport={(e) => setExportCtx({ kind: "prompt", entry: e })}
+ onRefresh={refreshEntries}
+ onDeleted={(deletedId) =>
+ setSelectedPromptId((prev) => (prev === deletedId ? null : prev))
+ }
+ onSaved={(submitted) =>
+ clearPromptDraftIfSaved(selectedPrompt.id, submitted)
+ }
+ pending={mutatingIds.has(lockKey("prompt", selectedPrompt.id))}
+ runMutation={runMutation}
+ />
+ ) : (
+ <EmptyDetail
+ icon={<BookmarkIcon className="size-5 text-muted-foreground/40" />}
+ title={searchQuery.trim() ? `No prompts match “${searchQuery}”` : "No saved prompts yet"}
+ hint={searchQuery.trim() ? undefined : "Save prompts you use often for quick reuse"}
+ onClearSearch={searchQuery.trim() ? () => setSearchQuery("") : undefined}
+ />
+ ))}
+
+ {activeTab === "lists" &&
+ (showNewList ? (
+ <NewPromptListForm
+ draft={newListDraft}
+ onDraftChange={setNewListDraft}
+ onClose={() => {
+ setNewListDraft(emptyListDraft());
+ setShowNewList(false);
+ }}
+ onRefresh={refreshLists}
+ onCreated={selectCreatedList}
+ creating={listCreate.creating}
+ create={listCreate.create}
+ />
+ ) : selectedList ? (
+ <PromptListDetail
+ key={selectedList.id}
+ entry={selectedList}
+ draft={listDrafts.get(selectedList.id)}
+ onDraftChange={(d) => setListDraft(selectedList.id, d)}
+ onRunList={onRunList}
+ onExport={(e) => setExportCtx({ kind: "list", entry: e })}
+ onRefresh={refreshLists}
+ onDeleted={(deletedId) =>
+ setSelectedListId((prev) => (prev === deletedId ? null : prev))
+ }
+ onSaved={(submitted) =>
+ clearListDraftIfSaved(selectedList.id, submitted)
+ }
+ pending={mutatingIds.has(lockKey("list", selectedList.id))}
+ runMutation={runMutation}
+ />
+ ) : (
+ <EmptyDetail
+ icon={<LayoutListIcon className="size-5 text-muted-foreground/40" />}
+ title={searchQuery.trim() ? `No prompt lists match “${searchQuery}”` : "No prompt lists yet"}
+ hint={searchQuery.trim() ? undefined : "A prompt list queues a sequence of prompts for quick reuse"}
+ onClearSearch={searchQuery.trim() ? () => setSearchQuery("") : undefined}
+ />
+ ))}
+ </div>
</div>
</DialogContent>
</Dialog>
diff --git a/studio/frontend/src/features/chat/prompt-storage/reorder.ts b/studio/frontend/src/features/chat/prompt-storage/reorder.ts
new file mode 100644
index 00000000000..58743327182
--- /dev/null
+++ b/studio/frontend/src/features/chat/prompt-storage/reorder.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export interface RowBox {
+ top: number;
+ height: number;
+}
+
+/**
+ * Where the dragged row belongs for a pointer at `localY`, as an index into the
+ * current order.
+ *
+ * Counts the rows the pointer has passed rather than hit-testing the row under
+ * it, and skips the dragged row itself. Testing "which row contains the
+ * pointer" oscillates across uneven heights: dropping a short row onto a tall
+ * one leaves the tall row still under the pointer, which sends it straight
+ * back. Midpoints of the others are stable, because after the move the dragged
+ * row occupies the space that shifted them.
+ */
+export function insertionIndex(
+ rows: readonly (RowBox | undefined)[],
+ from: number,
+ localY: number,
+): number {
+ let to = 0;
+ for (let i = 0; i < rows.length; i++) {
+ if (i === from) continue;
+ const row = rows[i];
+ if (!row) continue;
+ if (row.top + row.height / 2 < localY) to++;
+ }
+ return to;
+}
+
+/**
+ * Whether a window-level pointer event belongs to the drag `activePointerId`
+ * started.
+ *
+ * The grip deliberately does not capture the pointer, so the listeners are on
+ * `window` and see every pointer on the page. Ending a drag clears the id
+ * before React can unsubscribe them, so treating "no active pointer" as a match
+ * lets a still-held button reorder the list after the drag was already ended by
+ * a window blur.
+ */
+export function ownsDrag(
+ activePointerId: number | null,
+ eventPointerId: number,
+): boolean {
+ return activePointerId !== null && activePointerId === eventPointerId;
+}
+
+/**
+ * The translateY, in pixels, each row needs so that a reorder appears to start
+ * from where the rows were before it.
+ *
+ * `first` must be read at the moment the reorder is requested. Rows change
+ * height without the order changing, from the preview toggle and from a
+ * textarea regrowing on resize, so a baseline recorded at some earlier commit
+ * describes a layout that no longer exists and shifts every row by the
+ * difference. Sub-pixel moves are dropped rather than animated.
+ */
+export function flipShifts(
+ first: ReadonlyMap<string, number>,
+ last: ReadonlyMap<string, number>,
+): Map<string, number> {
+ const shifts = new Map<string, number>();
+ last.forEach((offset, uid) => {
+ const from = first.get(uid);
+ if (from === undefined) return;
+ const dy = from - offset;
+ if (Math.abs(dy) >= 1) shifts.set(uid, dy);
+ });
+ return shifts;
+}
diff --git a/studio/frontend/src/features/chat/prompt-storage/sortable-prompt-items.tsx b/studio/frontend/src/features/chat/prompt-storage/sortable-prompt-items.tsx
new file mode 100644
index 00000000000..d617cfca20a
--- /dev/null
+++ b/studio/frontend/src/features/chat/prompt-storage/sortable-prompt-items.tsx
@@ -0,0 +1,366 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { MarkdownPreview } from "@/components/markdown/markdown-preview";
+import { cn } from "@/lib/utils";
+import { flipShifts, insertionIndex, ownsDrag } from "./reorder";
+import { GripVerticalIcon, XIcon } from "lucide-react";
+import {
+ type ReactElement,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+
+// Textarea that grows with its content, capped at maxHeight.
+export function AutoTextarea({
+ value,
+ onChange,
+ placeholder,
+ minRows = 1,
+ maxHeight = 320,
+ className,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ minRows?: number;
+ maxHeight?: number;
+ className?: string;
+}): ReactElement {
+ const ref = useRef<HTMLTextAreaElement>(null);
+
+ const measure = useCallback(() => {
+ const el = ref.current;
+ if (!el) return;
+ el.style.height = "auto";
+ const next = Math.min(el.scrollHeight, maxHeight);
+ el.style.height = `${next}px`;
+ el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden";
+ }, [maxHeight]);
+
+ // Layout effect: measuring after paint flashes the wrong height while typing.
+ useLayoutEffect(measure, [value, measure]);
+
+ // A width change rewraps the text without touching `value`, and overflowY may
+ // be "hidden", so the new lines would be clipped until the next keystroke.
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+
+ window.addEventListener("resize", measure);
+
+ // Catches the column resizing without the window doing so.
+ let observer: ResizeObserver | undefined;
+ if (typeof ResizeObserver !== "undefined") {
+ let lastWidth = el.clientWidth;
+ observer = new ResizeObserver(() => {
+ // Width only; it also fires for the height we just set, which would loop.
+ const width = el.clientWidth;
+ if (width === lastWidth) return;
+ lastWidth = width;
+ measure();
+ });
+ observer.observe(el);
+ }
+
+ return () => {
+ window.removeEventListener("resize", measure);
+ observer?.disconnect();
+ };
+ }, [measure]);
+
+ return (
+ <textarea
+ ref={ref}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ rows={minRows}
+ className={cn(
+ "w-full resize-none rounded-lg border-0 bg-background/80 px-3 py-2 text-sm ring-1 ring-border/60 outline-none focus:ring-ring transition-shadow leading-relaxed",
+ className,
+ )}
+ />
+ );
+}
+
+function move<T>(arr: T[], from: number, to: number): T[] {
+ const next = [...arr];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+}
+
+let uidSeq = 0;
+function nextUid(): string {
+ uidSeq += 1;
+ return `i${uidSeq}`;
+}
+
+// Rows are keyed by a synthetic uid, not array index: index keys would swap the
+// values under the caret on reorder and break the animation.
+export function SortablePromptItems({
+ items,
+ onChange,
+ minItems = 0,
+ preview = false,
+}: {
+ items: string[];
+ onChange: (items: string[]) => void;
+ minItems?: number;
+ preview?: boolean;
+}): ReactElement {
+ const [uids, setUids] = useState<string[]>(() => items.map(() => nextUid()));
+ const [draggingUid, setDraggingUid] = useState<string | null>(null);
+
+ const containerRef = useRef<HTMLDivElement>(null);
+ const pointerYRef = useRef(0);
+ const pointerIdRef = useRef<number | null>(null);
+ const rowRefs = useRef(new Map<string, HTMLDivElement>());
+ const prevOffsets = useRef(new Map<string, number>());
+ const uidsRef = useRef(uids);
+ // Only a reorder animates, or an auto-growing textarea would make the rows
+ // below it wobble as you type.
+ const reorderTick = useRef(0);
+ const animatedTick = useRef(0);
+
+ // Resync when the count changes from outside (revert, switching lists, import).
+ // During render rather than in an effect, which would paint the new row once
+ // under a stale key first.
+ let rowUids = uids;
+ if (uids.length !== items.length) {
+ rowUids = items.map((_, i) => uids[i] ?? nextUid());
+ setUids(rowUids);
+ }
+
+ // Layout offsets, not client rects: a rect moves with the scroll position, so
+ // scrolling the pane between reorders would bake that distance into every
+ // transform and jump the whole list.
+ const measureOffsets = useCallback(() => {
+ const offsets = new Map<string, number>();
+ rowRefs.current.forEach((el, uid) => offsets.set(uid, el.offsetTop));
+ return offsets;
+ }, []);
+
+ // FLIP: snap each moved row back to where it was, then release, so the browser
+ // animates one transform per row rather than animating layout.
+ useLayoutEffect(() => {
+ if (reorderTick.current === animatedTick.current) return;
+ animatedTick.current = reorderTick.current;
+ flipShifts(prevOffsets.current, measureOffsets()).forEach((dy, uid) => {
+ const el = rowRefs.current.get(uid);
+ if (!el) return;
+ el.style.transition = "none";
+ el.style.transform = `translateY(${dy}px)`;
+ requestAnimationFrame(() => {
+ el.style.transition = "transform 180ms cubic-bezier(0.2, 0, 0, 1)";
+ el.style.transform = "";
+ });
+ });
+ }, [uids, measureOffsets]);
+
+ // Mirrors, so the drag listener does not resubscribe on every keystroke. A
+ // layout effect, not an assignment during render: they only have to be
+ // current before the next pointer event, and this runs well before that.
+ const itemsRef = useRef(items);
+ const onChangeRef = useRef(onChange);
+ useLayoutEffect(() => {
+ itemsRef.current = items;
+ onChangeRef.current = onChange;
+ uidsRef.current = rowUids;
+ });
+
+ const applyOrder = useCallback((from: number, to: number) => {
+ if (from === to) return;
+ // FLIP's "first", read now rather than at whichever commit last recorded it:
+ // the preview toggle and a resize change row heights on their own, and
+ // animating from those stale offsets shifted the whole list.
+ prevOffsets.current = measureOffsets();
+ reorderTick.current += 1;
+ const nextItems = move(itemsRef.current, from, to);
+ const nextUids = move(uidsRef.current, from, to);
+ // Advance the mirrors here too. A drag reorders faster than a commit, and
+ // the next hit-test must not run against the pre-move order.
+ itemsRef.current = nextItems;
+ uidsRef.current = nextUids;
+ onChangeRef.current(nextItems);
+ setUids(nextUids);
+ }, [measureOffsets]);
+
+ const handlePointerDown = useCallback(
+ (uid: string, e: React.PointerEvent<HTMLButtonElement>) => {
+ // Primary press only: a right/middle drag reports buttons 2 or 4, which
+ // the zero-buttons release check below cannot end.
+ if (e.button !== 0 || !e.isPrimary) return;
+ // isPrimary is per pointer type, so a mouse press can pass it mid-touch-drag.
+ if (pointerIdRef.current !== null) return;
+ pointerIdRef.current = e.pointerId;
+ // No setPointerCapture: reordering moves the row's DOM node, and detaching
+ // releases capture, killing the drag one row in. The window listener below
+ // outlives the move instead.
+ e.preventDefault();
+ pointerYRef.current = e.clientY;
+ setDraggingUid(uid);
+ },
+ [],
+ );
+
+ useEffect(() => {
+ if (!draggingUid) return;
+ const container = containerRef.current;
+ if (!container) return;
+
+ const evaluate = () => {
+ const order = uidsRef.current;
+ const from = order.indexOf(draggingUid);
+ if (from < 0) return;
+
+ // Layout offsets, not client rects: mid-FLIP a client rect still reports
+ // the pre-animation position. offsetTop/offsetHeight ignore transforms.
+ const localY = pointerYRef.current - container.getBoundingClientRect().top;
+ const boxes = order.map((uid) => {
+ const el = rowRefs.current.get(uid);
+ return el ? { top: el.offsetTop, height: el.offsetHeight } : undefined;
+ });
+ const to = insertionIndex(boxes, from, localY);
+ if (to !== from) applyOrder(from, to);
+ };
+
+ const endDrag = () => {
+ pointerIdRef.current = null;
+ setDraggingUid(null);
+ };
+
+ // Window listeners see every pointer; a second finger would otherwise
+ // reorder with its own clientY and its release would end this drag. An
+ // already-ended drag owns no pointer, so nothing matches until the cleanup
+ // below unsubscribes.
+ const isDragPointer = (e: PointerEvent) =>
+ ownsDrag(pointerIdRef.current, e.pointerId);
+
+ const onMove = (e: PointerEvent) => {
+ if (!isDragPointer(e)) return;
+ // Releasing outside the window delivers no pointerup, so treat the first
+ // move with no buttons held as the release we missed.
+ if (e.buttons === 0) {
+ endDrag();
+ return;
+ }
+ pointerYRef.current = e.clientY;
+ evaluate();
+ };
+
+ const onPointerEnd = (e: PointerEvent) => {
+ if (!isDragPointer(e)) return;
+ endDrag();
+ };
+
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onPointerEnd);
+ window.addEventListener("pointercancel", onPointerEnd);
+ // Release entirely outside the page, where no move follows to catch it.
+ window.addEventListener("blur", endDrag);
+ return () => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onPointerEnd);
+ window.removeEventListener("pointercancel", onPointerEnd);
+ window.removeEventListener("blur", endDrag);
+ };
+ }, [draggingUid, applyOrder]);
+
+ const nudge = useCallback(
+ (uid: string, delta: number) => {
+ const from = uidsRef.current.indexOf(uid);
+ const to = from + delta;
+ if (from < 0 || to < 0 || to >= itemsRef.current.length) return;
+ applyOrder(from, to);
+ },
+ [applyOrder],
+ );
+
+ return (
+ // `relative` makes this the offsetParent the hit-test measures against.
+ <div
+ ref={containerRef}
+ className={cn(
+ "relative flex flex-col gap-2",
+ // The drag tracks the pointer window-wide; without this it paints a
+ // text selection behind itself.
+ draggingUid && "select-none",
+ )}
+ >
+ {items.map((item, i) => {
+ const uid = rowUids[i] ?? `fallback-${i}`;
+ const isDragging = uid === draggingUid;
+ return (
+ <div
+ key={uid}
+ ref={(el) => {
+ if (el) rowRefs.current.set(uid, el);
+ else rowRefs.current.delete(uid);
+ }}
+ className={cn(
+ "flex items-start gap-2 rounded-lg",
+ isDragging && "relative z-10 bg-muted/60 ring-1 ring-border",
+ )}
+ >
+ <button
+ type="button"
+ aria-label={`Reorder prompt ${i + 1}`}
+ onPointerDown={(e) => handlePointerDown(uid, e)}
+ onKeyDown={(e) => {
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ nudge(uid, -1);
+ } else if (e.key === "ArrowDown") {
+ e.preventDefault();
+ nudge(uid, 1);
+ }
+ }}
+ className={cn(
+ "mt-1.5 flex h-7 w-5 shrink-0 touch-none items-center justify-center rounded text-muted-foreground/30 hover:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring outline-none transition-colors",
+ isDragging ? "cursor-grabbing text-muted-foreground" : "cursor-grab",
+ )}
+ >
+ <GripVerticalIcon className="size-4" />
+ </button>
+ <span className="mt-2.5 w-5 shrink-0 text-right text-xs font-medium tabular-nums text-muted-foreground/60">
+ {i + 1}.
+ </span>
+ <div className="min-w-0 flex-1">
+ {preview ? (
+ <MarkdownPreview
+ markdown={item}
+ className="max-h-none w-full bg-background/40 p-3 text-sm"
+ />
+ ) : (
+ <AutoTextarea
+ value={item}
+ onChange={(v) => onChange(items.map((x, idx) => (idx === i ? v : x)))}
+ placeholder={`Prompt ${i + 1}...`}
+ />
+ )}
+ </div>
+ {preview ? null : (
+ <button
+ type="button"
+ onClick={() => {
+ onChange(items.filter((_, idx) => idx !== i));
+ setUids((prev) => prev.filter((_, idx) => idx !== i));
+ }}
+ disabled={items.length <= minItems}
+ className="mt-1.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
+ title="Remove"
+ >
+ <XIcon className="size-3.5" />
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/studio/frontend/tests/prompt-list-reorder.test.ts b/studio/frontend/tests/prompt-list-reorder.test.ts
new file mode 100644
index 00000000000..58799a2904b
--- /dev/null
+++ b/studio/frontend/tests/prompt-list-reorder.test.ts
@@ -0,0 +1,202 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import {
+ type RowBox,
+ flipShifts,
+ insertionIndex,
+ ownsDrag,
+} from "../src/features/chat/prompt-storage/reorder.ts";
+
+const GAP = 2;
+
+// Lay rows out the way the flex column does, so a reorder can be replayed
+// against the geometry it actually produces.
+function layout(heights: number[]): RowBox[] {
+ const rows: RowBox[] = [];
+ let top = 0;
+ for (const height of heights) {
+ rows.push({ top, height });
+ top += height + GAP;
+ }
+ return rows;
+}
+
+function move<T>(arr: T[], from: number, to: number): T[] {
+ const next = [...arr];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+}
+
+// One drag frame: hit-test, then re-lay-out at the resulting order.
+function step(
+ heights: number[],
+ from: number,
+ localY: number,
+): { order: number[]; heights: number[]; to: number } {
+ const to = insertionIndex(layout(heights), from, localY);
+ const order = move(
+ heights.map((_, i) => i),
+ from,
+ to,
+ );
+ return { order, heights: move(heights, from, to), to };
+}
+
+test("a pointer above every midpoint targets the first slot", () => {
+ assert.equal(insertionIndex(layout([40, 40, 40]), 2, 0), 0);
+});
+
+test("a pointer past every midpoint targets the last slot", () => {
+ assert.equal(insertionIndex(layout([40, 40, 40]), 0, 1000), 2);
+});
+
+test("the dragged row's own box does not count towards its target", () => {
+ const rows = layout([40, 40, 40]);
+ // Pointer inside row 0, which is also the row being dragged.
+ assert.equal(insertionIndex(rows, 0, 20), 0);
+ // The same pointer with row 1 dragged instead: row 0's midpoint is above it.
+ assert.equal(insertionIndex(rows, 1, 20), 0);
+});
+
+test("a short row dragged onto a tall one settles instead of oscillating", () => {
+ // The case bottom-edge hit-testing gets wrong: after the swap the tall row is
+ // still under the pointer, which sends the short row straight back.
+ let heights = [40, 200];
+ const pointer = 150;
+
+ const first = step(heights, 0, pointer);
+ assert.deepEqual(first.order, [1, 0]);
+ heights = first.heights;
+
+ // Same pointer, next frame: the dragged row is now at index 1 and stays.
+ const second = step(heights, 1, pointer);
+ assert.equal(second.to, 1);
+ assert.deepEqual(second.order, [0, 1]);
+});
+
+test("dragging back up over the tall row settles too", () => {
+ // Continue from the settled [tall, short] order above.
+ let heights = [200, 40];
+ const pointer = 90;
+
+ const first = step(heights, 1, pointer);
+ assert.deepEqual(first.order, [1, 0]);
+ heights = first.heights;
+
+ const second = step(heights, 0, pointer);
+ assert.equal(second.to, 0);
+});
+
+test("a drag across uneven rows reaches a fixed point at every pointer height", () => {
+ const heights = [40, 200, 60, 24, 120, 80];
+ for (let from = 0; from < heights.length; from++) {
+ for (let pointer = -40; pointer <= 640; pointer += 4) {
+ const first = step(heights, from, pointer);
+ const settledAt = first.to;
+ // Replaying the same pointer against the new layout must not move it
+ // again, or the drag flip-flops for as long as the pointer is held.
+ const second = step(first.heights, settledAt, pointer);
+ assert.equal(
+ second.to,
+ settledAt,
+ `row ${from} at y=${pointer} moved to ${settledAt} then ${second.to}`,
+ );
+ }
+ }
+});
+
+test("rows without a measured box are skipped rather than counted", () => {
+ const rows = layout([40, 40, 40]);
+ assert.equal(insertionIndex([rows[0], undefined, rows[2]], 0, 1000), 1);
+});
+
+// The grip does not capture the pointer, so the move/up/cancel listeners are on
+// `window` and see every pointer on the page.
+test("only the pointer that started the drag drives it", () => {
+ assert.equal(ownsDrag(3, 3), true);
+ assert.equal(ownsDrag(3, 7), false, "a second finger reordered with its own y");
+});
+
+// Ending a drag clears the id, but React unsubscribes the window listeners a
+// commit later. Treating "no active pointer" as a match let a button still held
+// after a window blur keep reordering in that gap.
+test("an ended drag owns no pointer at all", () => {
+ assert.equal(ownsDrag(null, 3), false, "a blur-ended drag kept reordering");
+ assert.equal(ownsDrag(null, 0), false, "pointer id 0 is a real id, not absent");
+});
+
+// Offsets of a flex column of equal rows, keyed the way the component keys them.
+function offsets(height: number): Map<string, number> {
+ const map = new Map<string, number>();
+ ["i1", "i2", "i3"].forEach((uid, i) => map.set(uid, i * (height + GAP)));
+ return map;
+}
+
+test("only the rows a reorder moved are animated", () => {
+ const before = offsets(100);
+ // i1 and i2 swap; i3 keeps its slot.
+ const after = new Map([
+ ["i2", 0],
+ ["i1", 102],
+ ["i3", 204],
+ ]);
+ assert.deepEqual(
+ [...flipShifts(before, after)].sort(),
+ [
+ ["i1", -102],
+ ["i2", 102],
+ ].sort(),
+ "a row that did not move must not be transformed",
+ );
+});
+
+// The bug this exists for: rows change height with the order untouched, from the
+// preview toggle and from a textarea regrowing on resize. A baseline captured at
+// the old heights describes a layout that is gone, and the next reorder shifts
+// rows that never moved.
+test("a baseline from the wrong heights moves rows that stayed put", () => {
+ const stale = offsets(40);
+ const after = new Map([
+ ["i2", 0],
+ ["i1", 102],
+ ["i3", 204],
+ ]);
+ const shifts = flipShifts(stale, after);
+ assert.equal(shifts.get("i3"), -120, "the untouched last row jumps 120px");
+ assert.equal(shifts.get("i2"), 42, "the swap animates from the wrong distance");
+});
+
+test("a row with no baseline is left alone rather than animated from zero", () => {
+ const shifts = flipShifts(new Map([["i1", 0]]), new Map([["i9", 300]]));
+ assert.equal(shifts.has("i9"), false);
+});
+
+test("sub-pixel settling is not worth a transform", () => {
+ const shifts = flipShifts(new Map([["i1", 10]]), new Map([["i1", 10.4]]));
+ assert.equal(shifts.size, 0);
+});
+
+// flipShifts is only correct if the component hands it a baseline read at the
+// reorder, so keep the capture where it belongs.
+test("the baseline is captured when the reorder is requested", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/sortable-prompt-items.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const captures = source.split("prevOffsets.current = measureOffsets();").length - 1;
+ assert.equal(captures, 1, "the FLIP baseline is captured somewhere else too");
+ const [beforeApply] = source.split("const applyOrder");
+ assert.doesNotMatch(
+ beforeApply,
+ /prevOffsets\.current =/,
+ "the baseline is recorded from a commit again, which the heights outrun",
+ );
+});
diff --git a/studio/frontend/tests/prompt-storage-mutation-lock.test.ts b/studio/frontend/tests/prompt-storage-mutation-lock.test.ts
new file mode 100644
index 00000000000..9461d160a47
--- /dev/null
+++ b/studio/frontend/tests/prompt-storage-mutation-lock.test.ts
@@ -0,0 +1,431 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import {
+ type LockSet,
+ acquire,
+ lockKey,
+ release,
+ sameListDraft,
+ samePromptDraft,
+} from "../src/features/chat/prompt-storage/mutation-lock.ts";
+
+const empty: LockSet = new Set<string>();
+
+test("a second caller cannot take a lock that is already held", () => {
+ const [held, took] = acquire(empty, "p1");
+ assert.equal(took, true);
+ const [again, tookAgain] = acquire(held, "p1");
+ assert.equal(tookAgain, false, "the delete ran while the save was in flight");
+ assert.equal(again, held, "the loser must not replace the set and re-render");
+});
+
+test("locks are per row, so one row's save does not block another", () => {
+ const [one] = acquire(empty, "p1");
+ const [two, took] = acquire(one, "p2");
+ assert.equal(took, true);
+ assert.deepEqual([...two].sort(), ["p1", "p2"]);
+});
+
+// The bug this file exists for: the detail pane is keyed by row id, so selecting
+// another row unmounts it. A lock held there came back false, and because the
+// save is an unconditional PUT it could land after the DELETE and resurrect the
+// row. Holding it above the key is what makes this sequence safe.
+test("a lock survives the row switch that unmounts the pane", () => {
+ let held: LockSet = empty;
+ [held] = acquire(held, "p1"); // Save on p1 starts.
+ // User selects p2, then p1 again. The pane remounts; the set does not.
+ assert.equal(held.has("p1"), true, "the remounted pane would see no lock");
+ const [, tookDelete] = acquire(held, "p1");
+ assert.equal(tookDelete, false, "delete slipped past a save still in flight");
+ held = release(held, "p1"); // The PUT settles.
+ const [, tookAfter] = acquire(held, "p1");
+ assert.equal(tookAfter, true, "the lock never came back");
+});
+
+test("releasing an id nobody holds is a no-op on the same set", () => {
+ const [held] = acquire(empty, "p1");
+ assert.equal(release(held, "p2"), held);
+ assert.equal(release(empty, "p1"), empty);
+});
+
+test("the detail panes do not own a mutation lock", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Both panes are mounted with key={entry.id}, so a useState lock inside one
+ // resets on every row switch. That is the defect; keep it from coming back.
+ assert.doesNotMatch(
+ source,
+ /const \[pending, setPending\] = useState/,
+ "a detail pane owns its lock again, which a row switch resets",
+ );
+ for (const prop of ["pending={mutatingIds.has(", "runMutation={runMutation}"]) {
+ assert.equal(
+ source.split(prop).length - 1,
+ 2,
+ `${prop} should reach both PromptDetail and PromptListDetail`,
+ );
+ }
+});
+
+// Codex, on the first version of the lock: reading the outcome of a functional
+// updater straight after scheduling it is not sound, because React may defer the
+// updater. The caller then skips the request while the id still gets acquired
+// later during render, with no finally left to release it, and the row's Save and
+// Delete stay disabled for good. The ref is the authority for that reason.
+test("the lock decides from the ref, not from a scheduled updater", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(source, /const mutatingRef = useRef<ReadonlySet<string>>/);
+ assert.match(
+ source,
+ /const \[held, started\] = acquire\(mutatingRef\.current, id\);/,
+ "the lock is decided from state again, which can be stale",
+ );
+ assert.doesNotMatch(
+ source,
+ /let started = false;/,
+ "the deferred-updater pattern is back",
+ );
+});
+
+// A save is async and the editor stays usable while it runs, so clearing the
+// draft on success can discard whatever was typed in the meantime.
+test("a draft that moved on while saving is not cleared", () => {
+ const submitted = { name: "notes", text: "first" };
+ assert.equal(samePromptDraft({ ...submitted }, submitted), true);
+ assert.equal(
+ samePromptDraft({ name: "notes", text: "first, then more" }, submitted),
+ false,
+ "the newer edit would be thrown away",
+ );
+ assert.equal(
+ samePromptDraft({ name: "renamed", text: "first" }, submitted),
+ false,
+ );
+});
+
+test("list drafts compare by items, not by identity", () => {
+ const submitted = { name: "l", items: ["a", "b"] };
+ assert.equal(sameListDraft({ name: "l", items: ["a", "b"] }, submitted), true);
+ assert.equal(sameListDraft({ name: "l", items: ["a", "c"] }, submitted), false);
+ assert.equal(
+ sameListDraft({ name: "l", items: ["a", "b", "c"] }, submitted),
+ false,
+ "an item appended while saving would be thrown away",
+ );
+ assert.equal(sameListDraft({ name: "l", items: ["a"] }, submitted), false);
+});
+
+// Creating a row cannot use the by-id lock, because the id does not exist until
+// the request is built. Both New forms awaited an unguarded PUT: a second click
+// minted a second id and stored a duplicate, and a rejection was unhandled, so a
+// failed create looked exactly like a successful one.
+test("both create paths are guarded and report failure", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Above the forms, like the row locks: the forms are conditionally mounted, so
+ // selecting a rail row while a create is out would otherwise hand a reopened
+ // form a fresh false guard and let it mint a second id for the same draft.
+ assert.equal(
+ source.split("= useCreateGuard();").length - 1,
+ 2,
+ "the create guard is not owned once per kind above the New forms",
+ );
+ const [beforeForms] = source.split("function NewPromptForm");
+ assert.doesNotMatch(
+ beforeForms,
+ /const \{ creating, create \} = useCreateGuard\(\);/,
+ "a New form owns its guard again, which a row switch resets",
+ );
+ for (const prop of ["creating={promptCreate.creating}", "creating={listCreate.creating}"]) {
+ assert.ok(source.includes(prop), `${prop} should reach its New form`);
+ }
+ assert.equal(
+ source.split("disabled={creating ").length - 1,
+ 2,
+ "a Save button stays live while its create is in flight",
+ );
+ for (const message of ["Could not create prompt", "Could not create list"]) {
+ assert.ok(source.includes(message), `a failed create is silent: ${message}`);
+ }
+ // The ref decides, for the reason the mutation lock's does.
+ assert.match(source, /if \(creatingRef\.current\) return;/);
+});
+
+// The draft is what covers the entry the pane still holds, which is the pre-save
+// copy until the list is refetched. Clearing it first flashes the old text back.
+test("a save clears its draft only after the refreshed entry is in", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.equal(
+ source.split("await onRefresh();\n onSaved(submitted);").length - 1,
+ 2,
+ "a save pane drops the draft before the refresh lands",
+ );
+ assert.doesNotMatch(
+ source,
+ /onSaved\(submitted\);\n\s+onRefresh\(\);/,
+ "the unawaited refresh is back",
+ );
+});
+
+// The parent keeps a row selected during render, so clearing the selection while
+// the deleted row is still in promptEntries reselects it. The pane then renders
+// an entry the backend no longer has until the refetch lands.
+test("a delete clears its selection only after the row is gone", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const leadIns = source.split("onDeleted(entry.id);").slice(0, -1);
+ assert.equal(leadIns.length, 2, "both detail panes should clear a deleted row");
+ for (const before of leadIns) {
+ assert.ok(
+ before.lastIndexOf("await onRefresh();") >
+ before.lastIndexOf("await runMutation("),
+ "a delete pane clears the selection before its refresh lands",
+ );
+ }
+ assert.doesNotMatch(
+ source,
+ /onDeleted\(entry\.id\);\n\s+onRefresh\(\);/,
+ "the unawaited refresh is back",
+ );
+});
+
+// DialogContent is overflow-hidden, so anything the dialog's own children add up
+// to past its height is gone, not scrollable. A minimum height on the body has
+// to predict the header and search block above it, and that block gets taller
+// when its text wraps on a narrow dialog. At 320x320 the guess left the body
+// 57px too tall and Use, Save and Run fell outside the clip.
+test("the dialog body claims no height it has to guess", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.doesNotMatch(
+ source,
+ /min-h-\[[^\]]*dvh/,
+ "the body floor is measured against the viewport again",
+ );
+ assert.match(
+ source,
+ /flex-1 min-h-0 overflow-y-auto px-4 sm:px-6/,
+ "the body no longer shrinks to whatever the chrome leaves it",
+ );
+ // The row minimums are what actually keeps each pane usable.
+ assert.match(source, /grid-rows-\[minmax\(132px,30%\)_minmax\(272px,1fr\)\]/);
+});
+
+// The New form's fields stay editable while its create is out, and Cancel can
+// start a fresh draft during one. Resetting unconditionally when the request
+// lands discarded text that never reached the server, which is the defect
+// samePromptDraft already guards on the edit panes.
+test("a create resets its draft only if it still holds what was sent", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(source, /samePromptDraft\(prev, submitted\) \? emptyPromptDraft\(\) : prev/);
+ assert.match(source, /sameListDraft\(prev, submitted\) \? emptyListDraft\(\) : prev/);
+ // The created path must not run the Cancel callback, which discards outright.
+ assert.doesNotMatch(
+ source,
+ /onCreated\([^)]*\);\n\s+onClose\(\);/,
+ "the created path closes through Cancel again, which resets unconditionally",
+ );
+ assert.equal(
+ source.split("onCreated(id, submitted, mounted.current);").length - 1,
+ 2,
+ "both create paths should hand the submitted snapshot up",
+ );
+});
+
+// The comparison is the same one the edit panes use, so the empty-draft case has
+// to behave: a create that lands after Cancel must not resurrect an empty form.
+test("an empty draft does not match a submitted one", () => {
+ assert.equal(samePromptDraft({ name: "", text: "" }, { name: "n", text: "t" }), false);
+ assert.equal(sameListDraft({ name: "", items: ["", ""] }, { name: "l", items: ["a"] }), false);
+});
+
+// Selecting the Lists tab auto-selects its first row, so the detail pane mounts
+// the editor with no click, and one controlled textarea per item makes that cost
+// grow faster than the item count. The backend takes 10000 items in one list, so
+// the editor has to be able to wait.
+test("an oversized list waits to be asked before mounting its editor", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(source, /const EDITOR_ROW_LIMIT = \d+;/);
+ const limit = Number(/const EDITOR_ROW_LIMIT = (\d+);/.exec(source)?.[1]);
+ assert.ok(limit > 0 && limit < 500, `${limit} is not a limit that avoids the freeze`);
+ // Latched, not recomputed: Add prompt on a list at the limit would otherwise
+ // take it past and unmount the editor the user is typing in.
+ assert.match(
+ source,
+ /const \[editorMounted, setEditorMounted\] = useState\(\n\s+\(\) => items\.length <= EDITOR_ROW_LIMIT,\n\s+\);/,
+ );
+ assert.doesNotMatch(
+ source,
+ /const editorMounted = \w+ \|\| items\.length <= EDITOR_ROW_LIMIT;/,
+ "the mount decision is recomputed from the live length again",
+ );
+ // Deferring the editor must not narrow what a save, run or export carries.
+ for (const readsFullItems of [
+ "const filtered = items.filter((t) => t.trim());",
+ "const runnableItems = items.filter((t) => t.trim());",
+ ]) {
+ assert.ok(source.includes(readsFullItems), `truncated: ${readsFullItems}`);
+ }
+});
+
+// A create outlives the form that started it, and completion used to clear the
+// search, move the selection and close whatever New form was open by then.
+test("a finished create only moves the view its own form still owns", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.equal(
+ source.split("onCreated(id, submitted, mounted.current);").length - 1,
+ 2,
+ "a create path does not say whether its form is still on screen",
+ );
+ assert.equal(
+ source.split("if (!fromOpenForm) return;").length - 1,
+ 2,
+ "a completion still navigates after the user left the form",
+ );
+ // The draft still resets on a match, wherever the user went.
+ const [, afterGuard] = source.split("const selectCreatedPrompt");
+ assert.ok(
+ afterGuard.indexOf("setNewPromptDraft(") < afterGuard.indexOf("if (!fromOpenForm) return;"),
+ "the guard skips the draft reset, leaving a saved prompt marked unsaved",
+ );
+});
+
+// searchQuery is shared by both tabs, so filtering one collection filters the
+// hidden one too. Correcting the hidden tab's selection against that dropped the
+// row it had, and clearing the query in an effect left one render to do it in.
+test("only the visible tab's selection is corrected", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.match(source, /if \(activeTab === "prompts"\) \{\n\s+if \(filteredPrompts\.length === 0\)/);
+ assert.match(source, /const selectTab = useCallback\(\(tab: Tab\) => \{/);
+ assert.doesNotMatch(
+ source,
+ /\}, \[activeTab\]\);/,
+ "the per-tab reset is an effect again, which renders once with the old query",
+ );
+ assert.doesNotMatch(source, /onClick=\{\(\) => setActiveTab\(tab\)\}/);
+});
+
+// main.tsx wraps the app in StrictMode, which replays an effect as setup,
+// cleanup, setup on mount. A flag only initialised at the ref stays false from
+// that first cleanup, so every create reported an unmounted form and the New
+// form never closed on success.
+test("the New form's mounted flag is set in effect setup", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.equal(
+ source.split("mounted.current = true;").length - 1,
+ 2,
+ "a New form only sets its mounted flag at the ref, which StrictMode clears",
+ );
+ assert.doesNotMatch(
+ source,
+ /useEffect\(\(\) => \(\) => \{ mounted\.current = false; \}, \[\]\);/,
+ "the cleanup-only effect is back",
+ );
+});
+
+// Prompts and prompt lists live in separate tables with independent ids, so an
+// import can give one of each the same id. One set keyed on the raw id let a
+// prompt's save disable the unrelated list's Save and Delete.
+test("a prompt and a list with one id do not share a lock", () => {
+ let held: LockSet = new Set<string>();
+ [held] = acquire(held, lockKey("prompt", "x"));
+ assert.equal(held.has(lockKey("list", "x")), false, "the list is locked too");
+ const [, tookList] = acquire(held, lockKey("list", "x"));
+ assert.equal(tookList, true, "the list could not start its own mutation");
+ const [, tookPromptAgain] = acquire(held, lockKey("prompt", "x"));
+ assert.equal(tookPromptAgain, false, "the prompt's own lock stopped working");
+});
+
+test("no id can be crafted to collide across the two kinds", () => {
+ // The prefix is part of the key, so reaching a list key needs a list.
+ assert.notEqual(lockKey("prompt", "list:abc"), lockKey("list", "abc"));
+ assert.notEqual(lockKey("list", "prompt:abc"), lockKey("prompt", "abc"));
+});
+
+test("both panes take their lock through lockKey", async () => {
+ const source = await readFile(
+ new URL(
+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ assert.equal(source.split('runMutation(lockKey("prompt", entry.id)').length - 1, 2);
+ assert.equal(source.split('runMutation(lockKey("list", entry.id)').length - 1, 2);
+ assert.doesNotMatch(
+ source,
+ /runMutation\(entry\.id,/,
+ "a raw id reaches the shared lock set again",
+ );
+ assert.doesNotMatch(
+ source,
+ /mutatingIds\.has\(selected(Prompt|List)\.id\)/,
+ "a pane's pending state is read off a raw id again",
+ );
+});