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
fix(webv2): make prompt weight adjustments reliable
Josh Corbettef8129521c5d
diff --git a/docs/src/content/docs/concepts/prompt-syntax.mdx b/docs/src/content/docs/concepts/prompt-syntax.mdxindex 5d26267c57..40f860fde4 100644--- a/docs/src/content/docs/concepts/prompt-syntax.mdx+++ b/docs/src/content/docs/concepts/prompt-syntax.mdx@@ -88,6 +88,16 @@ You can group phrases and apply weight to the whole group, then nest another weiIn this example, the outer group strengthens the whole phrase, and the inner group gives `blue eyes` even more emphasis.+## Adjust weights with the keyboard in Webv2++In a prompt field, select text and press **Ctrl+Up** or **Ctrl+Down** to raise or lower its attention. With no selection, the shortcut targets the word at the caret. Selecting a group's parentheses or weight targets its contents.++- A selection inside a group changes only the selected words. A selection crossing a group boundary changes the selected words on both sides.+- Symbolic weights move one `+` or `-` step. Numeric weights change by `0.1` of effective attention, including inherited group weights.+- The numeric attention preference controls new weights; existing group weights retain their style.+- Adjacent content with matching weights merges, while the adjusted content stays selected for the next keypress.+- Inside prompt functions, the shortcut adjusts prompt arguments and preserves function parameters. Use **Ctrl+Z** to undo a weight change.+## Blend prompts with `.blend()`Use `.blend()` to mix the meaning of two or more prompts.diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.tsindex 02be42e8cb..d9052cef6b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.test.ts@@ -58,4 +58,25 @@ describe('prompt AST', () => {expect(roundTrip("('one', 'two')\n.and()")).toBe("('one', 'two').and()");expect(roundTrip('(one, two)\n.and()')).toBe('(one, two).and()');});++ it.each(['a ) tail', '(unfinished', 'a <unfinished', '< spaced embedding >', 'a > b', 'café+', '🌄+', '𐐀𐐁+'])(+ 'preserves text and incomplete syntax: %s',+ (prompt) => {+ expect(roundTrip(prompt)).toBe(prompt);+ }+ );++ it('keeps unicode words and surrogate pairs together with their attention', () => {+ expect(tokenizePrompt('café+ 🌄+ 𐐀𐐁+').map((token) => token.type)).toEqual([+ 'word',+ 'weight',+ 'whitespace',+ 'word',+ 'weight',+ 'whitespace',+ 'word',+ 'weight',+ ]);+ expect(parsePrompt('🌄+')[0]).toMatchObject({ text: '🌄', attention: '+', range: { start: 0, end: 3 } });+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.tsindex 791214af28..48632e1976 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/ast.ts@@ -11,7 +11,7 @@ export type PromptToken =| { type: 'punct'; value: string; range: PromptRange }| { type: 'lparen'; range: PromptRange }| { type: 'rparen'; range: PromptRange }- | { type: 'weight'; value: PromptAttention; range: PromptRange }+ | { type: 'weight'; value: PromptAttention; range: PromptRange; source?: string }| { type: 'lembed'; range: PromptRange }| { type: 'rembed'; range: PromptRange }| { type: 'escaped_paren'; value: '(' | ')'; range: PromptRange };@@ -39,10 +39,10 @@ export type PromptAstNode =isSelection?: boolean;};-const WORD_CHAR = /[A-Za-z0-9_]/;+const WORD_CHAR = /[\p{L}\p{N}\p{M}_]/u;const WHITESPACE = /\s/;const NUMERIC_WEIGHT = /^[+-]?\d+(?:\.\d+)?/;-const SYMBOLIC_WEIGHT = /^[+-]+/;+const SYMBOLIC_WEIGHT = /^(?:\++|-+)/;const PUNCTUATION = new Set(['.',',',@@ -110,7 +110,7 @@ const readSymbolicAttention = (prompt: string, start: number): { value: string;const end = start + match.length;- if (isWordChar(prompt[end])) {+ if (isWordChar(prompt[end]) || prompt[end] === '+' || prompt[end] === '-') {return null;}@@ -134,10 +134,15 @@ const readNumericAttention = (prompt: string, start: number): { value: number; e};const readWord = (prompt: string, start: number): { token: PromptToken; extraToken?: PromptToken; end: number } => {- let end = start + 1;+ const first = String.fromCodePoint(prompt.codePointAt(start) ?? 0);+ let end = start + first.length;- while (end < prompt.length && isWordChar(prompt[end])) {- end++;+ while (isWordChar(first) && end < prompt.length) {+ const next = String.fromCodePoint(prompt.codePointAt(end) ?? 0);+ if (!isWordChar(next)) {+ break;+ }+ end += next.length;}const token: PromptToken = { type: 'word', value: prompt.slice(start, end), range: range(start, end) };@@ -188,7 +193,12 @@ export const tokenizePrompt = (prompt: string): PromptToken[] => {const weight = numeric ?? symbolic;if (weight) {- tokens.push({ type: 'weight', value: weight.value, range: range(index + 1, weight.end) });+ tokens.push({+ type: 'weight',+ value: weight.value,+ range: range(index + 1, weight.end),+ source: prompt.slice(index + 1, weight.end),+ });index = weight.end;} else {index++;@@ -208,7 +218,7 @@ export const tokenizePrompt = (prompt: string): PromptToken[] => {continue;}- if (isWordChar(char)) {+ if (!PUNCTUATION.has(char)) {const result = readWord(prompt, index);tokens.push(result.token);@@ -220,13 +230,7 @@ export const tokenizePrompt = (prompt: string): PromptToken[] => {continue;}- if (PUNCTUATION.has(char)) {- tokens.push({ type: 'punct', value: char, range: range(index, index + 1) });- index++;- continue;- }-- tokens.push({ type: 'word', value: char, range: range(index, index + 1) });+ tokens.push({ type: 'punct', value: char, range: range(index, index + 1) });index++;}@@ -254,7 +258,7 @@ const tokenSource = (token: PromptToken): string => {case 'escaped_paren':return `\\${token.value}`;case 'weight':- return String(token.value);+ return token.source ?? String(token.value);default:return token.value;}@@ -262,8 +266,25 @@ const tokenSource = (token: PromptToken): string => {class PromptParser {private index = 0;-- constructor(private readonly tokens: PromptToken[]) {}+ private lastEmbeddingEnd = -1;+ private readonly groupEnds = new Map<number, number>();++ constructor(private readonly tokens: PromptToken[]) {+ const openings: number[] = [];+ for (let index = 0; index < tokens.length; index++) {+ const type = tokens[index]?.type;+ if (type === 'rembed') {+ this.lastEmbeddingEnd = index;+ } else if (type === 'lparen') {+ openings.push(index);+ } else if (type === 'rparen') {+ const opening = openings.pop();+ if (opening !== undefined) {+ this.groupEnds.set(opening, index);+ }+ }+ }+ }parse(): PromptAstNode[] {return this.parseNodes();@@ -301,6 +322,21 @@ class PromptParser {}private unquotedPromptFunctionAhead(): boolean {+ const closing = this.groupEnds.get(this.index - 1);+ if (closing === undefined) {+ return false;+ }+ let tailOffset = closing - this.index + 1;+ while (this.peek(tailOffset)?.type === 'whitespace') {+ tailOffset++;+ }+ if (+ !this.isPunct(tailOffset, '.') ||+ this.peek(tailOffset + 1)?.type !== 'word' ||+ this.peek(tailOffset + 2)?.type !== 'lparen'+ ) {+ return false;+ }let offset = 0;let depth = 0;let hasComma = false;@@ -312,21 +348,7 @@ class PromptParser {depth++;} else if (token?.type === 'rparen') {if (depth === 0) {- if (!hasComma) {- return false;- }-- let tailOffset = offset + 1;-- while (this.peek(tailOffset)?.type === 'whitespace') {- tailOffset++;- }-- return (- this.isPunct(tailOffset, '.') &&- this.peek(tailOffset + 1)?.type === 'word' &&- this.peek(tailOffset + 2)?.type === 'lparen'- );+ return hasComma;}depth--;@@ -581,10 +603,13 @@ class PromptParser {return tokens;}- private parseNodes(): PromptAstNode[] {+ private parseNodes(inGroup = false): PromptAstNode[] {const nodes: PromptAstNode[] = [];- while (this.peek() && this.peek()?.type !== 'rparen') {+ while (this.peek()) {+ if (inGroup && this.peek()?.type === 'rparen') {+ break;+ }const token = this.consume();switch (token.type) {@@ -601,7 +626,7 @@ class PromptParser {break;}- const children = this.parseNodes();+ const children = this.parseNodes(true);let nodeEnd = lparen.range.end;let attention: PromptAttention | undefined;@@ -614,14 +639,19 @@ class PromptParser {attention = weight.value;nodeEnd = weight.range.end;}- } else if (children.length > 0) {- nodeEnd = children.at(-1)?.range.end ?? nodeEnd;+ } else {+ nodes.push({ type: 'punct', value: '(', range: lparen.range }, ...children);+ break;}nodes.push({ type: 'group', attention, children, range: range(lparen.range.start, nodeEnd) });break;}case 'lembed': {+ if (this.lastEmbeddingEnd < this.index) {+ nodes.push({ type: 'punct', value: '<', range: token.range });+ break;+ }let value = '';let nodeEnd = token.range.end;@@ -635,7 +665,7 @@ class PromptParser {nodeEnd = this.consume().range.end;}- nodes.push({ type: 'embedding', value: value.trim(), range: range(token.range.start, nodeEnd) });+ nodes.push({ type: 'embedding', value, range: range(token.range.start, nodeEnd) });break;}case 'word': {@@ -658,6 +688,7 @@ class PromptParser {nodes.push({ type: 'escaped_paren', value: token.value, range: token.range });break;default:+ nodes.push({ type: 'punct', value: tokenSource(token), range: token.range });break;}}@@ -713,12 +744,48 @@ interface SerializeVisitor {onNode?: (node: PromptAstNode, start: number, end: number) => void;}-const appendAttention = (attention: PromptAttention | undefined): string =>- attention === undefined ? '' : String(attention);+const appendAttention = (attention: PromptAttention | undefined): string => {+ const value = attention === undefined ? '' : String(attention);+ if (typeof attention !== 'number' || !value.includes('e')) {+ return value;+ }+ // Compel's numeric syntax does not accept exponent notation.+ const [coefficient = '', exponent = '0'] = value.split('e');+ const sign = coefficient.startsWith('-') ? '-' : '';+ const [whole = '', fraction = ''] = coefficient.replace('-', '').split('.');+ const digits = whole + fraction;+ const point = whole.length + Number(exponent);+ if (point <= 0) {+ return `${sign}0.${'0'.repeat(-point)}${digits}`;+ }+ return point >= digits.length+ ? `${sign}${digits}${'0'.repeat(point - digits.length)}`+ : `${sign}${digits.slice(0, point)}.${digits.slice(point)}`;+};-const serializeInto = (nodes: PromptAstNode[], output: { value: string }, visitor?: SerializeVisitor): void => {- for (const node of nodes) {+const needsAttentionBoundary = (node: PromptAstNode, next: PromptAstNode | undefined): boolean => {+ if ((node.type !== 'word' && node.type !== 'group') || node.attention === undefined || !next) {+ return false;+ }+ const nextText = next.type === 'word' ? next.text : next.type === 'punct' ? next.value : '';+ return (+ isWordChar(nextText[0]) || (typeof node.attention === 'number' ? nextText.startsWith('.') : /^[+-]/.test(nextText))+ );+};++const serializeInto = (+ nodes: PromptAstNode[],+ output: { value: string },+ visitor?: SerializeVisitor,+ source?: string+): void => {+ for (let index = 0; index < nodes.length; index++) {+ const node = nodes[index]!;const start = output.value.length;+ const needsBoundary = needsAttentionBoundary(node, nodes[index + 1]);+ if (needsBoundary) {+ output.value += '(';+ }switch (node.type) {case 'punct':@@ -733,13 +800,23 @@ const serializeInto = (nodes: PromptAstNode[], output: { value: string }, visitobreak;case 'group':output.value += '(';- serializeInto(node.children, output, visitor);+ serializeInto(node.children, output, visitor, source);output.value += `)${appendAttention(node.attention)}`;break;case 'embedding':output.value += `<${node.value}>`;break;case 'prompt_function':+ if (source !== undefined) {+ let cursor = node.range.start;+ for (const arg of node.promptArgs) {+ output.value += source.slice(cursor, arg.contentRange.start);+ serializeInto(arg.nodes, output, visitor, source);+ cursor = arg.contentRange.end;+ }+ output.value += source.slice(cursor, node.range.end);+ break;+ }output.value += '(';node.promptArgs.forEach((arg, index) => {if (index > 0) {@@ -747,13 +824,16 @@ const serializeInto = (nodes: PromptAstNode[], output: { value: string }, visito}output.value += arg.quote;- serializeInto(arg.nodes, output, visitor);+ serializeInto(arg.nodes, output, visitor, source);output.value += CLOSE_QUOTE_BY_OPEN[arg.quote] ?? arg.quote;});output.value += `).${node.name}(${node.functionParams})`;break;}+ if (needsBoundary) {+ output.value += ')';+ }visitor?.onNode?.(node, start, output.value.length);}};@@ -767,22 +847,28 @@ export const serializePrompt = (nodes: PromptAstNode[]): string => {};export const serializePromptWithSelection = (- nodes: PromptAstNode[]+ nodes: PromptAstNode[],+ source?: string): { prompt: string; selectionStart: number; selectionEnd: number } => {const output = { value: '' };let selectionStart = Infinity;let selectionEnd = -1;- serializeInto(nodes, output, {- onNode: (node, start, end) => {- if (!node.isSelection) {- return;- }+ serializeInto(+ nodes,+ output,+ {+ onNode: (node, start, end) => {+ if (!node.isSelection) {+ return;+ }- selectionStart = Math.min(selectionStart, start);- selectionEnd = Math.max(selectionEnd, end);+ selectionStart = Math.min(selectionStart, start);+ selectionEnd = Math.max(selectionEnd, end);+ },},- });+ source+ );if (selectionStart === Infinity) {return { prompt: output.value, selectionStart: 0, selectionEnd: output.value.length };diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.tsindex c24305d802..9057e89ece 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.test.ts@@ -19,6 +19,104 @@ const adjust = (};describe('prompt attention adjustment', () => {+ it.each([+ ['(a b)++', 'a', 'decrement', '(a b+)+'],+ ['(a b+)++', 'a', 'increment', '(a b)+++'],+ ['x (a+ b)+', 'x (a+', 'increment', '(x a++ b)+'],+ ['(a b)+', 'a', 'increment', '(a+ b)+'],+ ] as const)('adjusts and absorbs group selections: %s / %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected, direction).prompt).toBe(expected);+ });++ it('keeps inherited symbolic attention when numeric style is preferred for new weights', () => {+ expect(adjust('(a b)+', 'a', 'increment', true).prompt).toBe('(a+ b)+');+ });++ it('preserves nested prompt functions when surrounding text changes', () => {+ expect(adjust("(x ('a', 'b').and())+", 'x', 'increment').prompt).toBe("(x+ ('a', 'b').and())+");+ });++ it('does not delete text after an unmatched closing parenthesis', () => {+ expect(adjust('a ) tail', 'a', 'increment').prompt).toBe('a+ ) tail');+ });++ it('keeps the selection local after absorbing an equal-weight neighbour', () => {+ const first = adjust('(a b+)++', 'a', 'increment');+ expect(first.prompt).toBe('(a b)+++');+ expect(first.prompt.slice(first.selectionStart, first.selectionEnd)).toBe('a');+ expect(adjustPromptAttention(first.prompt, first.selectionStart, first.selectionEnd, 'decrement').prompt).toBe(+ '(a b+)++'+ );+ });++ it('retains separate words when touching groups merge or become neutral', () => {+ expect(adjust('(a)1.1(b)1.2', 'a', 'increment').prompt).toBe('(a b)1.2');+ expect(adjust('(red)cat blue', 'blue', 'increment').prompt).toBe('red cat blue+');+ const result = adjust('(red)+(blue)+', 'red', 'decrement');+ expect(result).toEqual({ prompt: 'red blue+', selectionStart: 0, selectionEnd: 3 });+ expect(adjustPromptAttention(result.prompt, result.selectionStart, result.selectionEnd, 'decrement').prompt).toBe(+ 'red- blue+'+ );+ });++ it.each([+ [1, '(red+ blue)+'],+ [9, '(red blue+)+'],+ [0, '(red blue)++'],+ [10, '(red blue)++'],+ ])('targets the adjacent word at content boundaries and the group outside them: caret %s', (caret, expected) => {+ expect(adjust('(red blue)+', [caret as number, caret as number], 'increment').prompt).toBe(expected);+ });++ it.each([+ ['a (b)1.1', 'a', 'increment', '(a b)1.1'],+ ['(a)1.1 b', 'b', 'increment', '(a b)1.1'],+ ['(a b)1.2', 'a', 'decrement', '(a)1.1 (b)1.2'],+ ['(a+ b)1.2', 'a+', 'increment', '(a)1.42 (b)1.2'],+ ['((a)1.2 b)+', 'a', 'increment', '(a)1.42 b+'],+ ['(a- b)+ c', 'c', 'increment', '(a)0.99 (b c)+'],+ ['(a)0 b', 'a', 'decrement', '(a)-0.1 b'],+ ['a (b c)+', 'a (', 'increment', '(a b c)+'],+ ['café landscape', 'café', 'increment', 'café+ landscape'],+ ['🌄 landscape', '🌄', 'increment', '🌄+ landscape'],+ ['🌄+ landscape', '🌄+', 'decrement', '🌄 landscape'],+ ['razor-sharp teeth', 'razor', 'increment', '(razor+)-sharp teeth'],+ ['(a)0.0000001 b', 'b', 'increment', '(a)0.0000001 b+'],+ ['a (unfinished', 'a', 'increment', 'a+ (unfinished'],+ ['a <unfinished', 'a', 'increment', 'a+ <unfinished'],+ ['a )1.20 tail', 'a', 'increment', 'a+ )1.20 tail'],+ ["( 'a',\n 'b' ) .blend(0.70, 0.30)", 'a', 'increment', "( 'a+',\n 'b' ) .blend(0.70, 0.30)"],+ ["(x ('a', 'b').and())+", 'a', 'increment', "(x ('a+', 'b').and())+"],+ ["(x ('a', 'b').and())2", 'a', 'increment', "(x ('(a)1.05', 'b').and())2"],+ ["(('a', 'b').and(), c).blend(0.5, 0.5)", 'a', 'increment', "(('a+', 'b').and(), c).blend(0.5, 0.5)"],+ ] as const)('handles weight and syntax boundaries: %s / %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected, direction).prompt).toBe(expected);+ });++ it.each([' ', '\n', '().and()', "('a', 'b').blend(0.7, 0.3)"])(+ 'leaves non-content selections alone: %s',+ (prompt) => {+ const selection: [number, number] = prompt.includes('blend') ? [prompt.indexOf('0.7'), prompt.length] : [0, 1];+ expect(adjust(prompt, selection, 'increment').prompt).toBe(prompt);+ }+ );++ it.each(['increment', 'decrement'] as const)('keeps long sequences of symbolic steps exact: %s', (direction) => {+ let result = { prompt: 'a b', selectionStart: 0, selectionEnd: 1 };+ for (let count = 0; count < 100; count++) {+ result = adjustPromptAttention(result.prompt, result.selectionStart, result.selectionEnd, direction);+ }+ expect(result.prompt).toBe(`a${(direction === 'increment' ? '+' : '-').repeat(100)} b`);+ for (let count = 0; count < 100; count++) {+ result = adjustPromptAttention(+ result.prompt,+ result.selectionStart,+ result.selectionEnd,+ direction === 'increment' ? 'decrement' : 'increment'+ );+ }+ expect(result).toEqual({ prompt: 'a b', selectionStart: 0, selectionEnd: 1 });+ });it.each([['hello world', 'hello', 'increment', 'hello+ world'],['hello world', 'hello', 'decrement', 'hello- world'],diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.tsindex 3c15b55e63..a2274bba74 100644--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/attention.ts@@ -1,4 +1,4 @@-import type { PromptAstNode, PromptAttention, PromptFunctionArg, PromptRange } from './ast';+import type { PromptAstNode, PromptAttention, PromptRange } from './ast';import { parsePrompt, serializePromptWithSelection } from './ast';@@ -10,532 +10,320 @@ export interface PromptAttentionAdjustment {selectionEnd: number;}-const ATTENTION_FACTOR = 1.1;-const NUMERIC_STEP = 0.1;-const WEIGHT_EPSILON = 0.001;-const FACTOR_EPSILON = 0.005;-const GENERATED_RANGE: PromptRange = { start: 0, end: 0 };+type LeafNode = Exclude<PromptAstNode, { type: 'group' }>;-type PromptFunctionNode = Extract<PromptAstNode, { type: 'prompt_function' }>;-type LeafNode = Exclude<PromptAstNode, { type: 'group' | 'prompt_function' }>;+interface Weight {+ value: number;+ /** Exact symbolic steps avoid logarithms, rounding drift and tolerance-based regrouping. */+ steps: number | null;+ explicit: boolean;+}interface WeightedLeaf {- text: string;- type: LeafNode['type'];- weight: number;- range: PromptRange;- parentRange?: PromptRange;- hasExplicitAttention: boolean;- usesNumericAttention: boolean;- isSelected: boolean;+ node: LeafNode;+ weight: Weight;+ selected: boolean;}-type Region =- | { type: 'normal'; nodes: PromptAstNode[]; range: PromptRange }- | { type: 'prompt_function'; node: PromptFunctionNode };--const roundWeight = (weight: number): number => Number(weight.toFixed(4));--const isNeutralWeight = (weight: number): boolean => Math.abs(weight - 1) < WEIGHT_EPSILON;--const parseAttention = (attention: PromptAttention): number => {- if (typeof attention === 'number') {- return attention;- }-- if (attention.startsWith('+')) {- return ATTENTION_FACTOR ** attention.length;- }-- if (attention.startsWith('-')) {- return ATTENTION_FACTOR ** -attention.length;- }-- const numeric = Number(attention);-- return Number.isNaN(numeric) ? 1 : numeric;-};--const getSymbolicStepCount = (weight: number): number | null => {- if (weight <= 0) {- return null;- }-- if (isNeutralWeight(weight)) {- return 0;- }-- const steps = Math.round(Math.log(weight) / Math.log(ATTENTION_FACTOR));-- if (steps === 0) {- return null;- }-- return Math.abs(ATTENTION_FACTOR ** steps - weight) < FACTOR_EPSILON ? steps : null;-};+const NEUTRAL: Weight = { value: 1, steps: 0, explicit: false };+const GENERATED_RANGE: PromptRange = { start: 0, end: 0 };+const roundWeight = (weight: number): number => Number(weight.toPrecision(15));+const symbolicValue = (steps: number): number => (steps >= 0 ? 1.1 ** steps : 0.9 ** -steps);-const addSymbolicAttention = (current: PromptAttention | undefined, next: '+' | '-'): PromptAttention | undefined => {- if (current === undefined) {- return next;+const combineWeights = (parent: Weight, child: Weight): Weight => {+ if (!parent.explicit) {+ return child;}-- if (typeof current === 'number') {- return next === '+' ? roundWeight(current * ATTENTION_FACTOR) : roundWeight(current / ATTENTION_FACTOR);+ if (!child.explicit) {+ return parent;}-- const cancels = (current.startsWith('+') && next === '-') || (current.startsWith('-') && next === '+');-- if (!cancels) {- return `${current}${next}`;- }-- const remaining = current.slice(1);-- return remaining ? remaining : undefined;-};--const clipRange = (selectionStart: number, selectionEnd: number, range: PromptRange): PromptRange | null => {- if (selectionStart === selectionEnd) {- return selectionStart >= range.start && selectionStart <= range.end- ? { start: selectionStart, end: selectionEnd }+ // Opposite symbolic signs multiply in Compel (1.1 * 0.9 = 0.99); they do not cancel.+ const combinedSteps =+ parent.steps !== null &&+ child.steps !== null &&+ (parent.steps === 0 || child.steps === 0 || Math.sign(parent.steps) === Math.sign(child.steps))+ ? parent.steps + child.steps: null;- }-- const start = Math.max(selectionStart, range.start);- const end = Math.min(selectionEnd, range.end);-- return start < end ? { start, end } : null;-};--const rangesOverlap = (selectionStart: number, selectionEnd: number, range: PromptRange): boolean => {- if (selectionStart === selectionEnd) {- return range.start <= selectionStart && range.end >= selectionStart;- }-- return range.start < selectionEnd && range.end > selectionStart;-};--const extractRegions = (nodes: PromptAstNode[]): Region[] => {- const regions: Region[] = [];- let normalNodes: PromptAstNode[] = [];-- const flushNormalNodes = () => {- const first = normalNodes[0];- const last = normalNodes.at(-1);-- if (!first || !last) {- return;- }-- regions.push({ type: 'normal', nodes: normalNodes, range: { start: first.range.start, end: last.range.end } });- normalNodes = [];+ return {+ value: combinedSteps === null ? roundWeight(parent.value * child.value) : symbolicValue(combinedSteps),+ steps: combinedSteps,+ explicit: parent.explicit || child.explicit,};+};- for (const node of nodes) {- if (node.type === 'prompt_function') {- flushNormalNodes();- regions.push({ type: 'prompt_function', node });- } else {- normalNodes.push(node);- }+const inheritWeight = (parent: Weight, attention: PromptAttention | undefined): Weight => {+ if (attention === undefined) {+ return parent;}-- flushNormalNodes();-- return regions;+ const steps = typeof attention === 'number' ? null : attention.startsWith('+') ? attention.length : -attention.length;+ return combineWeights(parent, {+ value: typeof attention === 'number' ? attention : symbolicValue(steps!),+ steps,+ explicit: true,+ });};-const flattenNodes = (- nodes: PromptAstNode[],- inheritedWeight = 1,- parentRange?: PromptRange,- inheritedNumericAttention = false-): WeightedLeaf[] => {- const leaves: WeightedLeaf[] = [];+const overlaps = (selection: PromptRange, range: PromptRange): boolean =>+ selection.start === selection.end+ ? range.start <= selection.start && range.end >= selection.start+ : range.start < selection.end && range.end > selection.start;+/** A selection of a group's delimiters/weight targets that group's contents. */+const resolveSelection = (nodes: PromptAstNode[], selection: PromptRange): PromptRange => {for (const node of nodes) {- let weight = inheritedWeight;- let usesNumericAttention = inheritedNumericAttention;-- if ((node.type === 'word' || node.type === 'group') && node.attention !== undefined) {- weight *= parseAttention(node.attention);- usesNumericAttention = typeof node.attention === 'number';- }-- if (node.type === 'group') {- leaves.push(...flattenNodes(node.children, weight, node.range, usesNumericAttention));+ if (node.type !== 'group' || !overlaps(selection, node.range)) {continue;}-- if (node.type === 'prompt_function') {+ const first = node.children[0];+ const last = node.children.at(-1);+ if (!first || !last) {continue;}-- leaves.push({- hasExplicitAttention: node.type === 'word' && node.attention !== undefined,- isSelected: false,- parentRange,- range: node.range,- text: node.type === 'word' ? node.text : node.value,- type: node.type,- usesNumericAttention,- weight,- });- }-- return leaves;-};--const selectLeaves = (leaves: WeightedLeaf[], selectionStart: number, selectionEnd: number): WeightedLeaf[] => {- const selected = leaves.filter((leaf) => {- if (!rangesOverlap(selectionStart, selectionEnd, leaf.range)) {- return false;+ if (+ selection.start >= node.range.start &&+ selection.end <= node.range.end &&+ (selection.start === selection.end+ ? selection.end < first.range.start || selection.start > last.range.end+ : selection.end <= first.range.start || selection.start >= last.range.end)+ ) {+ return { start: first.range.start, end: last.range.end };}-- if (!leaf.parentRange) {- return true;+ const childSelection = resolveSelection(node.children, selection);+ if (childSelection !== selection) {+ return childSelection;}-- const parentContainsSelection = leaf.parentRange.start <= selectionStart && leaf.parentRange.end >= selectionEnd;- const selectionCoversParent = selectionStart <= leaf.parentRange.start && selectionEnd >= leaf.parentRange.end;-- return parentContainsSelection || selectionCoversParent || !leaf.hasExplicitAttention;- });-- if (selectionStart !== selectionEnd || selected.length < 2) {- return selected;}-- const contentLeaves = selected.filter((leaf) => leaf.type === 'word' || leaf.type === 'embedding');-- return contentLeaves.length > 0 ? contentLeaves : selected;+ return selection;};-const findSelectedGroup = (- nodes: PromptAstNode[],- selectionStart: number,- selectionEnd: number-): Extract<PromptAstNode, { type: 'group' }> | null => {+const flattenNodes = (nodes: PromptAstNode[], leaves: WeightedLeaf[], weight = NEUTRAL): void => {for (const node of nodes) {- if (node.type !== 'group') {- continue;- }-- const childGroup = findSelectedGroup(node.children, selectionStart, selectionEnd);-- if (childGroup) {- return childGroup;- }-- if (rangesOverlap(selectionStart, selectionEnd, node.range)) {- return node;- }- }-- return null;-};--const applyWeightStep = (leaves: WeightedLeaf[], direction: PromptAttentionDirection): void => {- for (const leaf of leaves) {- if (leaf.usesNumericAttention) {- leaf.weight = roundWeight(leaf.weight + (direction === 'increment' ? NUMERIC_STEP : -NUMERIC_STEP));+ const inherited = node.type === 'group' || node.type === 'word' ? inheritWeight(weight, node.attention) : weight;+ if (node.type === 'group') {+ flattenNodes(node.children, leaves, inherited);} else {- leaf.weight = roundWeight(leaf.weight * (direction === 'increment' ? ATTENTION_FACTOR : 1 / ATTENTION_FACTOR));+ const previous = leaves.at(-1);+ // Compel separates fragments at parentheses even without literal whitespace.+ // Keep that word boundary when the delimiters disappear during regrouping.+ if (previous?.node.type === 'word' && node.type === 'word' && previous.node.range.end < node.range.start) {+ leaves.push({+ node: { type: 'whitespace', value: ' ', range: { start: previous.node.range.end, end: node.range.start } },+ weight: NEUTRAL,+ selected: false,+ });+ }+ leaves.push({ node, weight: inherited, selected: false });}}};-const createLeafNode = (leaf: WeightedLeaf): PromptAstNode => {- const isSelection = leaf.isSelected || undefined;-- switch (leaf.type) {- case 'word':- return { type: 'word', text: leaf.text, range: leaf.range, isSelection };- case 'whitespace':- return { type: 'whitespace', value: leaf.text, range: leaf.range, isSelection };- case 'punct':- return { type: 'punct', value: leaf.text, range: leaf.range, isSelection };- case 'embedding':- return { type: 'embedding', value: leaf.text, range: leaf.range, isSelection };- case 'escaped_paren':- return { type: 'escaped_paren', value: leaf.text as '(' | ')', range: leaf.range, isSelection };- }-};--const findRunEnd = (leaves: WeightedLeaf[], start: number, predicate: (leaf: WeightedLeaf) => boolean): number => {- let end = start;-- while (end < leaves.length) {- const leaf = leaves[end];-- if (!leaf) {- break;+const selectLeaves = (leaves: WeightedLeaf[], selection: PromptRange): void => {+ if (selection.start !== selection.end) {+ for (const leaf of leaves) {+ leaf.selected = overlaps(selection, leaf.node.range);}-- if (predicate(leaf)) {- end++;+ return;+ }+ // At a token boundary prefer content over punctuation/whitespace, then the token+ // starting at the caret. A collapsed selection must never edit both neighbours.+ let best: WeightedLeaf | undefined;+ let bestRank = -1;+ for (const leaf of leaves) {+ if (!overlaps(selection, leaf.node.range)) {continue;}-- if (leaf.type !== 'whitespace') {- break;+ const content = leaf.node.type === 'word' || leaf.node.type === 'embedding' || leaf.node.type === 'prompt_function';+ const rank = (content ? 2 : 0) + (leaf.node.range.start === selection.start ? 1 : 0);+ if (rank > bestRank) {+ best = leaf;+ bestRank = rank;}-- let nextContent = end + 1;-- while (leaves[nextContent]?.type === 'whitespace') {- nextContent++;- }-- if (!leaves[nextContent] || !predicate(leaves[nextContent])) {- break;- }-- end = nextContent;}-- return end;-};--const trimWhitespaceRun = (leaves: WeightedLeaf[], start: number, end: number): PromptRange => {- let trimmedStart = start;- let trimmedEnd = end;-- while (trimmedStart < trimmedEnd && leaves[trimmedStart]?.type === 'whitespace') {- trimmedStart++;+ if (best) {+ best.selected = true;}-- while (trimmedEnd > trimmedStart && leaves[trimmedEnd - 1]?.type === 'whitespace') {- trimmedEnd--;- }-- return { start: trimmedStart, end: trimmedEnd };};-const pushLeaves = (nodes: PromptAstNode[], leaves: WeightedLeaf[], start: number, end: number): void => {- for (let index = start; index < end; index++) {- const leaf = leaves[index];-- if (leaf) {- nodes.push(createLeafNode(leaf));- }+const stepWeight = (weight: Weight, direction: PromptAttentionDirection, preferNumeric: boolean): Weight => {+ const delta = direction === 'increment' ? 1 : -1;+ if (weight.steps === null || (preferNumeric && !weight.explicit)) {+ return { value: roundWeight(weight.value + delta * 0.1), steps: null, explicit: true };}+ const steps = weight.steps + delta;+ return { value: symbolicValue(steps), steps, explicit: true };};-const selectedAll = (leaves: WeightedLeaf[]): boolean => leaves.length > 0 && leaves.every((leaf) => leaf.isSelected);--const createSymbolicRunNode = (leaves: WeightedLeaf[], sign: '+' | '-'): PromptAstNode | null => {- const factor = sign === '+' ? ATTENTION_FACTOR : 1 / ATTENTION_FACTOR;- const children = groupWeightedLeaves(leaves.map((leaf) => ({ ...leaf, weight: leaf.weight / factor })));+const leafNode = (leaf: WeightedLeaf): PromptAstNode => {+ const isSelection = leaf.selected || undefined;+ return leaf.node.type === 'word'+ ? { ...leaf.node, attention: undefined, isSelection }+ : { ...leaf.node, isSelection };+};- if (children.length === 0) {- return null;+const sameWeight = (a: Weight, b: Weight): boolean => {+ if (a.steps !== null && b.steps !== null) {+ return a.steps === b.steps;}+ return a.value === b.value || roundWeight(a.value) === roundWeight(b.value);+};- const isSelection = selectedAll(leaves) || undefined;-- if (children.length === 1) {- const child = children[0];-- if (child?.type === 'word' || child?.type === 'group') {- return { ...child, attention: addSymbolicAttention(child.attention, sign), isSelection };+/** Equal numeric and symbolic neighbours must merge in either document order. */+const unifyEqualWeights = (leaves: WeightedLeaf[]): void => {+ let start = 0;+ while (start < leaves.length) {+ const first = leaves[start]!;+ if (first.node.type === 'whitespace') {+ start++;+ continue;+ }+ let end = start + 1;+ let numeric = first.weight.steps === null;+ while (end < leaves.length) {+ const leaf = leaves[end]!;+ if (leaf.node.type !== 'whitespace') {+ if (!sameWeight(first.weight, leaf.weight)) {+ break;+ }+ numeric ||= leaf.weight.steps === null;+ }+ end++;+ }+ if (numeric) {+ for (let index = start; index < end; index++) {+ const leaf = leaves[index]!;+ if (leaf.node.type !== 'whitespace') {+ leaf.weight = { ...leaf.weight, steps: null };+ }+ }}+ start = end;}-- return { type: 'group', attention: sign, children, range: GENERATED_RANGE, isSelection };};-const createNumericRunNode = (leaves: WeightedLeaf[], weight: number): PromptAstNode | null => {- const children = groupWeightedLeaves(leaves.map((leaf) => ({ ...leaf, weight: 1 })));-- if (children.length === 0) {- return null;+const wrapRun = (children: PromptAstNode[], attention: PromptAttention, selected: boolean): PromptAstNode => {+ const child = children.length === 1 ? children[0] : undefined;+ if (typeof attention === 'string' && (child?.type === 'word' || child?.type === 'group')) {+ return { ...child, attention, isSelection: selected || undefined };}-- return {- type: 'group',- attention: roundWeight(weight),- children,- range: GENERATED_RANGE,- isSelection: selectedAll(leaves) || undefined,- };+ return { type: 'group', attention, children, range: GENERATED_RANGE, isSelection: selected || undefined };};const groupWeightedLeaves = (leaves: WeightedLeaf[]): PromptAstNode[] => {const nodes: PromptAstNode[] = [];let index = 0;-while (index < leaves.length) {- const leaf = leaves[index];-- if (!leaf) {- break;- }-- const stepCount = getSymbolicStepCount(leaf.weight);-- if (stepCount !== null && stepCount !== 0 && !leaf.usesNumericAttention) {- const isPositive = stepCount > 0;- const sign = isPositive ? '+' : '-';- const runEnd = findRunEnd(leaves, index, (candidate) => {- if (candidate.usesNumericAttention) {- return false;- }-- const candidateSteps = getSymbolicStepCount(candidate.weight);-- return candidateSteps !== null && (isPositive ? candidateSteps > 0 : candidateSteps < 0);- });- const trimmed = trimWhitespaceRun(leaves, index, runEnd);-- pushLeaves(nodes, leaves, index, trimmed.start);-- const runNode = createSymbolicRunNode(leaves.slice(trimmed.start, trimmed.end), sign);-- if (runNode) {- nodes.push(runNode);- }-- pushLeaves(nodes, leaves, trimmed.end, runEnd);- index = runEnd;- continue;- }-- if (isNeutralWeight(leaf.weight)) {- nodes.push(createLeafNode(leaf));+ const first = leaves[index]!;+ if (first.node.type === 'whitespace' || first.weight.value === 1) {+ nodes.push(leafNode(first));index++;continue;}-- const runWeight = leaf.weight;- const runEnd = findRunEnd(leaves, index, (candidate) => Math.abs(candidate.weight - runWeight) < WEIGHT_EPSILON);- const trimmed = trimWhitespaceRun(leaves, index, runEnd);-- pushLeaves(nodes, leaves, index, trimmed.start);-- const runNode = createNumericRunNode(leaves.slice(trimmed.start, trimmed.end), runWeight);-- if (runNode) {- nodes.push(runNode);+ const symbolic = first.weight.steps !== null;+ const sign = Math.sign(first.weight.steps ?? 0);+ let commonSteps = first.weight.steps ?? 0;+ let end = index + 1;+ let contentEnd = end;+ while (end < leaves.length) {+ const leaf = leaves[end]!;+ if (leaf.node.type !== 'whitespace') {+ if (+ symbolic+ ? leaf.weight.steps === null || Math.sign(leaf.weight.steps) !== sign+ : !sameWeight(first.weight, leaf.weight)+ ) {+ break;+ }+ if (symbolic) {+ commonSteps = sign * Math.min(Math.abs(commonSteps), Math.abs(leaf.weight.steps!));+ }+ contentEnd = end + 1;+ }+ end++;}-- pushLeaves(nodes, leaves, trimmed.end, runEnd);- index = runEnd;+ const run = leaves.slice(index, contentEnd);+ const children = symbolic+ ? groupWeightedLeaves(+ run.map((leaf) => {+ const steps = leaf.node.type === 'whitespace' ? 0 : leaf.weight.steps! - commonSteps;+ return { ...leaf, weight: { ...leaf.weight, steps, value: symbolicValue(steps) } };+ })+ )+ : run.map(leafNode);+ const attention = symbolic ? (sign > 0 ? '+' : '-').repeat(Math.abs(commonSteps)) : first.weight.value;+ nodes.push(+ wrapRun(+ children,+ attention,+ run.every((leaf) => leaf.selected)+ )+ );+ index = contentEnd;}-return nodes;};const adjustNodes = (nodes: PromptAstNode[],- selectionStart: number,- selectionEnd: number,+ selection: PromptRange,direction: PromptAttentionDirection,- preferNumericAttentionStyle: boolean+ preferNumeric: boolean,+ inherited = NEUTRAL): { nodes: PromptAstNode[]; modified: boolean } => {- const leaves = flattenNodes(nodes);- let selectedLeaves = selectLeaves(leaves, selectionStart, selectionEnd);-- if (selectedLeaves.length === 0) {- const group = findSelectedGroup(nodes, selectionStart, selectionEnd);-- if (group) {- selectedLeaves = leaves.filter(- (leaf) => leaf.range.start >= group.range.start && leaf.range.end <= group.range.end- );- }- }-- if (selectedLeaves.length === 0) {- return { nodes, modified: false };- }-- for (const leaf of selectedLeaves) {- leaf.isSelected = true;-- if (preferNumericAttentionStyle && !leaf.hasExplicitAttention) {- leaf.usesNumericAttention = true;- }- }-- applyWeightStep(selectedLeaves, direction);-- return { nodes: groupWeightedLeaves(leaves), modified: true };-};--const adjustPromptFunction = (- node: PromptFunctionNode,- selectionStart: number,- selectionEnd: number,- direction: PromptAttentionDirection,- preferNumericAttentionStyle: boolean-): { node: PromptFunctionNode; modified: boolean } => {+ const target = resolveSelection(nodes, selection);+ const leaves: WeightedLeaf[] = [];+ flattenNodes(nodes, leaves);+ selectLeaves(leaves, target);let modified = false;- const promptArgs: PromptFunctionArg[] = node.promptArgs.map((arg) => {- const clipped = clipRange(selectionStart, selectionEnd, arg.contentRange);-- if (!clipped) {- return arg;+ for (const leaf of leaves) {+ if (!Number.isFinite(leaf.weight.value)) {+ throw new TypeError('Non-finite prompt attention');}-- const result = adjustNodes(arg.nodes, clipped.start, clipped.end, direction, preferNumericAttentionStyle);-- if (!result.modified) {- return arg;+ if (!leaf.selected) {+ continue;}-- modified = true;- return { ...arg, nodes: result.nodes };- });-- return modified ? { node: { ...node, promptArgs }, modified: true } : { node, modified: false };-};--const adjustPromptAttentionUnchecked = (- prompt: string,- selectionStart: number,- selectionEnd: number,- direction: PromptAttentionDirection,- preferNumericAttentionStyle = false-): PromptAttentionAdjustment => {- const nodes = parsePrompt(prompt);- const nextNodes: PromptAstNode[] = [];- let modified = false;-- for (const region of extractRegions(nodes)) {- if (region.type === 'normal') {- const clipped = clipRange(selectionStart, selectionEnd, region.range);-- if (!clipped) {- nextNodes.push(...region.nodes);- continue;- }-- const result = adjustNodes(region.nodes, clipped.start, clipped.end, direction, preferNumericAttentionStyle);- modified = modified || result.modified;- nextNodes.push(...result.nodes);+ if (leaf.node.type === 'prompt_function') {+ const context = combineWeights(inherited, leaf.weight);+ let functionModified = false;+ const promptArgs = leaf.node.promptArgs.map((arg) => {+ if (!overlaps(target, arg.contentRange)) {+ return arg;+ }+ const result = adjustNodes(arg.nodes, target, direction, preferNumeric, context);+ functionModified ||= result.modified;+ return result.modified ? { ...arg, nodes: result.nodes } : arg;+ });+ leaf.node = functionModified ? { ...leaf.node, promptArgs } : leaf.node;+ leaf.selected = false;+ modified ||= functionModified;continue;}-- const clipped = clipRange(selectionStart, selectionEnd, region.node.range);-- if (!clipped) {- nextNodes.push(region.node);+ if (leaf.node.type === 'whitespace') {continue;}-- const result = adjustPromptFunction(- region.node,- clipped.start,- clipped.end,- direction,- preferNumericAttentionStyle- );- modified = modified || result.modified;- nextNodes.push(result.node);+ if (inherited.value === 0) {+ leaf.selected = false;+ continue;+ }+ const stepped = stepWeight(combineWeights(inherited, leaf.weight), direction, preferNumeric);+ const relativeSteps = stepped.steps !== null && inherited.steps !== null ? stepped.steps - inherited.steps : null;+ const canUseSymbolic =+ relativeSteps !== null &&+ (relativeSteps === 0 || inherited.steps === 0 || Math.sign(relativeSteps) === Math.sign(inherited.steps!));+ leaf.weight = {+ value: canUseSymbolic ? symbolicValue(relativeSteps) : roundWeight(stepped.value / inherited.value),+ steps: canUseSymbolic ? relativeSteps : null,+ explicit: true,+ };+ if (!Number.isFinite(leaf.weight.value)) {+ throw new TypeError('Non-finite prompt attention');+ }+ modified = true;}-- return modified ? serializePromptWithSelection(nextNodes) : { prompt, selectionStart, selectionEnd };+ if (!modified) {+ return { nodes, modified: false };+ }+ unifyEqualWeights(leaves);+ return { nodes: groupWeightedLeaves(leaves), modified: true };};export const adjustPromptAttention = (@@ -545,9 +333,16 @@ export const adjustPromptAttention = (direction: PromptAttentionDirection,preferNumericAttentionStyle = false): PromptAttentionAdjustment => {+ const unchanged = { prompt, selectionStart, selectionEnd };try {- return adjustPromptAttentionUnchecked(prompt, selectionStart, selectionEnd, direction, preferNumericAttentionStyle);+ const selection = {+ start: Math.max(0, Math.min(prompt.length, selectionStart, selectionEnd)),+ end: Math.min(prompt.length, Math.max(0, selectionStart, selectionEnd)),+ };+ const result = adjustNodes(parsePrompt(prompt), selection, direction, preferNumericAttentionStyle);+ return result.modified ? serializePromptWithSelection(result.nodes, prompt) : unchanged;} catch {- return { prompt, selectionStart, selectionEnd };+ // Prompts are edited while incomplete, and pathological nesting must not break typing.+ return unchanged;}};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsxindex e7c9acdbf1..041dbc20d1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx@@ -160,7 +160,7 @@ describe('ResizableTextarea', () => {it('participates in the shared Ctrl+Up/Down prompt-attention system', async () => {const PromptHarness = () => {- const [value, setValue] = useState('hello world');+ const [value, setValue] = useState('(hello world+)++');const handleChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) => {setValue(event.currentTarget.value);}, []);@@ -194,13 +194,26 @@ describe('ResizableTextarea', () => {const textarea = host.querySelector<HTMLTextAreaElement>('textarea')!;textarea.focus();- textarea.setSelectionRange(0, 5);+ textarea.setSelectionRange(1, 6, 'backward');await act(() => {expect(adjustFocusedPromptAttention('increment', false)).toBe(true);});- await expect.poll(() => textarea.value).toBe('hello+ world');+ await expect.poll(() => textarea.value).toBe('(hello world)+++');+ expect(textarea.value.slice(textarea.selectionStart, textarea.selectionEnd)).toBe('hello');+ expect(textarea.selectionDirection).toBe('backward');++ await act(() => {+ expect(adjustFocusedPromptAttention('decrement', false)).toBe(true);+ });+ await expect.poll(() => textarea.value).toBe('(hello world+)++');+ expect(textarea.value.slice(textarea.selectionStart, textarea.selectionEnd)).toBe('hello');++ await act(async () => {+ await userEvent.keyboard('{Control>}z{/Control}');+ });+ await expect.poll(() => textarea.value).toBe('(hello world)+++');});// Regression: the write goes through the native value setter and a syntheticdiff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.tsindex 366572f3ab..1a18f8ae08 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptAttentionHotkeys.ts@@ -50,6 +50,7 @@ export const adjustFocusedPromptAttention = (return false;}+ const selectionDirection = textarea.selectionDirection;const result = adjustPromptAttention(textarea.value,textarea.selectionStart,@@ -63,7 +64,7 @@ export const adjustFocusedPromptAttention = (}replaceTextareaValue(textarea, result.prompt);- textarea.setSelectionRange(result.selectionStart, result.selectionEnd);+ textarea.setSelectionRange(result.selectionStart, result.selectionEnd, selectionDirection);return true;};