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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(models): edit trigger phrases as tags
Josh Corbett817551814b2a
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.browser.test.tsxnew file mode 100644index 0000000000..2a2c9844f7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.browser.test.tsx@@ -0,0 +1,108 @@+import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { TriggerPhrasesEditor } from './TriggerPhrasesEditor';++const api = vi.hoisted(() => ({ updateModel: vi.fn() }));+const store = vi.hoisted(() => ({ replaceModelInStore: vi.fn() }));++vi.mock('@features/models/data/api', () => api);+vi.mock('@features/models/data/modelsStore', () => store);+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe('TriggerPhrasesEditor', () => {+ let host: HTMLDivElement;+ let root: Root;+ const onError = vi.fn();+ const mount = (phrases: readonly string[]) =>+ act(() => {+ root.render(+ <ChakraProvider value={system}>+ <TriggerPhrasesEditor modelKey="lora-1" phrases={phrases} onError={onError} />+ </ChakraProvider>+ );+ });+ const lastSaved = () => {+ const [, patch] = api.updateModel.mock.lastCall as [string, { trigger_phrases: string[] }];++ return patch.trigger_phrases;+ };+ const tagTexts = () =>+ [...host.querySelectorAll<HTMLElement>('[data-scope="tags-input"][data-part="item-text"]')].map(+ (element) => element.textContent+ );++ beforeEach(() => {+ api.updateModel.mockReset();+ api.updateModel.mockImplementation((_key: string, patch: { trigger_phrases: string[] }) =>+ Promise.resolve({ key: 'lora-1', trigger_phrases: patch.trigger_phrases })+ );+ store.replaceModelInStore.mockReset();+ onError.mockReset();+ accountLifecycle.activate('trigger-test-a', ':user:trigger-test-a');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+ });++ it('adds with Enter, refuses a duplicate, and removes from the tag', async () => {+ await mount(['alpha']);+ const input = page.getByRole('textbox', { name: 'models.triggerPhrases' });++ await input.fill('beta');+ await userEvent.keyboard('{Enter}');+ await expect.poll(() => api.updateModel.mock.calls.length).toBe(1);+ expect(lastSaved()).toEqual(['alpha', 'beta']);++ await input.fill('ALPHA');+ await userEvent.keyboard('{Enter}');+ await expect.element(page.getByText('models.triggerPhraseDuplicate')).toBeVisible();+ expect(api.updateModel).toHaveBeenCalledTimes(1);++ await page.getByRole('button', { name: 'models.removeTriggerPhrase' }).first().click();+ await expect.poll(() => api.updateModel.mock.calls.length).toBe(2);+ expect(lastSaved()).toEqual(['beta']);+ });++ it('edits a tag in place on double-click, keeping its position', async () => {+ await mount(['alpha', 'beta', 'gamma']);++ await page.getByText('beta', { exact: true }).dblClick();+ const itemInput = () =>+ host+ .querySelectorAll<HTMLElement>('[data-scope="tags-input"][data-part="item"]')[1]!+ .querySelector<HTMLInputElement>('[data-part="item-input"]')!;+ await expect.poll(() => itemInput().value).toBe('beta');+ expect(document.activeElement).toBe(itemInput());++ await userEvent.keyboard('{Backspace}{Backspace}{Backspace}{Backspace}Beta{Enter}');+ await expect.poll(() => api.updateModel.mock.calls.length).toBe(1);+ expect(lastSaved()).toEqual(['alpha', 'Beta', 'gamma']);+ expect(tagTexts()).toEqual(['alpha', 'Beta', 'gamma']);+ });++ it('puts the list back when a save fails', async () => {+ api.updateModel.mockRejectedValueOnce(new Error('offline'));+ await mount(['alpha']);++ await page.getByRole('textbox', { name: 'models.triggerPhrases' }).fill('beta');+ await userEvent.keyboard('{Enter}');+ await expect.poll(() => onError.mock.calls.length).toBe(1);++ expect(onError).toHaveBeenCalledWith('offline');+ expect(tagTexts()).toEqual(['alpha']);+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsxindex 29f1c4f033..bc7d4d5ecd 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/TriggerPhrasesEditor.tsx@@ -1,25 +1,27 @@-/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import { HStack, Icon, Input, Tag, Text, Wrap } from '@chakra-ui/react';+/* eslint-disable react-perf/jsx-no-new-function-as-prop */+import { TagsInput, Text } from '@chakra-ui/react';import { triggerPhraseSchema } from '@features/models/core/schemas';import { updateModel } from '@features/models/data/api';import { replaceModelInStore } from '@features/models/data/modelsStore';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';-import { Button, Field } from '@platform/ui';-import { PlusIcon } from 'lucide-react';+import { Field } from '@platform/ui';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';interface TriggerPhrasesEditorState {- draft: string;error: string | null;- isSaving: boolean;modelKey: string;+ /** The phrases prop this local value was derived from; a new prop replaces the value. */+ phrases: readonly string[];+ value: string[];}/**- * Tag-style editor for a model's trigger phrases. Each add/remove persists- * immediately — there is no separate save step for phrases.+ * Tag editor for a model's trigger phrases: type + Enter adds, Backspace or+ * the tag's control removes, double-click (or Enter on a highlighted tag)+ * edits in place. Every change persists immediately — there is no separate+ * save step — and a failed save puts the list back as it was.*/export const TriggerPhrasesEditor = ({modelKey,@@ -32,127 +34,89 @@ export const TriggerPhrasesEditor = ({}) => {const { t } = useTranslation();const [editor, setEditor] = useState<TriggerPhrasesEditorState>(() => ({- draft: '',error: null,- isSaving: false,modelKey,+ phrases,+ value: [...phrases],}));- const isEditorCurrent = editor.modelKey === modelKey;- const draft = isEditorCurrent ? editor.draft : '';- const error = isEditorCurrent ? editor.error : null;- const isSaving = isEditorCurrent ? editor.isSaving : false;- // The saving flag lives in the modelKey-scoped editor state (so it resets on- // model switch); the hook's own isBusy is unused, only its scope plumbing.- const { run } = useScopedAction();-- const persist = async (nextPhrases: string[]): Promise<boolean> => {- setEditor((current) => ({- draft: current.modelKey === modelKey ? current.draft : '',- error: current.modelKey === modelKey ? current.error : null,- isSaving: true,- modelKey,- }));-- const stopSaving = () =>- setEditor((current) => (current.modelKey === modelKey ? { ...current, isSaving: false } : current));- let saved = false;+ // Render-phase adjustment (not an effect): a new prop list — another model,+ // or a save that landed — replaces the local value wholesale.+ if (editor.modelKey !== modelKey || editor.phrases !== phrases) {+ setEditor({ error: null, modelKey, phrases, value: [...phrases] });+ }+ const { error, value } = editor;+ const { isBusy: isSaving, run } = useScopedAction();- await run(+ const persist = (nextPhrases: string[]) => {+ setEditor({ error: null, modelKey, phrases, value: nextPhrases });+ void run(async (owner) => {const updated = await updateModel(modelKey, { trigger_phrases: nextPhrases }, owner.signal);assertAccountScopeCurrent(owner);replaceModelInStore(updated);- saved = true;- stopSaving();},(_message, persistError) => {onError(persistError instanceof Error ? persistError.message : t('models.failedToUpdateTriggerPhrases'));- stopSaving();+ setEditor({ error: null, modelKey, phrases, value: [...phrases] });});-- return saved;};- const addPhrase = async () => {- const parsed = triggerPhraseSchema.safeParse(draft);-- if (!parsed.success) {- setEditor({- draft,- error: parsed.error.issues[0]?.message ?? t('models.invalidTriggerPhrase'),- isSaving,- modelKey,- });- return;- }-- if (phrases.some((phrase) => phrase.toLowerCase() === parsed.data.toLowerCase())) {- setEditor({ draft, error: t('models.triggerPhraseDuplicate'), isSaving, modelKey });- return;- }+ return (+ <Field error={error} helpText={t('models.triggerPhrasesHelp')} label={t('models.triggerPhrases')}>+ <TagsInput.Root+ blurBehavior="add"+ disabled={isSaving}+ editable+ size="sm"+ validate={({ inputValue, value: current }) => {+ const parsed = triggerPhraseSchema.safeParse(inputValue);- setEditor({ draft, error: null, isSaving, modelKey });+ if (!parsed.success) {+ setEditor({+ error: parsed.error.issues[0]?.message ?? t('models.invalidTriggerPhrase'),+ modelKey,+ phrases,+ value,+ });+ return false;+ }- // Clear the draft only once it is saved, so a failure never eats the text.- if (await persist([...phrases, parsed.data])) {- setEditor((current) => (current.modelKey === modelKey ? { ...current, draft: '' } : current));- }- };+ if (current.some((phrase) => phrase.toLowerCase() === parsed.data.toLowerCase())) {+ setEditor({ error: t('models.triggerPhraseDuplicate'), modelKey, phrases, value });+ return false;+ }- return (- <Field error={error} helpText={t('models.triggerPhrasesHelp')} label={t('models.triggerPhrases')}>- <HStack gap="1.5">- <Input- aria-invalid={error ? true : undefined}- placeholder={t('models.addTriggerPhrase')}- size="xs"- value={draft}- onChange={(event) => {- setEditor({ draft: event.currentTarget.value, error: null, isSaving, modelKey });- }}- onKeyDown={(event) => {- if (event.key === 'Enter') {- event.preventDefault();- void addPhrase();+ return true;+ }}+ value={value}+ w="full"+ onValueChange={({ value: next }) => persist(next)}+ >+ <TagsInput.Control>+ <TagsInput.Context>+ {(api) =>+ api.value.map((phrase, index) => (+ <TagsInput.Item key={`${phrase}:${index}`} index={index} value={phrase}>+ <TagsInput.ItemPreview>+ <TagsInput.ItemText>{phrase}</TagsInput.ItemText>+ <TagsInput.ItemDeleteTrigger aria-label={t('models.removeTriggerPhrase', { phrase })} />+ </TagsInput.ItemPreview>+ <TagsInput.ItemInput />+ </TagsInput.Item>+ ))}- }}- />- <Button- disabled={draft.trim().length === 0}- loading={isSaving}- size="xs"- variant="outline"- onClick={() => {- void addPhrase();- }}- >- <Icon as={PlusIcon} boxSize="3.5" />- {t('common.add')}- </Button>- </HStack>- {phrases.length > 0 ? (- <Wrap gap="1">- {phrases.map((phrase) => (- <Tag.Root key={phrase} size="sm" variant="surface">- <Tag.Label>{phrase}</Tag.Label>- <Tag.EndElement>- <Tag.CloseTrigger- aria-label={t('models.removeTriggerPhrase', { phrase })}- onClick={() => {- void persist(phrases.filter((existing) => existing !== phrase));- }}- />- </Tag.EndElement>- </Tag.Root>- ))}- </Wrap>- ) : (+ </TagsInput.Context>+ <TagsInput.Input aria-label={t('models.triggerPhrases')} placeholder={t('models.addTriggerPhrase')} />+ </TagsInput.Control>+ <TagsInput.HiddenInput />+ </TagsInput.Root>+ {value.length === 0 ? (<Text color="fg.subtle" fontSize="2xs">{t('models.noTriggerPhrasesYet')}</Text>- )}+ ) : null}</Field>);};