Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): add some prompt actions

joshistoastd701cbcd37ef
diff --git a/invokeai/frontend/webv2/src/workbench/generation/promptHistory.ts b/invokeai/frontend/webv2/src/workbench/generation/promptHistory.ts
new file mode 100644
index 0000000000..7b9fefdc02
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/promptHistory.ts
@@ -0,0 +1,55 @@
+import type { PromptHistoryItem } from '@workbench/types';
+
+import type { GenerateSettings } from './types';
+
+export const MAX_PROMPT_HISTORY = 100;
+
+export const normalizePromptHistoryItem = (item: PromptHistoryItem): PromptHistoryItem | null => {
+ const positivePrompt = item.positivePrompt.trim();
+ const negativePrompt = item.negativePrompt?.trim() || null;
+
+ if (positivePrompt.length === 0 && !negativePrompt) {
+ return null;
+ }
+
+ return { negativePrompt, positivePrompt };
+};
+
+const isSamePromptHistoryItem = (a: PromptHistoryItem, b: PromptHistoryItem): boolean =>
+ a.positivePrompt === b.positivePrompt && (a.negativePrompt ?? null) === (b.negativePrompt ?? null);
+
+export const addPromptHistoryItem = (
+ history: readonly PromptHistoryItem[],
+ item: PromptHistoryItem
+): PromptHistoryItem[] => {
+ const prompt = normalizePromptHistoryItem(item);
+
+ if (!prompt) {
+ return [...history];
+ }
+
+ return [prompt, ...history.filter((entry) => !isSamePromptHistoryItem(entry, prompt))].slice(0, MAX_PROMPT_HISTORY);
+};
+
+export const removePromptHistoryItem = (
+ history: readonly PromptHistoryItem[],
+ item: PromptHistoryItem
+): PromptHistoryItem[] => history.filter((entry) => !isSamePromptHistoryItem(entry, item));
+
+export const filterPromptHistory = (history: readonly PromptHistoryItem[], searchTerm: string): PromptHistoryItem[] => {
+ const query = searchTerm.trim().toLowerCase();
+
+ if (!query) {
+ return [...history];
+ }
+
+ return history.filter(
+ (item) =>
+ item.positivePrompt.toLowerCase().includes(query) || (item.negativePrompt ?? '').toLowerCase().includes(query)
+ );
+};
+
+export const getPromptHistoryItemFromGenerateSettings = (settings: GenerateSettings): PromptHistoryItem => ({
+ negativePrompt: settings.negativePromptEnabled ? settings.negativePrompt : null,
+ positivePrompt: settings.positivePrompt,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/promptUtilities.ts b/invokeai/frontend/webv2/src/workbench/generation/promptUtilities.ts
new file mode 100644
index 0000000000..de73b9bab1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/promptUtilities.ts
@@ -0,0 +1,36 @@
+import { apiFetchJson } from '@workbench/backend/http';
+
+export interface ExpandPromptRequest {
+ prompt: string;
+ model_key: string;
+ max_tokens?: number;
+ system_prompt?: string | null;
+}
+
+export interface ExpandPromptResponse {
+ expanded_prompt: string;
+ error?: string | null;
+}
+
+export interface ImageToPromptRequest {
+ image_name: string;
+ model_key: string;
+ instruction?: string;
+}
+
+export interface ImageToPromptResponse {
+ prompt: string;
+ error?: string | null;
+}
+
+export const expandPrompt = (request: ExpandPromptRequest): Promise<ExpandPromptResponse> =>
+ apiFetchJson('/api/v1/utilities/expand-prompt', {
+ body: JSON.stringify(request),
+ method: 'POST',
+ });
+
+export const imageToPrompt = (request: ImageToPromptRequest): Promise<ImageToPromptResponse> =>
+ apiFetchJson('/api/v1/utilities/image-to-prompt', {
+ body: JSON.stringify(request),
+ method: 'POST',
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index efa69c05b5..f21c50271f 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -7,6 +7,7 @@ import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsS
import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';
import { getWidgetsForRegion } from '@workbench/widgetRegistry';
import { focusPositivePrompt } from '@workbench/widgets/generate/promptFields';
+import { navigatePromptHistory } from '@workbench/widgets/generate/promptFields/promptHistoryNavigation';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';
@@ -31,6 +32,8 @@ export const FIRST_PARTY_APP_COMMAND_IDS = [
'app.selectWorkflowsTab',
'app.selectModelsTab',
'app.selectQueueTab',
+ 'app.promptHistoryPrev',
+ 'app.promptHistoryNext',
'app.focusPrompt',
'app.toggleLeftPanel',
'app.toggleRightPanel',
@@ -184,6 +187,28 @@ export const useRegisterFirstPartyCommands = () => {
id: 'app.focusPrompt',
title: 'Focus prompt',
}),
+ commandApi.register({
+ handler: () =>
+ navigatePromptHistory({
+ direction: -1,
+ dispatch,
+ models: modelsRef.current,
+ project: projectRef.current,
+ }),
+ id: 'app.promptHistoryPrev',
+ title: 'Previous prompt history item',
+ }),
+ commandApi.register({
+ handler: () =>
+ navigatePromptHistory({
+ direction: 1,
+ dispatch,
+ models: modelsRef.current,
+ project: projectRef.current,
+ }),
+ id: 'app.promptHistoryNext',
+ title: 'Next prompt history item',
+ }),
commandApi.register({
handler: () => {
const region = projectRef.current.widgetRegions.left;
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
index 3df36b908f..12a49eb30d 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx
@@ -173,7 +173,7 @@ export const InvokeControl = () => {
Invoke
</Text>
<HStack gap="1" maxW="full" mb="-0.5">
- <Text fontSize="2xs" fontWeight="600" lineHeight="1.1" opacity="0.85" truncate>
+ <Text fontSize="0.58rem" lineHeight="1.1" opacity="0.85" truncate>
{routeLabel}
</Text>
{isLocked ? <Icon as={LockKeyholeIcon} boxSize="2.5" flexShrink={0} /> : null}
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index 593b63f21d..c021ce8944 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -458,6 +458,7 @@ export interface Project {
widgetGraphs: Partial<Record<WidgetTypeId, GraphContract>>;
canvas: CanvasStateContract;
graphHistory: GraphHistorySnapshot[];
+ promptHistory: PromptHistoryItem[];
undoRedo: UndoRedoHistory;
queue: QueueState;
events: ProjectEvent[];
@@ -517,6 +518,11 @@ export interface GraphHistorySnapshot {
document?: ProjectGraphState;
}
+export interface PromptHistoryItem {
+ positivePrompt: string;
+ negativePrompt: string | null;
+}
+
export interface UndoRedoEntry {
id: string;
createdAt: string;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx
index af53a56b8d..e1d8d2c452 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx
@@ -1,4 +1,5 @@
import type { GenerateModelConfig, GenerateSettings } from '@workbench/generation/types';
+import type { PromptHistoryItem } from '@workbench/types';
import { Stack } from '@chakra-ui/react';
import { getPromptPolicy } from '@workbench/generation/baseGenerationPolicies';
@@ -14,14 +15,28 @@ interface GeneratePromptFieldsProps {
export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: GeneratePromptFieldsProps) => {
const promptPolicy = getPromptPolicy(selectedModel, settings);
+ const usePromptHistoryItem = (prompt: PromptHistoryItem) => {
+ onCommit(
+ promptPolicy.negativeVisible
+ ? {
+ negativePrompt: prompt.negativePrompt ?? '',
+ negativePromptEnabled: prompt.negativePrompt ? true : settings.negativePromptEnabled,
+ positivePrompt: prompt.positivePrompt,
+ }
+ : { positivePrompt: prompt.positivePrompt }
+ );
+ };
return (
<Stack gap="1" py="2">
<PositivePromptField
heightPx={settings.positivePromptHeightPx}
value={settings.positivePrompt}
+ loras={settings.loras}
+ selectedModel={selectedModel}
onChange={(positivePrompt) => onCommit({ positivePrompt })}
onResizeEnd={(positivePromptHeightPx) => onCommit({ positivePromptHeightPx })}
+ onUsePrompt={usePromptHistoryItem}
/>
{promptPolicy.negativeVisible ? (
<NegativePromptField
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx
new file mode 100644
index 0000000000..3c92d9801f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptActions.tsx
@@ -0,0 +1,616 @@
+import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/types';
+import type { ModelConfig } from '@workbench/models/types';
+import type { PromptHistoryItem } from '@workbench/types';
+import type { ChangeEvent } from 'react';
+
+import { HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } from '@chakra-ui/react';
+import { getApiErrorMessage } from '@workbench/backend/http';
+import { Button, IconButton, Scrollable, Tooltip } from '@workbench/components/ui';
+import { filterPromptHistory } from '@workbench/generation/promptHistory';
+import { expandPrompt, imageToPrompt } from '@workbench/generation/promptUtilities';
+import { getSelectedGalleryImage } from '@workbench/image-actions';
+import { ModelSelect } from '@workbench/models/components/ModelSelect';
+import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';
+import { shallowEqual, useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
+import {
+ BookDashedIcon,
+ CurlyBracesIcon,
+ HistoryIcon,
+ ImageUpIcon,
+ PlusIcon,
+ SparklesIcon,
+ TrashIcon,
+ Undo2Icon,
+} from 'lucide-react';
+import { useEffect, useId, useState } from 'react';
+
+import { insertPositivePromptText } from './promptFocus';
+
+const DISABLED_PROMPT_ACTIONS = [
+ { icon: BookDashedIcon, label: 'Prompt Template' },
+ { icon: CurlyBracesIcon, label: 'Show dynamic prompts' },
+];
+
+interface PositivePromptActionsProps {
+ loras: GenerateLora[];
+ onUsePrompt: (prompt: PromptHistoryItem) => void;
+ positivePrompt: string;
+ selectedModel: GenerateModelConfig | undefined;
+ onPositivePromptChange: (prompt: string) => void;
+}
+
+export const PositivePromptActions = ({
+ loras,
+ onPositivePromptChange,
+ onUsePrompt,
+ positivePrompt,
+ selectedModel,
+}: PositivePromptActionsProps) => (
+ <HStack gap="0.5">
+ <AddPromptTriggerButton
+ loras={loras}
+ positivePrompt={positivePrompt}
+ selectedModel={selectedModel}
+ onPositivePromptChange={onPositivePromptChange}
+ />
+ {DISABLED_PROMPT_ACTIONS.map(({ icon: ActionIcon, label }) => (
+ <Tooltip key={label} content={label}>
+ <IconButton aria-label={label} disabled size="2xs" variant="ghost">
+ <ActionIcon />
+ </IconButton>
+ </Tooltip>
+ ))}
+ <ExpandPromptButton onPositivePromptChange={onPositivePromptChange} positivePrompt={positivePrompt} />
+ <ImageToPromptButton onPositivePromptChange={onPositivePromptChange} />
+ <PositivePromptHistoryButton onUsePrompt={onUsePrompt} />
+ </HStack>
+);
+
+type PromptTriggerOption = {
+ group: string;
+ label: string;
+ value: string;
+};
+
+const getTriggerPhrases = (model: unknown): string[] => {
+ if (!model || typeof model !== 'object') {
+ return [];
+ }
+
+ const triggerPhrases = (model as { trigger_phrases?: unknown }).trigger_phrases;
+
+ return Array.isArray(triggerPhrases)
+ ? triggerPhrases.filter((phrase): phrase is string => typeof phrase === 'string' && phrase.trim().length > 0)
+ : [];
+};
+
+const getPromptTriggerOptions = ({
+ loras,
+ models,
+ selectedModel,
+}: {
+ loras: GenerateLora[];
+ models: readonly ModelConfig[];
+ selectedModel: GenerateModelConfig | undefined;
+}): PromptTriggerOption[] => {
+ const options: PromptTriggerOption[] = [];
+
+ for (const phrase of getTriggerPhrases(selectedModel)) {
+ options.push({ group: selectedModel?.name ?? 'Main model', label: phrase, value: phrase });
+ }
+
+ for (const lora of loras) {
+ if (!lora.isEnabled) {
+ continue;
+ }
+
+ for (const phrase of getTriggerPhrases(lora.model)) {
+ options.push({ group: lora.model.name, label: phrase, value: phrase });
+ }
+ }
+
+ if (selectedModel) {
+ for (const model of models) {
+ if (model.type === 'embedding' && model.base === selectedModel.base) {
+ options.push({ group: 'Compatible embeddings', label: model.name, value: `<${model.name}>` });
+ }
+ }
+ }
+
+ const seen = new Set<string>();
+
+ return options.filter((option) => {
+ const key = `${option.group}:${option.value}`;
+
+ if (seen.has(key)) {
+ return false;
+ }
+
+ seen.add(key);
+ return true;
+ });
+};
+
+const AddPromptTriggerButton = ({
+ loras,
+ onPositivePromptChange,
+ positivePrompt,
+ selectedModel,
+}: Pick<PositivePromptActionsProps, 'loras' | 'onPositivePromptChange' | 'positivePrompt' | 'selectedModel'>) => {
+ const { models } = useModelsSnapshot();
+ const triggerId = useId();
+ const [isOpen, setIsOpen] = useState(false);
+ const [searchTerm, setSearchTerm] = useState('');
+ const options = getPromptTriggerOptions({ loras, models, selectedModel });
+ const filteredOptions = options.filter((option) => {
+ const query = searchTerm.trim().toLowerCase();
+
+ return !query || option.label.toLowerCase().includes(query) || option.group.toLowerCase().includes(query);
+ });
+ const groupedOptions = filteredOptions.reduce<Array<{ group: string; options: PromptTriggerOption[] }>>(
+ (groups, option) => {
+ const existingGroup = groups.find((group) => group.group === option.group);
+
+ if (existingGroup) {
+ existingGroup.options.push(option);
+ } else {
+ groups.push({ group: option.group, options: [option] });
+ }
+
+ return groups;
+ },
+ []
+ );
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ }, []);
+
+ const selectTrigger = (trigger: string) => {
+ insertPositivePromptText({ onChange: onPositivePromptChange, text: trigger, value: positivePrompt });
+ setIsOpen(false);
+ };
+
+ return (
+ <Popover.Root
+ ids={{ trigger: triggerId }}
+ lazyMount
+ open={isOpen}
+ positioning={{ placement: 'bottom-end' }}
+ onOpenChange={(event) => {
+ setIsOpen(event.open);
+ if (event.open) {
+ setSearchTerm('');
+ }
+ }}
+ >
+ <Tooltip content="Add prompt trigger" ids={{ trigger: triggerId }}>
+ <Popover.Trigger asChild>
+ <IconButton aria-label="Add prompt trigger" size="2xs" variant="ghost">
+ <PlusIcon />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="22rem">
+ <Popover.Body p="2.5">
+ <Stack gap="2" h="18rem">
+ <Input
+ aria-label="Search prompt triggers"
+ disabled={options.length === 0}
+ placeholder="Search prompt triggers"
+ size="xs"
+ value={searchTerm}
+ onChange={(event) => setSearchTerm(event.currentTarget.value)}
+ />
+ <Separator />
+ <Scrollable flex="1" label="Prompt trigger options" minH="0">
+ {options.length === 0 ? (
+ <PromptHistoryEmptyText>No prompt triggers available.</PromptHistoryEmptyText>
+ ) : filteredOptions.length === 0 ? (
+ <PromptHistoryEmptyText>No matching triggers.</PromptHistoryEmptyText>
+ ) : (
+ <Stack gap="2">
+ {groupedOptions.map((group) => (
+ <Stack key={group.group} gap="0">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" px="2" textTransform="uppercase">
+ {group.group}
+ </Text>
+ {group.options.map((option, index) => (
+ <Button
+ key={`${option.group}-${option.value}-${index}`}
+ alignItems="start"
+ h="auto"
+ justifyContent="start"
+ px="2"
+ py="1.5"
+ size="xs"
+ variant="ghost"
+ transitionDuration="faster"
+ onClick={() => selectTrigger(option.value)}
+ >
+ <Text color="fg" fontSize="xs" textAlign="start" wordBreak="break-word">
+ {option.label}
+ </Text>
+ </Button>
+ ))}
+ </Stack>
+ ))}
+ </Stack>
+ )}
+ </Scrollable>
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+const ExpandPromptButton = ({
+ onPositivePromptChange,
+ positivePrompt,
+}: Pick<PositivePromptActionsProps, 'onPositivePromptChange' | 'positivePrompt'>) => {
+ const dispatch = useWorkbenchDispatch();
+ const { models } = useModelsSnapshot();
+ const triggerId = useId();
+ const [isOpen, setIsOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
+ const textLlmModels = models.filter((model) => model.type === 'text_llm');
+ const selectedModel = selectedModelKey ? textLlmModels.find((model) => model.key === selectedModelKey) : null;
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ }, []);
+
+ const runExpandPrompt = async () => {
+ if (!selectedModel || !positivePrompt.trim()) {
+ return;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const result = await expandPrompt({ model_key: selectedModel.key, prompt: positivePrompt });
+
+ if (result.expanded_prompt) {
+ onPositivePromptChange(result.expanded_prompt);
+ }
+
+ setIsOpen(false);
+ } catch (error) {
+ dispatch({ message: getApiErrorMessage(error, 'Could not expand the prompt.'), type: 'recordError' });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Popover.Root
+ ids={{ trigger: triggerId }}
+ lazyMount
+ open={isOpen}
+ positioning={{ placement: 'bottom-end' }}
+ onOpenChange={(event) => setIsOpen(event.open)}
+ >
+ <Tooltip
+ content={textLlmModels.length === 0 ? 'No Text LLM installed' : 'Expand prompt'}
+ ids={{ trigger: triggerId }}
+ >
+ <Popover.Trigger asChild>
+ <IconButton
+ aria-label="Expand prompt"
+ disabled={isLoading || !positivePrompt.trim()}
+ size="2xs"
+ variant="ghost"
+ >
+ <SparklesIcon />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="22rem">
+ <Popover.Body p="2.5">
+ <Stack gap="2.5">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ Expand Prompt
+ </Text>
+ {textLlmModels.length === 0 ? (
+ <Text color="fg.subtle" fontSize="xs">
+ Install a Text LLM model to expand prompts.
+ </Text>
+ ) : (
+ <>
+ <ModelSelect
+ isClearable={false}
+ modelTypes={['text_llm']}
+ placeholder="Select Text LLM"
+ size="xs"
+ value={selectedModelKey}
+ onChange={(model) => setSelectedModelKey(model?.key ?? null)}
+ />
+ <Button
+ disabled={!selectedModel || !positivePrompt.trim()}
+ loading={isLoading}
+ size="xs"
+ onClick={() => void runExpandPrompt()}
+ >
+ Expand
+ </Button>
+ </>
+ )}
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+const ImageToPromptButton = ({
+ onPositivePromptChange,
+}: Pick<PositivePromptActionsProps, 'onPositivePromptChange'>) => {
+ const dispatch = useWorkbenchDispatch();
+ const { models } = useModelsSnapshot();
+ const selectedImage = useActiveProjectSelector(getSelectedGalleryImage, shallowEqual);
+ const triggerId = useId();
+ const [isOpen, setIsOpen] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
+ const llavaModels = models.filter((model) => model.type === 'llava_onevision');
+ const selectedModel = selectedModelKey ? llavaModels.find((model) => model.key === selectedModelKey) : null;
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ }, []);
+
+ const runImageToPrompt = async () => {
+ if (!selectedImage || !selectedModel) {
+ return;
+ }
+
+ setIsLoading(true);
+
+ try {
+ const result = await imageToPrompt({ image_name: selectedImage.imageName, model_key: selectedModel.key });
+
+ if (result.prompt) {
+ onPositivePromptChange(result.prompt);
+ }
+
+ setIsOpen(false);
+ } catch (error) {
+ dispatch({
+ message: getApiErrorMessage(error, 'Could not generate a prompt from the selected image.'),
+ type: 'recordError',
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Popover.Root
+ ids={{ trigger: triggerId }}
+ lazyMount
+ open={isOpen}
+ positioning={{ placement: 'bottom-end' }}
+ onOpenChange={(event) => setIsOpen(event.open)}
+ >
+ <Tooltip
+ content={llavaModels.length === 0 ? 'No vision model installed' : 'Image to prompt'}
+ ids={{ trigger: triggerId }}
+ >
+ <Popover.Trigger asChild>
+ <IconButton aria-label="Image to prompt" disabled={isLoading} size="2xs" variant="ghost">
+ <ImageUpIcon />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="22rem">
+ <Popover.Body p="2.5">
+ <Stack gap="2.5">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ Image to Prompt
+ </Text>
+ {llavaModels.length === 0 ? (
+ <Text color="fg.subtle" fontSize="xs">
+ Install a LLaVA OneVision model to generate prompts from images.
+ </Text>
+ ) : (
+ <>
+ <ModelSelect
+ isClearable={false}
+ modelTypes={['llava_onevision']}
+ placeholder="Select vision model"
+ size="xs"
+ value={selectedModelKey}
+ onChange={(model) => setSelectedModelKey(model?.key ?? null)}
+ />
+ {selectedImage ? (
+ <HStack gap="2">
+ <Image
+ alt={selectedImage.imageName}
+ boxSize="10"
+ flexShrink="0"
+ objectFit="cover"
+ rounded="md"
+ src={selectedImage.thumbnailUrl || selectedImage.imageUrl}
+ />
+ <Text color="fg.subtle" fontSize="xs" truncate>
+ {selectedImage.imageName}
+ </Text>
+ </HStack>
+ ) : (
+ <Text color="fg.subtle" fontSize="xs">
+ Select an image in Gallery or Preview first.
+ </Text>
+ )}
+ <Button
+ disabled={!selectedImage || !selectedModel}
+ loading={isLoading}
+ size="xs"
+ onClick={() => void runImageToPrompt()}
+ >
+ Generate Prompt
+ </Button>
+ </>
+ )}
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+const PositivePromptHistoryButton = ({ onUsePrompt }: Pick<PositivePromptActionsProps, 'onUsePrompt'>) => {
+ const dispatch = useWorkbenchDispatch();
+ const promptHistory = useActiveProjectSelector((project) => project.promptHistory);
+ const historyTriggerId = useId();
+ const [isOpen, setIsOpen] = useState(false);
+ const [searchTerm, setSearchTerm] = useState('');
+ const filteredPrompts = filterPromptHistory(promptHistory, searchTerm);
+
+ const onChangeSearchTerm = (event: ChangeEvent<HTMLInputElement>) => {
+ setSearchTerm(event.currentTarget.value);
+ };
+
+ const usePrompt = (prompt: PromptHistoryItem) => {
+ onUsePrompt(prompt);
+ setIsOpen(false);
+ };
+
+ return (
+ <Popover.Root
+ ids={{ trigger: historyTriggerId }}
+ lazyMount
+ open={isOpen}
+ positioning={{ placement: 'bottom-end' }}
+ onOpenChange={(event) => setIsOpen(event.open)}
+ >
+ <Tooltip content="Prompt history" ids={{ trigger: historyTriggerId }}>
+ <Popover.Trigger asChild>
+ <IconButton aria-label="Prompt history" size="2xs" variant="ghost">
+ <HistoryIcon />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <Popover.Content bg="bg.muted" borderColor="border.emphasized" borderWidth="1px" w="24rem">
+ <Popover.Body p="2.5">
+ <Stack gap="2" h="18rem">
+ <HStack justify="space-between">
+ <Input
+ aria-label="Search prompt history"
+ disabled={promptHistory.length === 0}
+ placeholder="Search prompt history"
+ size="xs"
+ value={searchTerm}
+ onChange={onChangeSearchTerm}
+ />
+ <Button
+ disabled={promptHistory.length === 0}
+ size="xs"
+ variant="ghost"
+ onClick={() => dispatch({ type: 'clearPromptHistory' })}
+ >
+ <Icon as={TrashIcon} boxSize="3" />
+ Clear
+ </Button>
+ </HStack>
+ <Separator />
+ <Scrollable flex="1" label="Prompt history entries" minH="0">
+ {promptHistory.length === 0 ? (
+ <PromptHistoryEmptyText>No prompt history yet.</PromptHistoryEmptyText>
+ ) : filteredPrompts.length === 0 ? (
+ <PromptHistoryEmptyText>No matching prompts.</PromptHistoryEmptyText>
+ ) : (
+ <Stack gap="1">
+ {filteredPrompts.map((prompt, index) => (
+ <>
+ <PromptHistoryItemRow
+ key={`${prompt.positivePrompt}-${prompt.negativePrompt ?? ''}-${index}`}
+ prompt={prompt}
+ onUsePrompt={usePrompt}
+ />
+ <Separator />
+ </>
+ ))}
+ </Stack>
+ )}
+ </Scrollable>
+ <Text color="fg.subtle" fontSize="2xs" textAlign="center">
+ Alt+Up/Down switches between prompts while focused.
+ </Text>
+ </Stack>
+ </Popover.Body>
+ </Popover.Content>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+const PromptHistoryEmptyText = ({ children }: { children: string }) => (
+ <HStack h="full" justify="center" minH="9rem">
+ <Text color="fg.subtle" fontSize="xs">
+ {children}
+ </Text>
+ </HStack>
+);
+
+const PromptHistoryItemRow = ({
+ onUsePrompt,
+ prompt,
+}: {
+ onUsePrompt: (prompt: PromptHistoryItem) => void;
+ prompt: PromptHistoryItem;
+}) => {
+ const dispatch = useWorkbenchDispatch();
+
+ return (
+ <HStack align="start" gap="1.5" pr="1">
+ <IconButton aria-label="Use prompt" size="2xs" variant="ghost" onClick={() => onUsePrompt(prompt)}>
+ <Icon as={Undo2Icon} boxSize="3.5" />
+ </IconButton>
+ <Stack flex="1" gap="0.5" minW="0">
+ {prompt.positivePrompt ? (
+ <Text color="fg" fontSize="2xs" wordBreak="break-word">
+ <Text as="span" color="fg.subtle" fontWeight="600">
+ Prompt:
+ </Text>{' '}
+ {prompt.positivePrompt}
+ </Text>
+ ) : null}
+ {prompt.negativePrompt ? (
+ <Text color="fg" fontSize="2xs" wordBreak="break-word">
+ <Text as="span" color="fg.subtle" fontWeight="600">
+ Negative:
+ </Text>{' '}
+ {prompt.negativePrompt}
+ </Text>
+ ) : null}
+ </Stack>
+
+ <IconButton
+ aria-label="Delete prompt history item"
+ colorPalette="red"
+ size="2xs"
+ variant="ghost"
+ onClick={() => dispatch({ prompt, type: 'removePromptFromHistory' })}
+ >
+ <Icon as={TrashIcon} boxSize="3.5" />
+ </IconButton>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx
index 01994c7472..466ae9e09c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx
@@ -1,18 +1,44 @@
+import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/types';
+import type { PromptHistoryItem } from '@workbench/types';
import type { ChangeEvent } from 'react';
import { Field, ResizableTextarea } from '@workbench/components/ui';
+import { PositivePromptActions } from './PositivePromptActions';
import { registerPositivePromptElement } from './promptFocus';
+import { resetPromptHistoryNavigation } from './promptHistoryNavigation';
interface PositivePromptFieldProps {
heightPx: number;
+ loras: GenerateLora[];
+ selectedModel: GenerateModelConfig | undefined;
value: string;
onChange: (value: string) => void;
onResizeEnd: (heightPx: number) => void;
+ onUsePrompt: (prompt: PromptHistoryItem) => void;
}
-export const PositivePromptField = ({ heightPx, onChange, onResizeEnd, value }: PositivePromptFieldProps) => (
- <Field label="Prompt">
+export const PositivePromptField = ({
+ heightPx,
+ loras,
+ onChange,
+ onResizeEnd,
+ onUsePrompt,
+ selectedModel,
+ value,
+}: PositivePromptFieldProps) => (
+ <Field
+ label="Prompt"
+ labelEnd={
+ <PositivePromptActions
+ loras={loras}
+ positivePrompt={value}
+ selectedModel={selectedModel}
+ onPositivePromptChange={onChange}
+ onUsePrompt={onUsePrompt}
+ />
+ }
+ >
<ResizableTextarea
aria-label="Positive prompt"
defaultHeightPx={heightPx}
@@ -23,7 +49,10 @@ export const PositivePromptField = ({ heightPx, onChange, onResizeEnd, value }:
fontFamily="mono"
textareaRef={registerPositivePromptElement}
value={value}
- onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
+ resetPromptHistoryNavigation();
+ onChange(event.currentTarget.value);
+ }}
onResizeEnd={onResizeEnd}
/>
</Field>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.ts
index 5385c8cb17..0fcd60bba5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptFocus.ts
@@ -14,3 +14,27 @@ export const focusPositivePrompt = (): boolean => {
return true;
};
+
+export const isPositivePromptFocused = (): boolean =>
+ positivePromptElement !== null && document.activeElement === positivePromptElement;
+
+export const insertPositivePromptText = ({
+ onChange,
+ text,
+ value,
+}: {
+ onChange: (value: string) => void;
+ text: string;
+ value: string;
+}): void => {
+ const caret = positivePromptElement?.selectionStart ?? value.length;
+ const nextValue = `${value.slice(0, caret)}${text}${value.slice(caret)}`;
+ const nextCaret = caret + text.length;
+
+ onChange(nextValue);
+
+ window.requestAnimationFrame(() => {
+ positivePromptElement?.focus();
+ positivePromptElement?.setSelectionRange(nextCaret, nextCaret);
+ });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts
new file mode 100644
index 0000000000..2eec6c55d1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptHistoryNavigation.ts
@@ -0,0 +1,128 @@
+import type { GenerateModelConfig } from '@workbench/generation/types';
+import type { ModelConfig } from '@workbench/models/types';
+import type { Project } from '@workbench/types';
+import type { WorkbenchAction } from '@workbench/workbenchState';
+import type { Dispatch } from 'react';
+
+import { getPromptPolicy, isSupportedGenerateModel } from '@workbench/generation/baseGenerationPolicies';
+import { normalizeGenerateSettings } from '@workbench/generation/settings';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+
+import { isPositivePromptFocused } from './promptFocus';
+
+type NavigationState = {
+ historyIndex: number;
+ stashedPrompts: {
+ negativePrompt: string;
+ negativePromptEnabled: boolean;
+ positivePrompt: string;
+ };
+};
+
+let navigationState: NavigationState | null = null;
+
+export const resetPromptHistoryNavigation = (): void => {
+ navigationState = null;
+};
+
+const getSelectedGenerateModel = (
+ settings: ReturnType<typeof normalizeGenerateSettings>,
+ models: readonly ModelConfig[] | undefined
+): GenerateModelConfig | undefined => {
+ if (!settings || !models) {
+ return undefined;
+ }
+
+ return models.filter(isSupportedGenerateModel).find((model) => model.key === settings.modelKey);
+};
+
+const applyPromptHistoryIndex = ({
+ dispatch,
+ models,
+ project,
+}: {
+ dispatch: Dispatch<WorkbenchAction>;
+ models: readonly ModelConfig[] | undefined;
+ project: Project;
+}): void => {
+ if (!navigationState) {
+ return;
+ }
+
+ const prompt = project.promptHistory[navigationState.historyIndex];
+ const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));
+
+ if (!prompt || !settings) {
+ return;
+ }
+
+ const selectedModel = getSelectedGenerateModel(settings, models);
+ const promptPolicy = getPromptPolicy(selectedModel, settings);
+ const values: Record<string, unknown> = { positivePrompt: prompt.positivePrompt };
+
+ if (promptPolicy.negativeVisible) {
+ values.negativePrompt = prompt.negativePrompt ?? '';
+ values.negativePromptEnabled = prompt.negativePrompt ? true : settings.negativePromptEnabled;
+ }
+
+ dispatch({ type: 'patchWidgetValues', values, widgetId: 'generate' });
+};
+
+export const navigatePromptHistory = ({
+ direction,
+ dispatch,
+ models,
+ project,
+}: {
+ direction: -1 | 1;
+ dispatch: Dispatch<WorkbenchAction>;
+ models: readonly ModelConfig[] | undefined;
+ project: Project;
+}): void => {
+ if (!isPositivePromptFocused() || project.promptHistory.length === 0) {
+ return;
+ }
+
+ const settings = normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));
+
+ if (!settings) {
+ return;
+ }
+
+ if (direction === -1) {
+ if (!navigationState) {
+ navigationState = {
+ historyIndex: 0,
+ stashedPrompts: {
+ negativePrompt: settings.negativePrompt,
+ negativePromptEnabled: settings.negativePromptEnabled,
+ positivePrompt: settings.positivePrompt,
+ },
+ };
+ } else if (navigationState.historyIndex < project.promptHistory.length - 1) {
+ navigationState = { ...navigationState, historyIndex: navigationState.historyIndex + 1 };
+ }
+
+ applyPromptHistoryIndex({ dispatch, models, project });
+ return;
+ }
+
+ if (!navigationState) {
+ return;
+ }
+
+ const nextHistoryIndex = navigationState.historyIndex - 1;
+
+ if (nextHistoryIndex < 0) {
+ dispatch({
+ type: 'patchWidgetValues',
+ values: navigationState.stashedPrompts,
+ widgetId: 'generate',
+ });
+ navigationState = null;
+ return;
+ }
+
+ navigationState = { ...navigationState, historyIndex: nextHistoryIndex };
+ applyPromptHistoryIndex({ dispatch, models, project });
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 2458a5eb8b..d6695d2ac4 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { GenerateWidgetValues, MainModelConfig } from './generation/types';
import type { GeneratedImageContract, Project, WorkbenchState } from './types';
+import { MAX_PROMPT_HISTORY } from './generation/promptHistory';
import { DEFAULT_PROJECT_SETTINGS } from './settings/store';
import { getProjectWidgetValues } from './widgetState';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState';
@@ -792,6 +793,113 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(getActiveProject(state).queue.items).toEqual([]);
});
+ it('records submitted Generate prompt pairs in project prompt history', () => {
+ let state = primeGenerate(undefined, { negativePrompt: ' blurry ', positivePrompt: ' a cat ' });
+
+ state = submitGenerate(state);
+
+ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a cat' }]);
+ });
+
+ it('does not record empty Generate prompt pairs', () => {
+ let state = primeGenerate(undefined, { negativePrompt: ' ', positivePrompt: ' ' });
+
+ state = submitGenerate(state);
+
+ expect(getActiveProject(state).promptHistory).toEqual([]);
+ });
+
+ it('stores disabled negative prompts as null in project prompt history', () => {
+ let state = primeGenerate(undefined, {
+ negativePrompt: 'ignored negative prompt',
+ negativePromptEnabled: false,
+ positivePrompt: 'a cat',
+ });
+
+ state = submitGenerate(state);
+
+ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: null, positivePrompt: 'a cat' }]);
+ });
+
+ it('deduplicates prompt history by prompt pair and moves the newest submission to the top', () => {
+ let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });
+
+ state = submitGenerate(state);
+ state = workbenchReducer(state, {
+ type: 'setGenerateSettings',
+ values: createGenerateValues({ negativePrompt: 'blurry', positivePrompt: 'a dog' }),
+ });
+ state = submitGenerate(state);
+ state = workbenchReducer(state, {
+ type: 'setGenerateSettings',
+ values: createGenerateValues({ negativePrompt: 'low quality', positivePrompt: 'a cat' }),
+ });
+ state = submitGenerate(state);
+
+ expect(getActiveProject(state).promptHistory).toEqual([
+ { negativePrompt: 'low quality', positivePrompt: 'a cat' },
+ { negativePrompt: 'blurry', positivePrompt: 'a dog' },
+ ]);
+ });
+
+ it('caps project prompt history', () => {
+ let state = createInitialWorkbenchState();
+
+ for (let i = 0; i < MAX_PROMPT_HISTORY + 1; i += 1) {
+ state = primeGenerate(state, { positivePrompt: `prompt ${i}` });
+ state = submitGenerate(state);
+ }
+
+ const history = getActiveProject(state).promptHistory;
+
+ expect(history).toHaveLength(MAX_PROMPT_HISTORY);
+ expect(history[0]?.positivePrompt).toBe(`prompt ${MAX_PROMPT_HISTORY}`);
+ expect(history.at(-1)?.positivePrompt).toBe('prompt 1');
+ });
+
+ it('supports explicit prompt history remove and clear actions', () => {
+ let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });
+
+ state = submitGenerate(state);
+ state = workbenchReducer(state, {
+ prompt: { negativePrompt: 'blurry', positivePrompt: 'a dog' },
+ type: 'addPromptToHistory',
+ });
+ state = workbenchReducer(state, {
+ prompt: { negativePrompt: 'low quality', positivePrompt: 'a cat' },
+ type: 'removePromptFromHistory',
+ });
+
+ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a dog' }]);
+
+ state = workbenchReducer(state, { type: 'clearPromptHistory' });
+
+ expect(getActiveProject(state).promptHistory).toEqual([]);
+ });
+
+ it('does not roll back prompt history during project undo and redo', () => {
+ let state = primeGenerate(undefined, { positivePrompt: 'history prompt' });
+
+ state = submitGenerate(state);
+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });
+ state = workbenchReducer(state, { type: 'undoProjectChange' });
+ state = workbenchReducer(state, { type: 'redoProjectChange' });
+
+ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: null, positivePrompt: 'history prompt' }]);
+ });
+
+ it('hydrates older projects with empty prompt history', () => {
+ const initial = createInitialWorkbenchState();
+ const legacyState = {
+ ...initial,
+ projects: initial.projects.map(({ promptHistory: _promptHistory, ...project }) => project),
+ } as unknown as WorkbenchState;
+
+ const hydrated = workbenchReducer(initial, { state: legacyState, type: 'hydrateWorkbench' });
+
+ expect(getActiveProject(hydrated).promptHistory).toEqual([]);
+ });
+
it('routes Gallery destination results to Gallery without staging them on Canvas', () => {
let state = primeGenerate();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 0a05cfa223..a396d61fd5 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -19,6 +19,7 @@ import type {
ProjectLayoutState,
ProjectSettings,
ProjectUndoSnapshot,
+ PromptHistoryItem,
QueueItem,
QueueItemStatus,
ResultDestination,
@@ -40,8 +41,14 @@ import type { ProjectGraphState } from './workflows/types';
import { getGenerationModelAvailabilityReasons } from './generation/baseGenerationPolicies';
import { sanitizeBatchCount } from './generation/batch';
import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';
+import {
+ addPromptHistoryItem,
+ getPromptHistoryItemFromGenerateSettings,
+ removePromptHistoryItem,
+} from './generation/promptHistory';
import {
cloneGenerateWidgetValues,
+ normalizeGenerateSettings,
normalizeGenerateWidgetValues,
syncGenerateWidgetValuesWithModels,
} from './generation/settings';
@@ -105,6 +112,9 @@ type WorkbenchAction =
| { type: 'setRegionWidgetSize'; region: WidgetRegion; sizePx: number }
| { type: 'setGenerateSettings'; values: GenerateWidgetValues }
| { type: 'setGenerateBatchCount'; batchCount: number }
+ | { type: 'addPromptToHistory'; prompt: PromptHistoryItem }
+ | { type: 'removePromptFromHistory'; prompt: PromptHistoryItem }
+ | { type: 'clearPromptHistory' }
| { type: 'patchWidgetValues'; widgetId: WidgetTypeId; values: Record<string, unknown> }
| { type: 'patchWidgetInstanceValues'; instanceId: WidgetInstanceId; values: Record<string, unknown> }
| { type: 'setWidgetInstanceValues'; instanceId: WidgetInstanceId; values: Record<string, unknown> }
@@ -666,6 +676,29 @@ const ensureCenterRegion = (
};
};
+const normalizePromptHistory = (value: unknown): PromptHistoryItem[] => {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+
+ return value.reduceRight<PromptHistoryItem[]>((history, item) => {
+ if (!item || typeof item !== 'object') {
+ return history;
+ }
+
+ const record = item as Record<string, unknown>;
+
+ if (typeof record.positivePrompt !== 'string') {
+ return history;
+ }
+
+ return addPromptHistoryItem(history, {
+ negativePrompt: typeof record.negativePrompt === 'string' ? record.negativePrompt : null,
+ positivePrompt: record.positivePrompt,
+ });
+ }, []);
+};
+
const ensureProjectWidgetContracts = (project: Project): Project => {
const defaultWidgetRegions = createWidgetRegions();
const legacyWidgetRegions = project.widgetRegions as
@@ -677,6 +710,7 @@ const ensureProjectWidgetContracts = (project: Project): Project => {
...project,
canvas: cloneCanvas(project.canvas ?? createCanvasState()),
projectGraph: normalizeProjectGraph(project.projectGraph),
+ promptHistory: normalizePromptHistory((project as Partial<Project>).promptHistory),
settings: normalizeProjectSettings(project.settings),
widgetRegions: {
left: legacyWidgetRegions?.left ?? legacyWidgetRegions?.['left-panel'] ?? defaultWidgetRegions.left,
@@ -723,6 +757,7 @@ const createProject = (index: number, id = `project-${index}`): Project => ({
invocation: { ...defaultInvocationRoute },
layout: { ...defaultLayoutPreset.initialLayout, panels: { ...defaultLayoutPreset.initialLayout.panels } },
name: `Project Name #${index}`,
+ promptHistory: [],
projectGraph: createProjectGraph(`${id}-graph`),
queue: { items: [] },
settings: normalizeProjectSettings(),
@@ -1115,6 +1150,8 @@ const submitInvocationSnapshot = (
const { graph, widgetStates } = compiledSnapshot;
const graphHistorySnapshot = createGraphHistorySnapshot(`Queue snapshot ${queueItemId}`, graph);
+ const generateSettings =
+ route.sourceId === 'generate' ? normalizeGenerateSettings(widgetStates.generate.values) : null;
const queueItem: QueueItem = {
cancellable: backendSupportsCancellation,
id: queueItemId,
@@ -1143,6 +1180,9 @@ const submitInvocationSnapshot = (
...project.events,
],
graphHistory: [graphHistorySnapshot, ...project.graphHistory].slice(0, HISTORY_LIMIT),
+ promptHistory: generateSettings
+ ? addPromptHistoryItem(project.promptHistory, getPromptHistoryItemFromGenerateSettings(generateSettings))
+ : project.promptHistory,
invocation: {
...project.invocation,
destination: route.destination,
@@ -1435,6 +1475,21 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
updateProjectWidgetValues(project, 'generate', (values) => ({ ...values, batchCount }))
);
}
+ case 'addPromptToHistory': {
+ return updateActiveProject(state, (project) => ({
+ ...project,
+ promptHistory: addPromptHistoryItem(project.promptHistory, action.prompt),
+ }));
+ }
+ case 'removePromptFromHistory': {
+ return updateActiveProject(state, (project) => ({
+ ...project,
+ promptHistory: removePromptHistoryItem(project.promptHistory, action.prompt),
+ }));
+ }
+ case 'clearPromptHistory': {
+ return updateActiveProject(state, (project) => ({ ...project, promptHistory: [] }));
+ }
case 'patchWidgetValues': {
// Generic widget-owned UI state (panel modes, tabs, sizes). Not undoable.
return updateActiveProject(state, (project) =>
@@ -2142,6 +2197,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
...restoredProject,
events: project.events,
graphHistory: project.graphHistory,
+ promptHistory: project.promptHistory,
queue: project.queue,
undoRedo: {
future: [
@@ -2172,6 +2228,7 @@ export const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction)
...restoredProject,
events: project.events,
graphHistory: project.graphHistory,
+ promptHistory: project.promptHistory,
queue: project.queue,
undoRedo: {
future: project.undoRedo.future.slice(1),