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(webv2): add prompt AST, keybind weighting and experimental syntax highlighting.
joshistoast70b921f1b370
diff --git a/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsx b/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsxindex 9d1dc621f8..a154d2db2f 100644--- a/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsx+++ b/invokeai/frontend/webv2/src/workbench/components/ui/ResizableTextarea.tsx@@ -3,6 +3,7 @@ import type {KeyboardEvent as ReactKeyboardEvent,PointerEvent as ReactPointerEvent,Ref,+ ReactNode,} from 'react';import { Box, Textarea } from '@chakra-ui/react';@@ -26,6 +27,7 @@ export interface ResizableTextareaProps extends Omit<largeStepPx?: number;stepPx?: number;textareaRef?: Ref<HTMLTextAreaElement>;+ underlay?: ReactNode;onResizeEnd?: (heightPx: number) => void;}@@ -38,6 +40,7 @@ export const ResizableTextarea = ({resizeHandleAriaLabel,stepPx = DEFAULT_STEP_PX,textareaRef,+ underlay,...textareaProps}: ResizableTextareaProps) => {const initialHeightPx = clamp(defaultHeightPx, minHeightPx, maxHeightPx);@@ -97,7 +100,15 @@ export const ResizableTextarea = ({return (<Box position="relative">- <Textarea ref={textareaRef} h={`${displayHeightPx}px`} resize="none" {...textareaProps} />+ {underlay}+ <Textarea+ ref={textareaRef}+ h={`${displayHeightPx}px`}+ position={underlay ? 'relative' : textareaProps.position}+ resize="none"+ zIndex={underlay ? 1 : textareaProps.zIndex}+ {...textareaProps}+ /><Boxaria-label={resizeHandleAriaLabel}aria-orientation="horizontal"@@ -113,6 +124,7 @@ export const ResizableTextarea = ({role="separator"tabIndex={0}transition="background var(--wb-motion-duration-fast) ease, opacity var(--wb-motion-duration-fast) ease"+ zIndex={2}_after={{bg: 'border.emphasized',borderRadius: 'full',diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.test.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.test.tsnew file mode 100644index 0000000000..02be42e8cb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest';++import { parsePrompt, serializePrompt, tokenizePrompt } from './ast';++describe('prompt AST', () => {+ const roundTrip = (prompt: string): string => serializePrompt(parsePrompt(prompt));++ it('tokenizes symbolic weights without treating hyphenated words as attention', () => {+ expect(tokenizePrompt('cat+').map((token) => token.type)).toEqual(['word', 'weight']);+ expect(tokenizePrompt('razor-sharp').map((token) => token.type)).toEqual(['word', 'punct', 'word']);+ });++ it('parses prompt function argument ranges', () => {+ const node = parsePrompt("('one two', 'three four').and()")[0];++ expect(node?.type).toBe('prompt_function');++ if (node?.type !== 'prompt_function') {+ return;+ }++ expect(node.promptArgs).toHaveLength(2);+ expect(node.promptArgs[0]?.contentRange).toEqual({ start: 2, end: 9 });+ expect(node.promptArgs[1]?.contentRange).toEqual({ start: 13, end: 23 });+ });++ it.each([+ 'a cat',+ '(a cat)',+ '(a cat)1.2',+ 'cat+',+ 'cat++',+ 'cat-',+ '(hello world)+',+ '\\(medium\\)',+ 'colored pencil \\(medium\\) (enhanced)',+ '<embedding_name>',+ 'portrait \\(realistic\\) (high quality)1.2',+ "('one two', 'three four').and()",+ "('one', 'two three. four.').or()",+ "('one', 'two').blend(0.7, 0.3)",+ "('hello+', '(world)-').and()",+ "some text, ('a', 'b').and(), more text",+ "('a', 'b', 'c').blend(0.5, 0.3, 0.2)",+ '(one two, three four).and()',+ '(one two, three four).blend(0.7, 0.3)',+ '(a, b, c).blend(0.5, 0.3, 0.2)',+ 'some text, (a, b).and(), more text',+ '(\u201cone\u201d, \u201ctwo\u201d).and()',+ '(\u2018one\u2019, \u2018two\u2019).or()',+ "('one',\n 'two',\n 'three').and()",+ 'A bear \\(with razor-sharp teeth\\) in a forest.',+ ])('round-trips %s', (prompt) => {+ expect(roundTrip(prompt)).toBe(prompt);+ });++ it('normalizes whitespace between prompt function args and method names', () => {+ expect(roundTrip("('one', 'two')\n.and()")).toBe("('one', 'two').and()");+ expect(roundTrip('(one, two)\n.and()')).toBe('(one, two).and()');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.tsnew file mode 100644index 0000000000..791214af28--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/ast.ts@@ -0,0 +1,792 @@+export type PromptAttention = string | number;++export interface PromptRange {+ start: number;+ end: number;+}++export type PromptToken =+ | { type: 'word'; value: string; range: PromptRange }+ | { type: 'whitespace'; value: string; range: PromptRange }+ | { type: 'punct'; value: string; range: PromptRange }+ | { type: 'lparen'; range: PromptRange }+ | { type: 'rparen'; range: PromptRange }+ | { type: 'weight'; value: PromptAttention; range: PromptRange }+ | { type: 'lembed'; range: PromptRange }+ | { type: 'rembed'; range: PromptRange }+ | { type: 'escaped_paren'; value: '(' | ')'; range: PromptRange };++export interface PromptFunctionArg {+ nodes: PromptAstNode[];+ quote: string;+ contentRange: PromptRange;+ separator?: string;+}++export type PromptAstNode =+ | { type: 'word'; text: string; attention?: PromptAttention; range: PromptRange; isSelection?: boolean }+ | { type: 'group'; children: PromptAstNode[]; attention?: PromptAttention; range: PromptRange; isSelection?: boolean }+ | { type: 'embedding'; value: string; range: PromptRange; isSelection?: boolean }+ | { type: 'whitespace'; value: string; range: PromptRange; isSelection?: boolean }+ | { type: 'punct'; value: string; range: PromptRange; isSelection?: boolean }+ | { type: 'escaped_paren'; value: '(' | ')'; range: PromptRange; isSelection?: boolean }+ | {+ type: 'prompt_function';+ name: string;+ promptArgs: PromptFunctionArg[];+ functionParams: string;+ range: PromptRange;+ isSelection?: boolean;+ };++const WORD_CHAR = /[A-Za-z0-9_]/;+const WHITESPACE = /\s/;+const NUMERIC_WEIGHT = /^[+-]?\d+(?:\.\d+)?/;+const SYMBOLIC_WEIGHT = /^[+-]+/;+const PUNCTUATION = new Set([+ '.',+ ',',+ '/',+ '!',+ '?',+ ';',+ ':',+ "'",+ '"',+ '\u2018',+ '\u2019',+ '\u201c',+ '\u201d',+ '`',+ '~',+ '@',+ '#',+ '$',+ '%',+ '^',+ '&',+ '*',+ '=',+ '_',+ '|',+ '+',+ '-',+]);++const OPEN_QUOTES = new Set(["'", '"', '\u2018', '\u201c']);+const CLOSE_QUOTE_BY_OPEN: Record<string, string> = {+ "'": "'",+ '"': '"',+ '\u2018': '\u2019',+ '\u201c': '\u201d',+};++const range = (start: number, end: number): PromptRange => ({ start, end });++const isWordChar = (char: string | undefined): boolean => Boolean(char && WORD_CHAR.test(char));++const attentionValue = (raw: string): PromptAttention => {+ const numeric = Number(raw);++ return Number.isNaN(numeric) ? raw : numeric;+};++const readWhitespace = (prompt: string, start: number): PromptToken => {+ let end = start + 1;++ while (end < prompt.length && WHITESPACE.test(prompt[end] ?? '')) {+ end++;+ }++ return { type: 'whitespace', value: prompt.slice(start, end), range: range(start, end) };+};++const readSymbolicAttention = (prompt: string, start: number): { value: string; end: number } | null => {+ const match = prompt.slice(start).match(SYMBOLIC_WEIGHT)?.[0];++ if (!match) {+ return null;+ }++ const end = start + match.length;++ if (isWordChar(prompt[end])) {+ return null;+ }++ return { value: match, end };+};++const readNumericAttention = (prompt: string, start: number): { value: number; end: number } | null => {+ const match = prompt.slice(start).match(NUMERIC_WEIGHT)?.[0];++ if (!match) {+ return null;+ }++ const end = start + match.length;++ if (prompt[end] === '.' || isWordChar(prompt[end])) {+ return null;+ }++ return { value: Number(match), end };+};++const readWord = (prompt: string, start: number): { token: PromptToken; extraToken?: PromptToken; end: number } => {+ let end = start + 1;++ while (end < prompt.length && isWordChar(prompt[end])) {+ end++;+ }++ const token: PromptToken = { type: 'word', value: prompt.slice(start, end), range: range(start, end) };+ const symbolic = readSymbolicAttention(prompt, end);++ if (!symbolic) {+ return { token, end };+ }++ return {+ token,+ extraToken: { type: 'weight', value: symbolic.value, range: range(end, symbolic.end) },+ end: symbolic.end,+ };+};++export const tokenizePrompt = (prompt: string): PromptToken[] => {+ const tokens: PromptToken[] = [];+ let index = 0;++ while (index < prompt.length) {+ const char = prompt[index] ?? '';++ if (WHITESPACE.test(char)) {+ const token = readWhitespace(prompt, index);+ tokens.push(token);+ index = token.range.end;+ continue;+ }++ if (char === '\\' && (prompt[index + 1] === '(' || prompt[index + 1] === ')')) {+ tokens.push({ type: 'escaped_paren', value: prompt[index + 1] as '(' | ')', range: range(index, index + 2) });+ index += 2;+ continue;+ }++ if (char === '(') {+ tokens.push({ type: 'lparen', range: range(index, index + 1) });+ index++;+ continue;+ }++ if (char === ')') {+ tokens.push({ type: 'rparen', range: range(index, index + 1) });++ const numeric = readNumericAttention(prompt, index + 1);+ const symbolic = numeric ? null : readSymbolicAttention(prompt, index + 1);+ const weight = numeric ?? symbolic;++ if (weight) {+ tokens.push({ type: 'weight', value: weight.value, range: range(index + 1, weight.end) });+ index = weight.end;+ } else {+ index++;+ }+ continue;+ }++ if (char === '<') {+ tokens.push({ type: 'lembed', range: range(index, index + 1) });+ index++;+ continue;+ }++ if (char === '>') {+ tokens.push({ type: 'rembed', range: range(index, index + 1) });+ index++;+ continue;+ }++ if (isWordChar(char)) {+ const result = readWord(prompt, index);+ tokens.push(result.token);++ if (result.extraToken) {+ tokens.push(result.extraToken);+ }++ index = result.end;+ 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) });+ index++;+ }++ return tokens;+};++const tokenValue = (token: PromptToken | undefined): string | undefined => {+ if (!token || !('value' in token)) {+ return undefined;+ }++ return String(token.value);+};++const tokenSource = (token: PromptToken): string => {+ switch (token.type) {+ case 'lparen':+ return '(';+ case 'rparen':+ return ')';+ case 'lembed':+ return '<';+ case 'rembed':+ return '>';+ case 'escaped_paren':+ return `\\${token.value}`;+ case 'weight':+ return String(token.value);+ default:+ return token.value;+ }+};++class PromptParser {+ private index = 0;++ constructor(private readonly tokens: PromptToken[]) {}++ parse(): PromptAstNode[] {+ return this.parseNodes();+ }++ private peek(offset = 0): PromptToken | undefined {+ return this.tokens[this.index + offset];+ }++ private consume(): PromptToken {+ const token = this.tokens[this.index];++ if (!token) {+ throw new Error('Unexpected end of prompt tokens');+ }++ this.index++;+ return token;+ }++ private isPunct(offset: number, value: string): boolean {+ return this.peek(offset)?.type === 'punct' && tokenValue(this.peek(offset)) === value;+ }++ private quotedPromptFunctionAhead(): boolean {+ let offset = 0;++ while (this.peek(offset)?.type === 'whitespace') {+ offset++;+ }++ const token = this.peek(offset);++ return token?.type === 'punct' && OPEN_QUOTES.has(tokenValue(token) ?? '');+ }++ private unquotedPromptFunctionAhead(): boolean {+ let offset = 0;+ let depth = 0;+ let hasComma = false;++ while (this.peek(offset)) {+ const token = this.peek(offset);++ if (token?.type === 'lparen') {+ 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'+ );+ }++ depth--;+ } else if (depth === 0 && token?.type === 'punct' && tokenValue(token) === ',') {+ hasComma = true;+ }++ offset++;+ }++ return false;+ }++ private parseMethodTail(savedIndex: number): { name: string; params: string; end: number } | null {+ while (this.peek()?.type === 'whitespace') {+ this.consume();+ }++ if (!this.isPunct(0, '.') || this.peek(1)?.type !== 'word' || this.peek(2)?.type !== 'lparen') {+ this.index = savedIndex;+ return null;+ }++ this.consume();+ const name = tokenValue(this.consume()) ?? '';+ this.consume();++ let depth = 0;+ let params = '';++ while (this.peek()) {+ const token = this.peek();++ if (token?.type === 'rparen' && depth === 0) {+ break;+ }++ const consumed = this.consume();++ if (consumed.type === 'lparen') {+ depth++;+ } else if (consumed.type === 'rparen') {+ depth--;+ }++ params += tokenSource(consumed);+ }++ if (this.peek()?.type !== 'rparen') {+ this.index = savedIndex;+ return null;+ }++ const close = this.consume();++ return { name, params, end: close.range.end };+ }++ private parseQuotedPromptFunction(+ lparen: PromptToken & { type: 'lparen' },+ savedIndex: number+ ): PromptAstNode | null {+ const args: PromptFunctionArg[] = [];+ let expectedOpenQuote: string | null = null;+ let pendingSeparator: string | undefined;++ while (this.peek()) {+ while (this.peek()?.type === 'whitespace') {+ this.consume();+ }++ if (this.peek()?.type === 'rparen') {+ break;+ }++ if (args.length > 0) {+ if (!this.isPunct(0, ',')) {+ this.index = savedIndex;+ return null;+ }++ this.consume();+ pendingSeparator = this.consumeWhitespaceValue();+ }++ const openQuote = this.peek();+ const quote = tokenValue(openQuote);++ if (openQuote?.type !== 'punct' || !quote || !OPEN_QUOTES.has(quote)) {+ this.index = savedIndex;+ return null;+ }++ if (expectedOpenQuote === null) {+ expectedOpenQuote = quote;+ } else if (quote !== expectedOpenQuote) {+ this.index = savedIndex;+ return null;+ }++ this.consume();++ const closeQuote = CLOSE_QUOTE_BY_OPEN[quote] ?? quote;+ const contentStart = openQuote.range.end;+ const argTokens: PromptToken[] = [];+ let contentEnd = contentStart;++ while (this.peek() && !(this.peek()?.type === 'punct' && tokenValue(this.peek()) === closeQuote)) {+ const token = this.consume();+ argTokens.push(token);+ contentEnd = token.range.end;+ }++ if (!(this.peek()?.type === 'punct' && tokenValue(this.peek()) === closeQuote)) {+ this.index = savedIndex;+ return null;+ }++ this.consume();+ args.push({+ contentRange: range(contentStart, contentEnd),+ nodes: parsePromptTokens(argTokens),+ quote,+ separator: pendingSeparator,+ });+ pendingSeparator = undefined;+ }++ if (args.length === 0 || this.peek()?.type !== 'rparen') {+ this.index = savedIndex;+ return null;+ }++ this.consume();++ const tail = this.parseMethodTail(savedIndex);++ if (!tail) {+ return null;+ }++ return {+ type: 'prompt_function',+ name: tail.name,+ promptArgs: args,+ functionParams: tail.params,+ range: range(lparen.range.start, tail.end),+ };+ }++ private parseUnquotedPromptFunction(+ lparen: PromptToken & { type: 'lparen' },+ savedIndex: number+ ): PromptAstNode | null {+ const args: PromptFunctionArg[] = [];+ let pendingSeparator: string | undefined;++ while (this.peek()) {+ if (this.peek()?.type === 'rparen') {+ break;+ }++ if (args.length > 0) {+ if (!this.isPunct(0, ',')) {+ this.index = savedIndex;+ return null;+ }++ this.consume();+ pendingSeparator = this.consumeWhitespaceValue();+ }++ const argTokens = this.consumeUnquotedArgTokens();++ if (argTokens.length === 0) {+ this.index = savedIndex;+ return null;+ }++ const trimmedTokens = trimWhitespaceTokens(argTokens);+ const first = trimmedTokens[0];+ const last = trimmedTokens.at(-1);++ if (!first || !last) {+ this.index = savedIndex;+ return null;+ }++ args.push({+ contentRange: range(first.range.start, last.range.end),+ nodes: parsePromptTokens(trimmedTokens),+ quote: '',+ separator: pendingSeparator,+ });+ pendingSeparator = undefined;+ }++ if (args.length < 2 || this.peek()?.type !== 'rparen') {+ this.index = savedIndex;+ return null;+ }++ this.consume();++ const tail = this.parseMethodTail(savedIndex);++ if (!tail) {+ return null;+ }++ return {+ type: 'prompt_function',+ name: tail.name,+ promptArgs: args,+ functionParams: tail.params,+ range: range(lparen.range.start, tail.end),+ };+ }++ private consumeWhitespaceValue(): string {+ let value = '';++ while (this.peek()?.type === 'whitespace') {+ value += tokenValue(this.consume()) ?? '';+ }++ return value;+ }++ private consumeUnquotedArgTokens(): PromptToken[] {+ const tokens: PromptToken[] = [];+ let depth = 0;++ while (this.peek()) {+ const token = this.peek();++ if (token?.type === 'lparen') {+ depth++;+ } else if (token?.type === 'rparen') {+ if (depth === 0) {+ break;+ }++ depth--;+ } else if (depth === 0 && token?.type === 'punct' && tokenValue(token) === ',') {+ break;+ }++ tokens.push(this.consume());+ }++ return tokens;+ }++ private parseNodes(): PromptAstNode[] {+ const nodes: PromptAstNode[] = [];++ while (this.peek() && this.peek()?.type !== 'rparen') {+ const token = this.consume();++ switch (token.type) {+ case 'whitespace':+ nodes.push({ type: 'whitespace', value: token.value, range: token.range });+ break;+ case 'lparen': {+ const lparen = token;+ const savedIndex = this.index;+ const promptFunction = this.parsePromptFunctionIfPresent(lparen, savedIndex);++ if (promptFunction) {+ nodes.push(promptFunction);+ break;+ }++ const children = this.parseNodes();+ let nodeEnd = lparen.range.end;+ let attention: PromptAttention | undefined;++ if (this.peek()?.type === 'rparen') {+ const rparen = this.consume();+ nodeEnd = rparen.range.end;++ if (this.peek()?.type === 'weight') {+ const weight = this.consume() as PromptToken & { type: 'weight' };+ attention = weight.value;+ nodeEnd = weight.range.end;+ }+ } else if (children.length > 0) {+ nodeEnd = children.at(-1)?.range.end ?? nodeEnd;+ }++ nodes.push({ type: 'group', attention, children, range: range(lparen.range.start, nodeEnd) });+ break;+ }+ case 'lembed': {+ let value = '';+ let nodeEnd = token.range.end;++ while (this.peek() && this.peek()?.type !== 'rembed') {+ const embedToken = this.consume();+ value += tokenSource(embedToken);+ nodeEnd = embedToken.range.end;+ }++ if (this.peek()?.type === 'rembed') {+ nodeEnd = this.consume().range.end;+ }++ nodes.push({ type: 'embedding', value: value.trim(), range: range(token.range.start, nodeEnd) });+ break;+ }+ case 'word': {+ let nodeEnd = token.range.end;+ let attention: PromptAttention | undefined;++ if (this.peek()?.type === 'weight') {+ const weight = this.consume() as PromptToken & { type: 'weight' };+ attention = attentionValue(String(weight.value));+ nodeEnd = weight.range.end;+ }++ nodes.push({ type: 'word', text: token.value, attention, range: range(token.range.start, nodeEnd) });+ break;+ }+ case 'punct':+ nodes.push({ type: 'punct', value: token.value, range: token.range });+ break;+ case 'escaped_paren':+ nodes.push({ type: 'escaped_paren', value: token.value, range: token.range });+ break;+ default:+ break;+ }+ }++ return nodes;+ }++ private parsePromptFunctionIfPresent(+ lparen: PromptToken & { type: 'lparen' },+ savedIndex: number+ ): PromptAstNode | null {+ if (this.quotedPromptFunctionAhead()) {+ const quoted = this.parseQuotedPromptFunction(lparen, savedIndex);++ if (quoted) {+ return quoted;+ }+ }++ if (this.unquotedPromptFunctionAhead()) {+ const unquoted = this.parseUnquotedPromptFunction(lparen, savedIndex);++ if (unquoted) {+ return unquoted;+ }+ }++ this.index = savedIndex;+ return null;+ }+}++const trimWhitespaceTokens = (tokens: PromptToken[]): PromptToken[] => {+ let start = 0;+ let end = tokens.length;++ while (start < end && tokens[start]?.type === 'whitespace') {+ start++;+ }++ while (end > start && tokens[end - 1]?.type === 'whitespace') {+ end--;+ }++ return tokens.slice(start, end);+};++export const parsePromptTokens = (tokens: PromptToken[]): PromptAstNode[] => new PromptParser(tokens).parse();++export const parsePrompt = (prompt: string): PromptAstNode[] => parsePromptTokens(tokenizePrompt(prompt));++interface SerializeVisitor {+ onNode?: (node: PromptAstNode, start: number, end: number) => void;+}++const appendAttention = (attention: PromptAttention | undefined): string =>+ attention === undefined ? '' : String(attention);++const serializeInto = (nodes: PromptAstNode[], output: { value: string }, visitor?: SerializeVisitor): void => {+ for (const node of nodes) {+ const start = output.value.length;++ switch (node.type) {+ case 'punct':+ case 'whitespace':+ output.value += node.value;+ break;+ case 'escaped_paren':+ output.value += `\\${node.value}`;+ break;+ case 'word':+ output.value += `${node.text}${appendAttention(node.attention)}`;+ break;+ case 'group':+ output.value += '(';+ serializeInto(node.children, output, visitor);+ output.value += `)${appendAttention(node.attention)}`;+ break;+ case 'embedding':+ output.value += `<${node.value}>`;+ break;+ case 'prompt_function':+ output.value += '(';+ node.promptArgs.forEach((arg, index) => {+ if (index > 0) {+ output.value += `,${arg.separator ?? ' '}`;+ }++ output.value += arg.quote;+ serializeInto(arg.nodes, output, visitor);+ output.value += CLOSE_QUOTE_BY_OPEN[arg.quote] ?? arg.quote;+ });+ output.value += `).${node.name}(${node.functionParams})`;+ break;+ }++ visitor?.onNode?.(node, start, output.value.length);+ }+};++export const serializePrompt = (nodes: PromptAstNode[]): string => {+ const output = { value: '' };++ serializeInto(nodes, output);++ return output.value;+};++export const serializePromptWithSelection = (+ nodes: PromptAstNode[]+): { 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;+ }++ selectionStart = Math.min(selectionStart, start);+ selectionEnd = Math.max(selectionEnd, end);+ },+ });++ if (selectionStart === Infinity) {+ return { prompt: output.value, selectionStart: 0, selectionEnd: output.value.length };+ }++ return { prompt: output.value, selectionStart, selectionEnd };+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.test.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.test.tsnew file mode 100644index 0000000000..c24305d802--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from 'vitest';++import type { PromptAttentionDirection } from './attention';++import { adjustPromptAttention } from './attention';++const adjust = (+ prompt: string,+ selected: string | [number, number],+ direction: PromptAttentionDirection,+ preferNumericAttentionStyle = false+) => {+ const range =+ typeof selected === 'string'+ ? ([prompt.indexOf(selected), prompt.indexOf(selected) + selected.length] as [number, number])+ : selected;++ return adjustPromptAttention(prompt, range[0], range[1], direction, preferNumericAttentionStyle);+};++describe('prompt attention adjustment', () => {+ it.each([+ ['hello world', 'hello', 'increment', 'hello+ world'],+ ['hello world', 'hello', 'decrement', 'hello- world'],+ ['hello+ world', 'hello+', 'increment', 'hello++ world'],+ ['hello+ world', 'hello+', 'decrement', 'hello world'],+ ['hello- world', 'hello-', 'decrement', 'hello-- world'],+ ['hello- world', 'hello-', 'increment', 'hello world'],+ ] as const)('adjusts a single word: %s %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected, direction).prompt).toBe(expected);+ });++ it.each([+ ['hello world', [0, 11], 'increment', '(hello world)+'],+ ['hello world', [0, 11], 'decrement', '(hello world)-'],+ ['one, two', [3, 3], 'increment', 'one+, two'],+ ['one, two', [5, 5], 'increment', 'one, two+'],+ ] as const)('adjusts selections and cursor boundaries: %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected as [number, number], direction).prompt).toBe(expected);+ });++ it.each([+ ['(hello world)+', [13, 14], 'increment', '(hello world)++'],+ ['(hello world)+', [0, 14], 'decrement', 'hello world'],+ ['(a b)+', [1, 2], 'increment', '(a+ b)+'],+ ['(a b)+ c', [3, 8], 'increment', '(a b+ c)+'],+ ['(a b)+ c', [3, 8], 'decrement', 'a+ b c-'],+ ] as const)('preserves and splits existing groups: %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected as [number, number], direction).prompt).toBe(expected);+ });++ it('preserves the adjusted selection range', () => {+ const result = adjust('(a b)+', [1, 2], 'increment');++ expect(result.prompt).toBe('(a+ b)+');+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('a+');+ });++ it.each([+ ['(masterpiece)1.3', [0, 16], 'increment', '(masterpiece)1.4'],+ ['(masterpiece)1.3', [0, 16], 'decrement', '(masterpiece)1.2'],+ ['(sunny midday light)1.15', [0, 24], 'increment', '(sunny midday light)1.25'],+ ] as const)('adjusts explicit numeric weights additively: %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected as [number, number], direction).prompt).toBe(expected);+ });++ it('does not corrupt unselected numeric weights', () => {+ const prompt = '(masterpiece)1.3, best quality, (sunny midday light)1.15, clear sky';+ const result = adjust(prompt, 'clear sky', 'increment');++ expect(result.prompt).toContain('(masterpiece)1.3');+ expect(result.prompt).toContain('(sunny midday light)1.15');+ expect(result.prompt).toContain('(clear sky)+');+ expect(result.prompt).not.toMatch(/\d\.\d{5,}/);+ });++ it.each([+ ["('hello world', 'other').and()", 'hello', 'increment', "('hello+ world', 'other').and()"],+ ["('a', 'hello world').or()", 'hello world', 'increment', "('a', '(hello world)+').or()"],+ ["('one two', 'three four').blend(0.7, 0.3)", 'two', 'increment', "('one two+', 'three four').blend(0.7, 0.3)"],+ ['(hello world, foo bar).and()', 'hello', 'increment', '(hello+ world, foo bar).and()'],+ [+ '(\u201chello world\u201d, \u201cother\u201d).and()',+ 'hello',+ 'increment',+ '(\u201chello+ world\u201d, \u201cother\u201d).and()',+ ],+ ] as const)('adjusts inside prompt function args: %s', (prompt, selected, direction, expected) => {+ expect(adjust(prompt, selected, direction).prompt).toBe(expected);+ });++ it('adjusts both prompt function args when a selection spans an argument separator', () => {+ const prompt = "('one two', 'three four').and()";+ const start = prompt.indexOf('two');+ const end = prompt.indexOf('three') + 'three'.length;+ const result = adjustPromptAttention(prompt, start, end, 'increment');++ expect(result.prompt).toBe("('one two+', 'three+ four').and()");+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toContain('two+');+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toContain('three+');+ });++ it('supports project numeric attention style for new weights', () => {+ expect(adjust('hello world', 'hello', 'increment', true).prompt).toBe('(hello)1.1 world');+ expect(adjust('hello world', [0, 11], 'decrement', true).prompt).toBe('(hello world)0.9');+ expect(adjust("('one two', 'three four').and()", 'one', 'increment', true).prompt).toBe(+ "('(one)1.1 two', 'three four').and()"+ );+ });++ it('keeps hyphenated words intact when adjacent text is adjusted', () => {+ expect(adjust('razor-sharp teeth', 'teeth', 'increment').prompt).toBe('razor-sharp teeth+');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.tsnew file mode 100644index 0000000000..3c15b55e63--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/attention.ts@@ -0,0 +1,553 @@+import type { PromptAstNode, PromptAttention, PromptFunctionArg, PromptRange } from './ast';++import { parsePrompt, serializePromptWithSelection } from './ast';++export type PromptAttentionDirection = 'increment' | 'decrement';++export interface PromptAttentionAdjustment {+ prompt: string;+ selectionStart: number;+ 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 PromptFunctionNode = Extract<PromptAstNode, { type: 'prompt_function' }>;+type LeafNode = Exclude<PromptAstNode, { type: 'group' | 'prompt_function' }>;++interface WeightedLeaf {+ text: string;+ type: LeafNode['type'];+ weight: number;+ range: PromptRange;+ parentRange?: PromptRange;+ hasExplicitAttention: boolean;+ usesNumericAttention: boolean;+ isSelected: 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 addSymbolicAttention = (current: PromptAttention | undefined, next: '+' | '-'): PromptAttention | undefined => {+ if (current === undefined) {+ return next;+ }++ if (typeof current === 'number') {+ return next === '+' ? roundWeight(current * ATTENTION_FACTOR) : roundWeight(current / ATTENTION_FACTOR);+ }++ 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 }+ : 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 = [];+ };++ for (const node of nodes) {+ if (node.type === 'prompt_function') {+ flushNormalNodes();+ regions.push({ type: 'prompt_function', node });+ } else {+ normalNodes.push(node);+ }+ }++ flushNormalNodes();++ return regions;+};++const flattenNodes = (+ nodes: PromptAstNode[],+ inheritedWeight = 1,+ parentRange?: PromptRange,+ inheritedNumericAttention = false+): WeightedLeaf[] => {+ const leaves: WeightedLeaf[] = [];++ 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));+ continue;+ }++ if (node.type === 'prompt_function') {+ 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 (!leaf.parentRange) {+ return true;+ }++ 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;+};++const findSelectedGroup = (+ nodes: PromptAstNode[],+ selectionStart: number,+ selectionEnd: number+): Extract<PromptAstNode, { type: 'group' }> | null => {+ 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));+ } else {+ leaf.weight = roundWeight(leaf.weight * (direction === 'increment' ? ATTENTION_FACTOR : 1 / ATTENTION_FACTOR));+ }+ }+};++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;+ }++ if (predicate(leaf)) {+ end++;+ continue;+ }++ if (leaf.type !== 'whitespace') {+ break;+ }++ 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++;+ }++ 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 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 })));++ if (children.length === 0) {+ return null;+ }++ 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 };+ }+ }++ 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;+ }++ return {+ type: 'group',+ attention: roundWeight(weight),+ children,+ range: GENERATED_RANGE,+ isSelection: selectedAll(leaves) || 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));+ 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);+ }++ pushLeaves(nodes, leaves, trimmed.end, runEnd);+ index = runEnd;+ }++ return nodes;+};++const adjustNodes = (+ nodes: PromptAstNode[],+ selectionStart: number,+ selectionEnd: number,+ direction: PromptAttentionDirection,+ preferNumericAttentionStyle: boolean+): { 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 } => {+ let modified = false;+ const promptArgs: PromptFunctionArg[] = node.promptArgs.map((arg) => {+ const clipped = clipRange(selectionStart, selectionEnd, arg.contentRange);++ if (!clipped) {+ return arg;+ }++ const result = adjustNodes(arg.nodes, clipped.start, clipped.end, direction, preferNumericAttentionStyle);++ if (!result.modified) {+ return arg;+ }++ 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);+ continue;+ }++ const clipped = clipRange(selectionStart, selectionEnd, region.node.range);++ if (!clipped) {+ nextNodes.push(region.node);+ continue;+ }++ const result = adjustPromptFunction(+ region.node,+ clipped.start,+ clipped.end,+ direction,+ preferNumericAttentionStyle+ );+ modified = modified || result.modified;+ nextNodes.push(result.node);+ }++ return modified ? serializePromptWithSelection(nextNodes) : { prompt, selectionStart, selectionEnd };+};++export const adjustPromptAttention = (+ prompt: string,+ selectionStart: number,+ selectionEnd: number,+ direction: PromptAttentionDirection,+ preferNumericAttentionStyle = false+): PromptAttentionAdjustment => {+ try {+ return adjustPromptAttentionUnchecked(prompt, selectionStart, selectionEnd, direction, preferNumericAttentionStyle);+ } catch {+ return { prompt, selectionStart, selectionEnd };+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.test.tsnew file mode 100644index 0000000000..7a75a2053a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { buildPromptHighlightSegments, type PromptHighlightKind } from './highlight';++const segmentsByText = (prompt: string, text: string) =>+ buildPromptHighlightSegments(prompt).filter((segment) => segment.text === text || segment.text.includes(text));++const kindForText = (prompt: string, text: string): PromptHighlightKind | undefined =>+ segmentsByText(prompt, text)[0]?.kind;++describe('prompt highlight segments', () => {+ it('highlights symbolic and numeric attention separately', () => {+ const segments = buildPromptHighlightSegments('cat+ (dog)1.2');++ expect(segments).toContainEqual({ kind: 'attention', range: { start: 3, end: 4 }, text: '+' });+ expect(segments).toContainEqual({ kind: 'attentionNumeric', range: { start: 10, end: 13 }, text: '1.2' });+ });++ it('highlights embeddings as a semantic range', () => {+ const prompt = 'use <embedding_name> now';++ expect(kindForText(prompt, '<embedding_name>')).toBe('embedding');+ });++ it('highlights escaped parentheses as literal prompt syntax', () => {+ const segments = buildPromptHighlightSegments('literal \\(medium\\)');++ expect(segments).toContainEqual({ kind: 'escapedParen', range: { start: 8, end: 10 }, text: '\\(' });+ expect(segments).toContainEqual({ kind: 'escapedParen', range: { start: 16, end: 18 }, text: '\\)' });+ });++ it('highlights prompt function args and method tails cosmetically', () => {+ const prompt = "('one two', 'three four').and()";++ expect(kindForText(prompt, 'one two')).toBe('promptFunctionArg');+ expect(kindForText(prompt, 'three four')).toBe('promptFunctionArg');+ expect(kindForText(prompt, '.and()')).toBe('promptFunctionMethod');+ });++ it('keeps attention syntax inside prompt function args higher priority than arg background', () => {+ const prompt = "('one+', 'two').and()";++ expect(kindForText(prompt, '+')).toBe('attention');+ });++ it('marks unmatched parentheses as cosmetic errors', () => {+ expect(kindForText('(unclosed', '(')).toBe('error');+ expect(kindForText('extra)', ')')).toBe('error');+ });++ it('does not mark hyphenated words as attention', () => {+ const prompt = 'razor-sharp teeth';++ expect(kindForText(prompt, '-')).toBe('punctuation');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.ts b/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.tsnew file mode 100644index 0000000000..47098e7763--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/generation/prompt/highlight.ts@@ -0,0 +1,196 @@+import type { PromptAstNode, PromptRange, PromptToken } from './ast';++import { parsePromptTokens, tokenizePrompt } from './ast';++export type PromptHighlightKind =+ | 'text'+ | 'attention'+ | 'attentionNumeric'+ | 'group'+ | 'embedding'+ | 'escapedParen'+ | 'promptFunctionMethod'+ | 'promptFunctionArg'+ | 'punctuation'+ | 'error';++export interface PromptHighlightSegment {+ kind: PromptHighlightKind;+ range: PromptRange;+ text: string;+}++interface HighlightAnnotation {+ kind: PromptHighlightKind;+ priority: number;+ range: PromptRange;+}++const ANNOTATION_PRIORITY = {+ error: 100,+ embedding: 40,+ promptFunctionMethod: 35,+ promptFunctionArg: 5,+} as const;++const BASE_PRIORITY: Record<PromptHighlightKind, number> = {+ attention: 30,+ attentionNumeric: 30,+ embedding: 30,+ error: 100,+ escapedParen: 20,+ group: 20,+ promptFunctionArg: 5,+ promptFunctionMethod: 35,+ punctuation: 10,+ text: 0,+};++const isNumericAttention = (value: unknown): boolean => typeof value === 'number' || !Number.isNaN(Number(value));++const tokenKind = (token: PromptToken): PromptHighlightKind => {+ switch (token.type) {+ case 'weight':+ return isNumericAttention(token.value) ? 'attentionNumeric' : 'attention';+ case 'lparen':+ case 'rparen':+ return 'group';+ case 'lembed':+ case 'rembed':+ return 'embedding';+ case 'escaped_paren':+ return 'escapedParen';+ case 'punct':+ return 'punctuation';+ default:+ return 'text';+ }+};++const covers = (outer: PromptRange, inner: PromptRange): boolean =>+ outer.start <= inner.start && outer.end >= inner.end;++const getBestAnnotation = (+ annotations: HighlightAnnotation[],+ tokenRange: PromptRange+): HighlightAnnotation | undefined =>+ annotations+ .filter((annotation) => covers(annotation.range, tokenRange))+ .sort((left, right) => right.priority - left.priority)[0];++const addPromptFunctionAnnotations = (+ prompt: string,+ node: Extract<PromptAstNode, { type: 'prompt_function' }>,+ annotations: HighlightAnnotation[]+): void => {+ for (const arg of node.promptArgs) {+ annotations.push({+ kind: 'promptFunctionArg',+ priority: ANNOTATION_PRIORITY.promptFunctionArg,+ range: arg.contentRange,+ });+ }++ const lastArg = node.promptArgs.at(-1);+ const methodStart = lastArg ? prompt.indexOf('.', lastArg.contentRange.end) : -1;++ if (methodStart >= 0 && methodStart < node.range.end) {+ annotations.push({+ kind: 'promptFunctionMethod',+ priority: ANNOTATION_PRIORITY.promptFunctionMethod,+ range: { start: methodStart, end: node.range.end },+ });+ }+};++const collectAnnotations = (+ prompt: string,+ nodes: PromptAstNode[],+ annotations: HighlightAnnotation[] = []+): HighlightAnnotation[] => {+ for (const node of nodes) {+ if (node.type === 'embedding') {+ annotations.push({ kind: 'embedding', priority: ANNOTATION_PRIORITY.embedding, range: node.range });+ continue;+ }++ if (node.type === 'group') {+ collectAnnotations(prompt, node.children, annotations);+ continue;+ }++ if (node.type === 'prompt_function') {+ addPromptFunctionAnnotations(prompt, node, annotations);+ collectAnnotations(+ prompt,+ node.promptArgs.flatMap((arg) => arg.nodes),+ annotations+ );+ }+ }++ return annotations;+};++const collectParenthesisErrors = (tokens: PromptToken[]): HighlightAnnotation[] => {+ const annotations: HighlightAnnotation[] = [];+ const stack: PromptToken[] = [];++ for (const token of tokens) {+ if (token.type === 'lparen') {+ stack.push(token);+ } else if (token.type === 'rparen') {+ if (stack.length > 0) {+ stack.pop();+ } else {+ annotations.push({ kind: 'error', priority: ANNOTATION_PRIORITY.error, range: token.range });+ }+ }+ }++ for (const token of stack) {+ annotations.push({ kind: 'error', priority: ANNOTATION_PRIORITY.error, range: token.range });+ }++ return annotations;+};++const appendSegment = (segments: PromptHighlightSegment[], segment: PromptHighlightSegment): void => {+ const previous = segments.at(-1);++ if (previous && previous.kind === segment.kind && previous.range.end === segment.range.start) {+ previous.text += segment.text;+ previous.range.end = segment.range.end;+ return;+ }++ segments.push(segment);+};++export const buildPromptHighlightSegments = (prompt: string): PromptHighlightSegment[] => {+ if (!prompt) {+ return [];+ }++ try {+ const tokens = tokenizePrompt(prompt);+ const annotations = [...collectAnnotations(prompt, parsePromptTokens(tokens)), ...collectParenthesisErrors(tokens)];+ const segments: PromptHighlightSegment[] = [];++ for (const token of tokens) {+ const annotation = getBestAnnotation(annotations, token.range);+ const baseKind = tokenKind(token);+ const kind = annotation && annotation.priority > BASE_PRIORITY[baseKind] ? annotation.kind : baseKind;++ appendSegment(segments, {+ kind,+ range: { ...token.range },+ text: prompt.slice(token.range.start, token.range.end),+ });+ }++ return segments;+ } catch {+ return [{ kind: 'text', range: { start: 0, end: prompt.length }, text: prompt }];+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex 57b997ed71..91c75c89ca 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -14,6 +14,10 @@ const implemented = new Set(['app.focusPrompt','app.invoke','app.invokeFront',+ 'app.promptHistoryNext',+ 'app.promptHistoryPrev',+ 'app.promptWeightDown',+ 'app.promptWeightUp','app.resetPanelLayout','app.selectCanvasTab','app.selectGenerateTab',@@ -59,6 +63,16 @@ const implemented = new Set(['workflows.undo',]);+const editableAppHotkeys = new Set([+ 'app.focusPrompt',+ 'app.invoke',+ 'app.invokeFront',+ 'app.promptHistoryNext',+ 'app.promptHistoryPrev',+ 'app.promptWeightDown',+ 'app.promptWeightUp',+]);+const formatHotkeyTitle = (id: string): string =>id.replace(/([a-z])([A-Z])/g, '$1 $2')@@ -68,17 +82,21 @@ const formatHotkeyTitle = (id: string): string =>.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ');-const hotkey = (category: HotkeyCategory, id: string, defaultKeys: string[]): HotkeyDefinition => ({- allowInEditable: category === 'app' && (id === 'invoke' || id === 'invokeFront'),- category,- commandId: `${category}.${id}`,- defaultKeys,- id: `${category}.${id}`,- implemented: implemented.has(`${category}.${id}`),- preventDefault: true,- scope: categoryScopes[category],- title: formatHotkeyTitle(id),-});+const hotkey = (category: HotkeyCategory, id: string, defaultKeys: string[]): HotkeyDefinition => {+ const commandId = `${category}.${id}`;++ return {+ allowInEditable: editableAppHotkeys.has(commandId),+ category,+ commandId,+ defaultKeys,+ id: commandId,+ implemented: implemented.has(commandId),+ preventDefault: true,+ scope: categoryScopes[category],+ title: formatHotkeyTitle(id),+ };+};export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('app', 'invoke', ['mod+enter']),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex f21c50271f..d38c97780e 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/modelsSimport { openWidgetPlacement } from '@workbench/widgetPlacementCommands';import { getWidgetsForRegion } from '@workbench/widgetRegistry';import { focusPositivePrompt } from '@workbench/widgets/generate/promptFields';+import { adjustFocusedPromptAttention } from '@workbench/widgets/generate/promptFields/promptAttentionHotkeys';import { navigatePromptHistory } from '@workbench/widgets/generate/promptFields/promptHistoryNavigation';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';@@ -34,6 +35,8 @@ export const FIRST_PARTY_APP_COMMAND_IDS = ['app.selectQueueTab','app.promptHistoryPrev','app.promptHistoryNext',+ 'app.promptWeightUp',+ 'app.promptWeightDown','app.focusPrompt','app.toggleLeftPanel','app.toggleRightPanel',@@ -209,6 +212,18 @@ export const useRegisterFirstPartyCommands = () => {id: 'app.promptHistoryNext',title: 'Next prompt history item',}),+ commandApi.register({+ handler: () =>+ adjustFocusedPromptAttention('increment', projectRef.current.settings.preferNumericAttentionStyle),+ id: 'app.promptWeightUp',+ title: 'Increase prompt weight',+ }),+ commandApi.register({+ handler: () =>+ adjustFocusedPromptAttention('decrement', projectRef.current.settings.preferNumericAttentionStyle),+ id: 'app.promptWeightDown',+ title: 'Decrease prompt weight',+ }),commandApi.register({handler: () => {const region = projectRef.current.widgetRegions.left;diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex d05e07460f..2a352e81ab 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -441,11 +441,16 @@ const ProjectSection = () => {/><SettingTogglechecked={settings.preferNumericAttentionStyle}- comingSoondescription="Prefer numeric prompt attention syntax when controls insert attention weights."label="Prefer numeric attention style"onChange={(checked) => updateProjectSettings({ preferNumericAttentionStyle: checked })}/>+ <SettingToggle+ checked={settings.showPromptSyntaxHighlighting}+ description="Experimental. Color prompt syntax in prompt fields without changing the prompt text or validation behavior."+ label="Highlight prompt syntax (experimental)"+ onChange={(checked) => updateProjectSettings({ showPromptSyntaxHighlighting: checked })}+ /></SettingsSection>);};diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex 8b386df270..a87be30b6d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -211,3 +211,15 @@ describe('clearWorkbenchSettings', () => {expect(api.__clientState.has(SETTINGS_KEY)).toBe(false);});});++describe('normalizeProjectSettings', () => {+ it('defaults prompt syntax highlighting off for older project payloads', () => {+ expect(store.normalizeProjectSettings({}).showPromptSyntaxHighlighting).toBe(false);+ expect(store.normalizeProjectSettings({ showPromptSyntaxHighlighting: true }).showPromptSyntaxHighlighting).toBe(+ true+ );+ expect(store.normalizeProjectSettings({ showPromptSyntaxHighlighting: false }).showPromptSyntaxHighlighting).toBe(+ false+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 8e58a9a955..e0751b9be8 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -63,6 +63,7 @@ export const DEVELOPER_LOG_NAMESPACES: DeveloperLogNamespace[] = [export const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {antialiasProgressImages: false,preferNumericAttentionStyle: false,+ showPromptSyntaxHighlighting: false,showProgressDetails: false,showProgressImagesInViewer: true,useCpuNoise: true,@@ -154,6 +155,10 @@ export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): Ptypeof settings?.preferNumericAttentionStyle === 'boolean'? settings.preferNumericAttentionStyle: DEFAULT_PROJECT_SETTINGS.preferNumericAttentionStyle,+ showPromptSyntaxHighlighting:+ typeof settings?.showPromptSyntaxHighlighting === 'boolean'+ ? settings.showPromptSyntaxHighlighting+ : DEFAULT_PROJECT_SETTINGS.showPromptSyntaxHighlighting,showProgressDetails:typeof settings?.showProgressDetails === 'boolean'? settings.showProgressDetailsdiff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex c021ce8944..3e9647553e 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -652,6 +652,7 @@ export interface ProjectSettings {antialiasProgressImages: boolean;showProgressImagesInViewer: boolean;preferNumericAttentionStyle: boolean;+ showPromptSyntaxHighlighting: boolean;}/** User-tunable appearance + behavior preferences surfaced in the Settings modal. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsxindex e1d8d2c452..0023904abb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/GeneratePromptFields.tsx@@ -3,6 +3,7 @@ import type { PromptHistoryItem } from '@workbench/types';import { Stack } from '@chakra-ui/react';import { getPromptPolicy } from '@workbench/generation/baseGenerationPolicies';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { NegativePromptField } from './NegativePromptField';import { PositivePromptField } from './PositivePromptField';@@ -14,6 +15,7 @@ interface GeneratePromptFieldsProps {}export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: GeneratePromptFieldsProps) => {+ const showSyntaxHighlighting = useActiveProjectSelector((project) => project.settings.showPromptSyntaxHighlighting);const promptPolicy = getPromptPolicy(selectedModel, settings);const usePromptHistoryItem = (prompt: PromptHistoryItem) => {onCommit(@@ -34,6 +36,7 @@ export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: Genevalue={settings.positivePrompt}loras={settings.loras}selectedModel={selectedModel}+ showSyntaxHighlighting={showSyntaxHighlighting}onChange={(positivePrompt) => onCommit({ positivePrompt })}onResizeEnd={(positivePromptHeightPx) => onCommit({ positivePromptHeightPx })}onUsePrompt={usePromptHistoryItem}@@ -43,6 +46,7 @@ export const GeneratePromptFields = ({ onCommit, selectedModel, settings }: GeneheightPx={settings.negativePromptHeightPx}isEnabled={settings.negativePromptEnabled}helpText={promptPolicy.negativeHelpText}+ showSyntaxHighlighting={showSyntaxHighlighting}value={settings.negativePrompt}onEnabledChange={(negativePromptEnabled) => onCommit({ negativePromptEnabled })}onChange={(negativePrompt) => onCommit({ negativePrompt })}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsxindex f6bb8a1809..4682004ba0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/NegativePromptField.tsx@@ -1,12 +1,16 @@import type { ChangeEvent } from 'react';import { Switch } from '@chakra-ui/react';-import { Field, ResizableTextarea } from '@workbench/components/ui';+import { Field } from '@workbench/components/ui';++import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';+import { PromptTextarea } from './PromptTextarea';interface NegativePromptFieldProps {heightPx: number;helpText?: string;isEnabled: boolean;+ showSyntaxHighlighting: boolean;value: string;onChange: (value: string) => void;onEnabledChange: (isEnabled: boolean) => void;@@ -20,6 +24,7 @@ export const NegativePromptField = ({onChange,onEnabledChange,onResizeEnd,+ showSyntaxHighlighting,value,}: NegativePromptFieldProps) => (<Field@@ -36,7 +41,8 @@ export const NegativePromptField = ({helpText={isEnabled ? helpText : undefined}>{isEnabled ? (- <ResizableTextarea+ <PromptTextarea+ {...PROMPT_ATTENTION_TARGET_PROPS}aria-label="Negative prompt"defaultHeightPx={heightPx}maxHeightPx={240}@@ -44,6 +50,7 @@ export const NegativePromptField = ({resizeHandleAriaLabel="Resize negative prompt"size="xs"fontFamily="mono"+ showSyntaxHighlighting={showSyntaxHighlighting}value={value}onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}onResizeEnd={onResizeEnd}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsxindex 466ae9e09c..f09174bdf5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PositivePromptField.tsx@@ -2,16 +2,19 @@ import type { GenerateLora, GenerateModelConfig } from '@workbench/generation/tyimport type { PromptHistoryItem } from '@workbench/types';import type { ChangeEvent } from 'react';-import { Field, ResizableTextarea } from '@workbench/components/ui';+import { Field } from '@workbench/components/ui';import { PositivePromptActions } from './PositivePromptActions';+import { PROMPT_ATTENTION_TARGET_PROPS } from './promptAttentionHotkeys';import { registerPositivePromptElement } from './promptFocus';import { resetPromptHistoryNavigation } from './promptHistoryNavigation';+import { PromptTextarea } from './PromptTextarea';interface PositivePromptFieldProps {heightPx: number;loras: GenerateLora[];selectedModel: GenerateModelConfig | undefined;+ showSyntaxHighlighting: boolean;value: string;onChange: (value: string) => void;onResizeEnd: (heightPx: number) => void;@@ -25,6 +28,7 @@ export const PositivePromptField = ({onResizeEnd,onUsePrompt,selectedModel,+ showSyntaxHighlighting,value,}: PositivePromptFieldProps) => (<Field@@ -39,7 +43,8 @@ export const PositivePromptField = ({/>}>- <ResizableTextarea+ <PromptTextarea+ {...PROMPT_ATTENTION_TARGET_PROPS}aria-label="Positive prompt"defaultHeightPx={heightPx}maxHeightPx={360}@@ -47,6 +52,7 @@ export const PositivePromptField = ({resizeHandleAriaLabel="Resize positive prompt"size="xs"fontFamily="mono"+ showSyntaxHighlighting={showSyntaxHighlighting}textareaRef={registerPositivePromptElement}value={value}onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsxnew file mode 100644index 0000000000..fb2b8ccdb1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/PromptTextarea.tsx@@ -0,0 +1,188 @@+import type { ResizableTextareaProps } from '@workbench/components/ui';+import type { PromptHighlightKind, PromptHighlightSegment } from '@workbench/generation/prompt/highlight';+import type { Ref, UIEvent } from 'react';++import { Box } from '@chakra-ui/react';+import { ResizableTextarea } from '@workbench/components/ui';+import { buildPromptHighlightSegments } from '@workbench/generation/prompt/highlight';+import { useLayoutEffect, useMemo, useRef, useState } from 'react';++const MAX_HIGHLIGHTED_PROMPT_LENGTH = 20_000;+const PROMPT_TEXTAREA_LINE_HEIGHT = '1.6';+const PROMPT_TEXTAREA_PX = '2.5';+const PROMPT_TEXTAREA_PY = '2';++const HIGHLIGHT_STYLE_BY_KIND: Record<+ PromptHighlightKind,+ { bg?: string; color: string; textDecoration?: string; textDecorationColor?: string }+> = {+ attention: { color: 'accent.solid' },+ attentionNumeric: { color: 'fg.success' },+ embedding: { bg: 'bg.warning', color: 'fg.warning' },+ error: { bg: 'bg.error', color: 'fg.error', textDecoration: 'underline wavy', textDecorationColor: 'fg.error' },+ escapedParen: { color: 'fg.muted' },+ group: { color: 'fg.subtle' },+ promptFunctionArg: { bg: 'accent.subtle/20', color: 'fg' },+ promptFunctionMethod: { color: 'accent.fg' },+ punctuation: { color: 'fg.subtle' },+ text: { color: 'fg' },+};++interface PromptTextareaProps extends Omit<ResizableTextareaProps, 'underlay'> {+ showSyntaxHighlighting: boolean;+ value: string;+}++const setRef = (ref: Ref<HTMLTextAreaElement> | undefined, element: HTMLTextAreaElement | null): void => {+ if (!ref) {+ return;+ }++ if (typeof ref === 'function') {+ ref(element);+ return;+ }++ (ref as { current: HTMLTextAreaElement | null }).current = element;+};++const PromptHighlightSpan = ({ segment }: { segment: PromptHighlightSegment }) => {+ const style = HIGHLIGHT_STYLE_BY_KIND[segment.kind];++ return (+ <Box+ as="span"+ bg={style.bg}+ borderRadius={style.bg ? '2px' : undefined}+ color={style.color}+ textDecoration={style.textDecoration}+ textDecorationColor={style.textDecorationColor}+ >+ {segment.text}+ </Box>+ );+};++export const PromptTextarea = ({+ fontFamily = 'mono',+ fontSize,+ lineHeight,+ onScroll,+ showSyntaxHighlighting,+ textareaRef,+ value,+ ...props+}: PromptTextareaProps) => {+ const localTextareaRef = useRef<HTMLTextAreaElement | null>(null);+ const [scroll, setScroll] = useState({ left: 0, top: 0 });+ const [textareaClientWidth, setTextareaClientWidth] = useState<number | null>(null);+ const shouldHighlight = showSyntaxHighlighting && value.length > 0 && value.length <= MAX_HIGHLIGHTED_PROMPT_LENGTH;+ const effectiveFontSize = fontSize ?? 'xs';+ const effectiveLineHeight = lineHeight ?? PROMPT_TEXTAREA_LINE_HEIGHT;+ const segments = useMemo(+ () => (shouldHighlight ? buildPromptHighlightSegments(value) : []),+ [shouldHighlight, value]+ );++ useLayoutEffect(() => {+ if (!shouldHighlight || !localTextareaRef.current) {+ return;+ }++ const textarea = localTextareaRef.current;+ const syncClientWidth = () => {+ const nextWidth = textarea.clientWidth;++ setTextareaClientWidth((currentWidth) => (currentWidth === nextWidth ? currentWidth : nextWidth));+ };+ const resizeObserver = new ResizeObserver(syncClientWidth);++ syncClientWidth();+ resizeObserver.observe(textarea);+ window.addEventListener('resize', syncClientWidth);++ return () => {+ resizeObserver.disconnect();+ window.removeEventListener('resize', syncClientWidth);+ };+ }, [shouldHighlight, value]);++ const handleTextareaRef = (element: HTMLTextAreaElement | null) => {+ localTextareaRef.current = element;+ setRef(textareaRef, element);+ };++ const handleScroll = (event: UIEvent<HTMLTextAreaElement>) => {+ setScroll({ left: event.currentTarget.scrollLeft, top: event.currentTarget.scrollTop });+ onScroll?.(event);+ };++ const underlay = shouldHighlight ? (+ <Box+ aria-hidden="true"+ bg="bg.emphasized"+ borderColor="transparent"+ borderRadius="md"+ borderWidth="1px"+ color="fg"+ inset="0"+ overflow="hidden"+ pointerEvents="none"+ position="absolute"+ zIndex={0}+ css={{ '@media (forced-colors: active)': { display: 'none' } }}+ >+ <Box+ as="pre"+ fontFamily={fontFamily}+ fontSize={effectiveFontSize}+ lineHeight={effectiveLineHeight}+ m="0"+ minH="100%"+ overflowWrap="break-word"+ px={PROMPT_TEXTAREA_PX}+ py={PROMPT_TEXTAREA_PY}+ transform={`translate(${-scroll.left}px, ${-scroll.top}px)`}+ whiteSpace="pre-wrap"+ w={textareaClientWidth ? `${textareaClientWidth}px` : '100%'}+ >+ {segments.map((segment) => (+ <PromptHighlightSpan key={`${segment.range.start}:${segment.range.end}:${segment.kind}`} segment={segment} />+ ))}+ {value.endsWith('\n') ? '\u200b' : null}+ </Box>+ </Box>+ ) : null;++ return (+ <ResizableTextarea+ {...props}+ bg={shouldHighlight ? 'transparent' : props.bg}+ caretColor={shouldHighlight ? 'fg' : props.caretColor}+ color={shouldHighlight ? 'transparent' : props.color}+ css={+ shouldHighlight+ ? {+ '&::selection': { color: 'transparent', WebkitTextFillColor: 'transparent' },+ '@media (forced-colors: active)': {+ WebkitTextFillColor: 'CanvasText',+ backgroundColor: 'Field',+ color: 'CanvasText',+ },+ WebkitTextFillColor: 'transparent',+ }+ : props.css+ }+ fontFamily={fontFamily}+ fontSize={effectiveFontSize}+ lineHeight={effectiveLineHeight}+ overflowWrap="break-word"+ px={PROMPT_TEXTAREA_PX}+ py={PROMPT_TEXTAREA_PY}+ textareaRef={handleTextareaRef}+ underlay={underlay}+ value={value}+ onScroll={handleScroll}+ />+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.tsnew file mode 100644index 0000000000..864340c595--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFields/promptAttentionHotkeys.ts@@ -0,0 +1,60 @@+import type { PromptAttentionDirection } from '@workbench/generation/prompt/attention';++import { adjustPromptAttention } from '@workbench/generation/prompt/attention';++export const PROMPT_ATTENTION_TARGET_ATTR = 'data-prompt-attention-target';+export const PROMPT_ATTENTION_TARGET_PROPS = { [PROMPT_ATTENTION_TARGET_ATTR]: 'true' } as const;++const isPromptAttentionTarget = (element: Element | null): element is HTMLTextAreaElement =>+ element instanceof HTMLTextAreaElement && element.getAttribute(PROMPT_ATTENTION_TARGET_ATTR) === 'true';++const setTextareaValue = (textarea: HTMLTextAreaElement, value: string): void => {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;++ if (valueSetter) {+ valueSetter.call(textarea, value);+ } else {+ textarea.value = value;+ }++ textarea.dispatchEvent(new Event('input', { bubbles: true }));+};++const replaceTextareaValue = (textarea: HTMLTextAreaElement, value: string): void => {+ textarea.focus();+ textarea.setSelectionRange(0, textarea.value.length);++ if (typeof document.execCommand === 'function' && document.execCommand('insertText', false, value)) {+ return;+ }++ setTextareaValue(textarea, value);+};++export const adjustFocusedPromptAttention = (+ direction: PromptAttentionDirection,+ preferNumericAttentionStyle: boolean+): boolean => {+ const textarea = document.activeElement;++ if (!isPromptAttentionTarget(textarea)) {+ return false;+ }++ const result = adjustPromptAttention(+ textarea.value,+ textarea.selectionStart,+ textarea.selectionEnd,+ direction,+ preferNumericAttentionStyle+ );++ if (result.prompt === textarea.value) {+ return false;+ }++ replaceTextareaValue(textarea, result.prompt);+ textarea.setSelectionRange(result.selectionStart, result.selectionEnd);++ return true;+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex d6695d2ac4..ef58b4fd31 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -1053,6 +1053,7 @@ describe('workbench account and project settings', () => {preferNumericAttentionStyle: true,showProgressDetails: false,showProgressImagesInViewer: true,+ showPromptSyntaxHighlighting: false,useCpuNoise: false,});});