Skip to content

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

Prompt Attention Fixes (#8860)

Josh Corbettfcdcd7f46b6f
diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.json
index 2db971d06a..4fcf0786b8 100644
--- a/invokeai/frontend/web/public/locales/en.json
+++ b/invokeai/frontend/web/public/locales/en.json
@@ -1566,6 +1566,8 @@
"general": "General",
"generation": "Generation",
"models": "Models",
+ "preferAttentionStyleNumeric": "Prefer Numeric Attention Style",
+ "prompt": "Prompt",
"resetComplete": "Web UI has been reset.",
"resetWebUI": "Reset Web UI",
"resetWebUIDesc1": "Resetting the web UI only resets the browser's local cache of your images and remembered settings. It does not delete any images from disk.",
diff --git a/invokeai/frontend/web/src/common/util/promptAST.test.ts b/invokeai/frontend/web/src/common/util/promptAST.test.ts
index 97f82716b8..32ad9dc09f 100644
--- a/invokeai/frontend/web/src/common/util/promptAST.test.ts
+++ b/invokeai/frontend/web/src/common/util/promptAST.test.ts
@@ -78,6 +78,44 @@ describe('promptAST', () => {
{ type: 'rembed', start: 15, end: 16 },
]);
});
+
+ it('should tokenize prompt function syntax', () => {
+ const tokens = tokenize("('a', 'b').and()");
+ expect(tokens).toEqual([
+ { type: 'lparen', start: 0, end: 1 },
+ { type: 'punct', value: "'", start: 1, end: 2 },
+ { type: 'word', value: 'a', start: 2, end: 3 },
+ { type: 'punct', value: "'", start: 3, end: 4 },
+ { type: 'punct', value: ',', start: 4, end: 5 },
+ { type: 'whitespace', value: ' ', start: 5, end: 6 },
+ { type: 'punct', value: "'", start: 6, end: 7 },
+ { type: 'word', value: 'b', start: 7, end: 8 },
+ { type: 'punct', value: "'", start: 8, end: 9 },
+ { type: 'rparen', start: 9, end: 10 },
+ { type: 'punct', value: '.', start: 10, end: 11 },
+ { type: 'word', value: 'and', start: 11, end: 14 },
+ { type: 'lparen', start: 14, end: 15 },
+ { type: 'rparen', start: 15, end: 16 },
+ ]);
+ });
+
+ it('should tokenize curly/smart quotes as punctuation', () => {
+ const tokens = tokenize('\u201chello\u201d');
+ expect(tokens).toEqual([
+ { type: 'punct', value: '\u201c', start: 0, end: 1 },
+ { type: 'word', value: 'hello', start: 1, end: 6 },
+ { type: 'punct', value: '\u201d', start: 6, end: 7 },
+ ]);
+ });
+
+ it('should tokenize curly single quotes as punctuation', () => {
+ const tokens = tokenize('\u2018hello\u2019');
+ expect(tokens).toEqual([
+ { type: 'punct', value: '\u2018', start: 0, end: 1 },
+ { type: 'word', value: 'hello', start: 1, end: 6 },
+ { type: 'punct', value: '\u2019', start: 6, end: 7 },
+ ]);
+ });
});
describe('parseTokens', () => {
@@ -167,6 +205,312 @@ describe('promptAST', () => {
const ast = parseTokens(tokens);
expect(ast).toEqual([{ type: 'embedding', value: 'embedding_name', range: { start: 0, end: 16 } }]);
});
+
+ describe('prompt functions', () => {
+ it('should parse .and() prompt function with single-quoted args', () => {
+ const tokens = tokenize("('one two', 'three four').and()");
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.functionParams).toBe('');
+ expect(pf.promptArgs).toHaveLength(2);
+
+ // First arg: 'one two'
+ expect(pf.promptArgs[0]!.quote).toBe("'");
+ expect(pf.promptArgs[0]!.nodes).toHaveLength(3); // word, ws, word
+ expect(pf.promptArgs[0]!.nodes[0]).toMatchObject({ type: 'word', text: 'one' });
+ expect(pf.promptArgs[0]!.nodes[2]).toMatchObject({ type: 'word', text: 'two' });
+
+ // Second arg: 'three four'
+ expect(pf.promptArgs[1]!.quote).toBe("'");
+ expect(pf.promptArgs[1]!.nodes).toHaveLength(3);
+ expect(pf.promptArgs[1]!.nodes[0]).toMatchObject({ type: 'word', text: 'three' });
+ expect(pf.promptArgs[1]!.nodes[2]).toMatchObject({ type: 'word', text: 'four' });
+ });
+
+ it('should parse .or() prompt function', () => {
+ const tokens = tokenize("('one', 'two three. four.').or()");
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('or');
+ expect(pf.promptArgs).toHaveLength(2);
+
+ // First arg: 'one'
+ expect(pf.promptArgs[0]!.nodes).toHaveLength(1);
+ expect(pf.promptArgs[0]!.nodes[0]).toMatchObject({ type: 'word', text: 'one' });
+
+ // Second arg: 'two three. four.'
+ expect(pf.promptArgs[1]!.nodes.length).toBeGreaterThanOrEqual(5);
+ });
+
+ it('should parse .blend() prompt function with params', () => {
+ const tokens = tokenize("('one', 'two').blend(0.7, 0.3)");
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('blend');
+ expect(pf.functionParams).toBe('0.7, 0.3');
+ expect(pf.promptArgs).toHaveLength(2);
+ });
+
+ it('should parse prompt function with double-quoted args', () => {
+ const tokens = tokenize('("one", "two").and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.promptArgs[0]!.quote).toBe('"');
+ });
+
+ it('should parse prompt function with curly double quotes', () => {
+ const tokens = tokenize('(\u201cone\u201d, \u201ctwo\u201d).and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.promptArgs).toHaveLength(2);
+ expect(pf.promptArgs[0]!.quote).toBe('\u201c');
+ expect(pf.promptArgs[0]!.nodes[0]).toMatchObject({ type: 'word', text: 'one' });
+ expect(pf.promptArgs[1]!.nodes[0]).toMatchObject({ type: 'word', text: 'two' });
+ });
+
+ it('should parse prompt function with curly single quotes', () => {
+ const tokens = tokenize('(\u2018one\u2019, \u2018two\u2019).and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.promptArgs[0]!.quote).toBe('\u2018');
+ });
+
+ it('should parse prompt function with curly quotes containing commas in args', () => {
+ const prompt = '(\u201chigh detail, cinematic\u201d, \u201csoft light, portrait\u201d).and()';
+ const ast = parseTokens(tokenize(prompt));
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.promptArgs).toHaveLength(2);
+ });
+
+ it('should parse prompt function with newline before .method()', () => {
+ const prompt = '(\u201cone\u201d, \u201ctwo\u201d)\n.and()';
+ const ast = parseTokens(tokenize(prompt));
+ expect(ast).toHaveLength(1);
+ expect(ast[0]!.type).toBe('prompt_function');
+ });
+
+ it('should parse quoted prompt function with newline before .method()', () => {
+ const prompt = "('one', 'two')\n.and()";
+ const ast = parseTokens(tokenize(prompt));
+ expect(ast).toHaveLength(1);
+ expect(ast[0]!.type).toBe('prompt_function');
+ });
+
+ it('should parse prompt function with attention inside args', () => {
+ const tokens = tokenize("('hello+', '(world)-').and()");
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+
+ // First arg: hello+
+ const arg0Word = pf.promptArgs[0]!.nodes[0]!;
+ expect(arg0Word).toMatchObject({ type: 'word', text: 'hello', attention: '+' });
+
+ // Second arg: (world)-
+ const arg1Group = pf.promptArgs[1]!.nodes[0]!;
+ expect(arg1Group.type).toBe('group');
+ if (arg1Group.type === 'group') {
+ expect(arg1Group.attention).toBe('-');
+ }
+ });
+
+ it('should preserve content range for each arg', () => {
+ const tokens = tokenize("('one two', 'three four').and()");
+ const ast = parseTokens(tokens);
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+
+ // 'one two' content is between quotes at positions 1 and 9
+ expect(pf.promptArgs[0]!.contentRange.start).toBe(2);
+ expect(pf.promptArgs[0]!.contentRange.end).toBe(9);
+
+ // 'three four' content is between quotes at positions 12 and 23
+ expect(pf.promptArgs[1]!.contentRange.start).toBe(13);
+ expect(pf.promptArgs[1]!.contentRange.end).toBe(23);
+ });
+
+ it('should parse prompt function embedded in larger prompt', () => {
+ const tokens = tokenize("some text, ('a', 'b').and(), more text");
+ const ast = parseTokens(tokens);
+
+ // Should have: word, ws, word, punct, ws, prompt_function, punct, ws, word, ws, word
+ const pfNodes = ast.filter((n) => n.type === 'prompt_function');
+ expect(pfNodes).toHaveLength(1);
+ expect(pfNodes[0]!.type).toBe('prompt_function');
+ });
+
+ it('should fall back to regular group when no method call follows', () => {
+ const tokens = tokenize("('a', 'b')");
+ const ast = parseTokens(tokens);
+
+ // Without .method(), this should be parsed as a regular group
+ expect(ast[0]!.type).toBe('group');
+ });
+
+ it('should parse three-arg prompt function', () => {
+ const tokens = tokenize("('a', 'b', 'c').blend(0.5, 0.3, 0.2)");
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.promptArgs).toHaveLength(3);
+ expect(pf.functionParams).toBe('0.5, 0.3, 0.2');
+ });
+ });
+
+ describe('unquoted prompt functions', () => {
+ it('should parse unquoted .and() prompt function', () => {
+ const tokens = tokenize('(one,two).and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.functionParams).toBe('');
+ expect(pf.promptArgs).toHaveLength(2);
+ expect(pf.promptArgs[0]!.quote).toBe('');
+ expect(pf.promptArgs[0]!.nodes[0]).toMatchObject({ type: 'word', text: 'one' });
+ expect(pf.promptArgs[1]!.quote).toBe('');
+ expect(pf.promptArgs[1]!.nodes[0]).toMatchObject({ type: 'word', text: 'two' });
+ });
+
+ it('should parse unquoted .and() with spaces', () => {
+ const tokens = tokenize('(one two, three four).and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('and');
+ expect(pf.promptArgs).toHaveLength(2);
+ expect(pf.promptArgs[0]!.nodes[0]).toMatchObject({ type: 'word', text: 'one' });
+ expect(pf.promptArgs[0]!.nodes[2]).toMatchObject({ type: 'word', text: 'two' });
+ expect(pf.promptArgs[1]!.nodes[0]).toMatchObject({ type: 'word', text: 'three' });
+ expect(pf.promptArgs[1]!.nodes[2]).toMatchObject({ type: 'word', text: 'four' });
+ });
+
+ it('should parse unquoted .blend() with params', () => {
+ const tokens = tokenize('(one two, three four).blend(0.7, 0.3)');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.name).toBe('blend');
+ expect(pf.functionParams).toBe('0.7, 0.3');
+ expect(pf.promptArgs).toHaveLength(2);
+ });
+
+ it('should parse unquoted three-arg prompt function', () => {
+ const tokens = tokenize('(a, b, c).blend(0.5, 0.3, 0.2)');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ expect(pf.promptArgs).toHaveLength(3);
+ expect(pf.functionParams).toBe('0.5, 0.3, 0.2');
+ });
+
+ it('should parse unquoted prompt function with attention inside args', () => {
+ const tokens = tokenize('(hello+, world).and()');
+ const ast = parseTokens(tokens);
+ expect(ast).toHaveLength(1);
+
+ const pf = ast[0]!;
+ expect(pf.type).toBe('prompt_function');
+ if (pf.type !== 'prompt_function') {
+ return;
+ }
+ const arg0Word = pf.promptArgs[0]!.nodes[0]!;
+ expect(arg0Word).toMatchObject({ type: 'word', text: 'hello', attention: '+' });
+ });
+
+ it('should fall back to regular group for single-arg unquoted function', () => {
+ const tokens = tokenize('(hello world).and()');
+ const ast = parseTokens(tokens);
+ // Without a comma, this is not detected as a prompt function
+ expect(ast[0]!.type).toBe('group');
+ });
+
+ it('should parse unquoted prompt function embedded in larger prompt', () => {
+ const tokens = tokenize('some text, (a, b).and(), more text');
+ const ast = parseTokens(tokens);
+ const pfNodes = ast.filter((n) => n.type === 'prompt_function');
+ expect(pfNodes).toHaveLength(1);
+ });
+ });
});
describe('serialize', () => {
@@ -218,6 +562,163 @@ describe('promptAST', () => {
const result = serialize(ast);
expect(result).toBe('<embedding_name>');
});
+
+ describe('prompt functions', () => {
+ it('should serialize .and() prompt function', () => {
+ const tokens = tokenize("('one two', 'three four').and()");
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe("('one two', 'three four').and()");
+ });
+
+ it('should serialize .or() prompt function', () => {
+ const tokens = tokenize("('one', 'two three. four.').or()");
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe("('one', 'two three. four.').or()");
+ });
+
+ it('should serialize .blend() with params', () => {
+ const tokens = tokenize("('one', 'two').blend(0.7, 0.3)");
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe("('one', 'two').blend(0.7, 0.3)");
+ });
+
+ it('should serialize prompt function with attention inside args', () => {
+ const tokens = tokenize("('hello+', '(world)-').and()");
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe("('hello+', '(world)-').and()");
+ });
+
+ it('should serialize prompt function embedded in larger prompt', () => {
+ const prompt = "some text, ('a', 'b').and(), more text";
+ const tokens = tokenize(prompt);
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe(prompt);
+ });
+
+ it('should serialize three-arg blend', () => {
+ const tokens = tokenize("('a', 'b', 'c').blend(0.5, 0.3, 0.2)");
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe("('a', 'b', 'c').blend(0.5, 0.3, 0.2)");
+ });
+
+ it('should serialize double-quoted prompt function', () => {
+ const tokens = tokenize('("one", "two").and()');
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe('("one", "two").and()');
+ });
+
+ it('should serialize curly double-quoted prompt function', () => {
+ const tokens = tokenize('(\u201cone\u201d, \u201ctwo\u201d).and()');
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe('(\u201cone\u201d, \u201ctwo\u201d).and()');
+ });
+
+ it('should serialize curly single-quoted prompt function', () => {
+ const tokens = tokenize('(\u2018one\u2019, \u2018two\u2019).and()');
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe('(\u2018one\u2019, \u2018two\u2019).and()');
+ });
+ });
+
+ describe('unquoted prompt functions', () => {
+ it('should serialize unquoted .and()', () => {
+ const tokens = tokenize('(one two, three four).and()');
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe('(one two, three four).and()');
+ });
+
+ it('should serialize unquoted .blend() with params', () => {
+ const tokens = tokenize('(one two, three four).blend(0.7, 0.3)');
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe('(one two, three four).blend(0.7, 0.3)');
+ });
+
+ it('should serialize unquoted prompt function embedded in larger prompt', () => {
+ const prompt = 'some text, (a, b).and(), more text';
+ const tokens = tokenize(prompt);
+ const ast = parseTokens(tokens);
+ const result = serialize(ast);
+ expect(result).toBe(prompt);
+ });
+ });
+ });
+
+ describe('round-trip (tokenize → parse → serialize)', () => {
+ const roundTrip = (prompt: string) => {
+ const tokens = tokenize(prompt);
+ const ast = parseTokens(tokens);
+ return serialize(ast);
+ };
+
+ it.each([
+ 'a cat',
+ '(a cat)',
+ '(a cat)1.2',
+ 'cat+',
+ 'cat++',
+ 'cat-',
+ '(hello world)+',
+ '(hello world)++',
+ '(hello world)-',
+ '\\(medium\\)',
+ 'colored pencil \\(medium\\) (enhanced)',
+ '<embedding_name>',
+ 'portrait \\(realistic\\) (high quality)1.2',
+ '(masterpiece)1.3, best quality, (high detail)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").and()',
+ // Curly double-quoted prompt functions
+ '(\u201cone\u201d, \u201ctwo\u201d).and()',
+ '(\u201chigh detail, cinematic\u201d, \u201csoft light, portrait\u201d).and()',
+ '(\u201cone\u201d, \u201ctwo\u201d).blend(0.7, 0.3)',
+ // Curly single-quoted prompt functions
+ '(\u2018one\u2019, \u2018two\u2019).and()',
+ '(\u2018one\u2019, \u2018two\u2019).or()',
+ // Unquoted prompt functions
+ '(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',
+ "('one',\n 'two',\n 'three').and()",
+ ])('should round-trip: %s', (prompt) => {
+ expect(roundTrip(prompt)).toBe(prompt);
+ });
+ });
+
+ describe('newline normalization', () => {
+ const roundTrip = (prompt: string) => {
+ const tokens = tokenize(prompt);
+ const ast = parseTokens(tokens);
+ return serialize(ast);
+ };
+
+ it('should normalize newline before .method() in quoted prompt function', () => {
+ expect(roundTrip("('one', 'two')\n.and()")).toBe("('one', 'two').and()");
+ });
+
+ it('should normalize newline before .method() in curly-quoted prompt function', () => {
+ expect(roundTrip('(\u201cone\u201d, \u201ctwo\u201d)\n.and()')).toBe('(\u201cone\u201d, \u201ctwo\u201d).and()');
+ });
+
+ it('should normalize newline before .method() in unquoted prompt function', () => {
+ expect(roundTrip('(one, two)\n.and()')).toBe('(one, two).and()');
+ });
});
describe('compel compatibility examples', () => {
diff --git a/invokeai/frontend/web/src/common/util/promptAST.ts b/invokeai/frontend/web/src/common/util/promptAST.ts
index f8cf7ca62e..0a1af62122 100644
--- a/invokeai/frontend/web/src/common/util/promptAST.ts
+++ b/invokeai/frontend/web/src/common/util/promptAST.ts
@@ -3,18 +3,10 @@
*/
export type Attention = string | number;
-type Word = string;
-
-type Punct = string;
-
-type Whitespace = string;
-
-type Embedding = string;
-
type Token =
- | { type: 'word'; value: Word; start: number; end: number }
- | { type: 'whitespace'; value: Whitespace; start: number; end: number }
- | { type: 'punct'; value: Punct; start: number; end: number }
+ | { type: 'word'; value: string; start: number; end: number }
+ | { type: 'whitespace'; value: string; start: number; end: number }
+ | { type: 'punct'; value: string; start: number; end: number }
| { type: 'lparen'; start: number; end: number }
| { type: 'rparen'; start: number; end: number }
| { type: 'weight'; value: Attention; start: number; end: number }
@@ -22,8 +14,21 @@ type Token =
| { type: 'rembed'; start: number; end: number }
| { type: 'escaped_paren'; value: '(' | ')'; start: number; end: number };
+/**
+ * A single argument in a prompt function like .and(), .or(), or .blend().
+ * Contains the parsed AST nodes of the argument content and metadata about quoting/range.
+ */
+export type PromptFunctionArg = {
+ nodes: ASTNode[];
+ quote: string;
+ /** Range of the content between the quotes (exclusive of quotes themselves) in original prompt coordinates. */
+ contentRange: { start: number; end: number };
+ /** Raw separator whitespace after the comma before this arg (args[1+] only). */
+ separator?: string;
+};
+
export type ASTNode =
- | { type: 'word'; text: Word; attention?: Attention; range: { start: number; end: number }; isSelection?: boolean }
+ | { type: 'word'; text: string; attention?: Attention; range: { start: number; end: number }; isSelection?: boolean }
| {
type: 'group';
children: ASTNode[];
@@ -31,20 +36,60 @@ export type ASTNode =
range: { start: number; end: number };
isSelection?: boolean;
}
- | { type: 'embedding'; value: Embedding; range: { start: number; end: number }; isSelection?: boolean }
- | { type: 'whitespace'; value: Whitespace; range: { start: number; end: number }; isSelection?: boolean }
- | { type: 'punct'; value: Punct; range: { start: number; end: number }; isSelection?: boolean }
- | { type: 'escaped_paren'; value: '(' | ')'; range: { start: number; end: number }; isSelection?: boolean };
+ | { type: 'embedding'; value: string; range: { start: number; end: number }; isSelection?: boolean }
+ | { type: 'whitespace'; value: string; range: { start: number; end: number }; isSelection?: boolean }
+ | { type: 'punct'; value: string; range: { start: number; end: number }; isSelection?: boolean }
+ | { type: 'escaped_paren'; value: '(' | ')'; range: { start: number; end: number }; isSelection?: boolean }
+ | {
+ type: 'prompt_function';
+ name: string;
+ promptArgs: PromptFunctionArg[];
+ functionParams: string;
+ range: { start: number; end: number };
+ isSelection?: boolean;
+ };
const WEIGHT_PATTERN = /^[+-]?(\d+(\.\d+)?|[+-]+)/;
const WHITESPACE_PATTERN = /^\s+/;
-const PUNCTUATION_PATTERN = /^[.,]/;
-const OTHER_PATTERN = /\s/;
+const WORD_CHAR_PATTERN = /[a-zA-Z0-9_]/;
+// prettier-ignore
+const PUNCTUATION_PATTERN = /^[.,/!?;:'"""''\u2018\u2019\u201c\u201d`~@#$%^&*=_|]/;
+
+/** All characters that can serve as an opening quote in a prompt function argument. */
+const OPEN_QUOTE_CHARS = new Set(["'", '"', '\u2018', '\u201c']);
+
+/** Map from opening curly quote to the matching closing curly quote. Straight quotes match themselves. */
+const CLOSE_QUOTE_MAP: Record<string, string> = {
+ "'": "'",
+ '"': '"',
+ '\u2018': '\u2019', // ' → '
+ '\u201c': '\u201d', // " → "
+};
+
+// #region Token Helpers
+
+/** Get the string value of a token, if it has one. */
+function tokenValue(t: Token | undefined): string | undefined {
+ if (!t) {
+ return undefined;
+ }
+ if ('value' in t) {
+ return String(t.value);
+ }
+ return undefined;
+}
+
+/** Check if a token is a punct token with a specific value. */
+function isPunctValue(t: Token | undefined, value: string): boolean {
+ return t?.type === 'punct' && tokenValue(t) === value;
+}
+
+// #region Tokenizer
/**
- * Convert a prompt string into an AST.
+ * Convert a prompt string into a token stream.
* @param prompt string
- * @returns ASTNode[]
+ * @returns Token[]
*/
export function tokenize(prompt: string): Token[] {
if (!prompt) {
@@ -52,7 +97,7 @@ export function tokenize(prompt: string): Token[] {
}
const len = prompt.length;
- let tokens: Token[] = [];
+ const tokens: Token[] = [];
let i = 0;
while (i < len) {
@@ -69,7 +114,7 @@ export function tokenize(prompt: string): Token[] {
tokenizeEmbedding(char, i) ||
tokenizeWord(prompt, i) ||
tokenizePunctuation(char, i) ||
- tokenizeOther(char, i);
+ tokenizeFallback(char, i);
if (result) {
if (result.token) {
@@ -168,15 +213,15 @@ function tokenizeWord(prompt: string, i: number): TokenizeResult {
return null;
}
- if (/[a-zA-Z0-9_]/.test(char)) {
+ if (WORD_CHAR_PATTERN.test(char)) {
let j = i;
- while (j < prompt.length && /[a-zA-Z0-9_]/.test(prompt[j]!)) {
+ while (j < prompt.length && WORD_CHAR_PATTERN.test(prompt[j]!)) {
j++;
}
const word = prompt.slice(i, j);
// Check for weight immediately after word (e.g., "Lorem+", "consectetur-")
- const weightMatch = prompt.slice(j).match(/^[+-]?(\d+(\.\d+)?|[+-]+)/);
+ const weightMatch = prompt.slice(j).match(WEIGHT_PATTERN);
if (weightMatch && weightMatch[0]) {
const weightEnd = j + weightMatch[0].length;
return {
@@ -210,17 +255,20 @@ function tokenizeEmbedding(char: string, i: number): TokenizeResult {
return null;
}
-function tokenizeOther(char: string, i: number): TokenizeResult {
- // Any other single character punctuation
- if (OTHER_PATTERN.test(char)) {
- return {
- token: { type: 'punct', value: char, start: i, end: i + 1 },
- nextIndex: i + 1,
- };
- }
- return null;
+/**
+ * Fallback tokenizer for characters not matched by any other tokenizer.
+ * Emits them as word tokens so they are preserved in the AST rather than silently dropped.
+ * This handles non-Latin Unicode text (CJK, emoji, etc.) and any other unrecognized characters.
+ */
+function tokenizeFallback(char: string, i: number): TokenizeResult {
+ return {
+ token: { type: 'word', value: char, start: i, end: i + 1 },
+ nextIndex: i + 1,
+ };
}
+// #region Parser
+
/**
* Convert tokens into an AST.
* @param tokens Token[]
@@ -233,10 +281,373 @@ export function parseTokens(tokens: Token[]): ASTNode[] {
return tokens[pos];
}
+ function peekAt(offset: number): Token | undefined {
+ return tokens[pos + offset];
+ }
+
function consume(): Token | undefined {
return tokens[pos++];
}
+ /**
+ * Quick lookahead check: does the current lparen (already consumed) start a quoted prompt function?
+ * A quoted prompt function looks like ('...', '...').method(...)
+ * We check if the first non-whitespace token after lparen is a quote character.
+ */
+ function isQuotedPromptFunctionAhead(): boolean {
+ let p = 0;
+ while (peekAt(p)?.type === 'whitespace') {
+ p++;
+ }
+ const t = peekAt(p);
+ return t?.type === 'punct' && OPEN_QUOTE_CHARS.has(tokenValue(t)!);
+ }
+
+ /**
+ * Lookahead check: does the current lparen (already consumed) start an unquoted prompt function?
+ * An unquoted prompt function looks like (arg1, arg2).method(...) where args are not quoted.
+ * We scan forward looking for a comma at the same nesting depth, then rparen followed by .word(
+ */
+ function isUnquotedPromptFunctionAhead(): boolean {
+ let p = 0;
+ let depth = 0;
+ let hasComma = false;
+
+ // Scan forward through tokens to find the matching rparen
+ while (peekAt(p)) {
+ const t = peekAt(p)!;
+
+ if (t.type === 'lparen') {
+ depth++;
+ } else if (t.type === 'rparen') {
+ if (depth === 0) {
+ // Found matching rparen — now check for .methodName( pattern
+ // (possibly with whitespace between ) and .)
+ if (!hasComma) {
+ return false; // No comma means it's just a regular group
+ }
+ let next = p + 1;
+ while (peekAt(next)?.type === 'whitespace') {
+ next++;
+ }
+ return (
+ isPunctValue(peekAt(next), '.') && peekAt(next + 1)?.type === 'word' && peekAt(next + 2)?.type === 'lparen'
+ );
+ }
+ depth--;
+ } else if (isPunctValue(t, ',') && depth === 0) {
+ hasComma = true;
+ }
+
+ p++;
+ }
+ return false;
+ }
+
+ /**
+ * Parse the `.methodName(params)` suffix that follows the closing rparen of a prompt function.
+ * Assumes whitespace has already been skipped. Returns null and restores pos if the pattern
+ * doesn't match.
+ */
+ function tryParseMethodTail(savedPos: number): { name: string; functionParams: string; endPos: number } | null {
+ // Skip whitespace between ) and .methodName (allows newlines)
+ while (peek()?.type === 'whitespace') {
+ consume();
+ }
+
+ // Expect .methodName(params)
+ if (!isPunctValue(peek(), '.')) {
+ pos = savedPos;
+ return null;
+ }
+ consume(); // consume dot
+
+ if (peek()?.type !== 'word') {
+ pos = savedPos;
+ return null;
+ }
+ const methodName = tokenValue(consume())!;
+
+ // Expect opening paren for method call
+ if (peek()?.type !== 'lparen') {
+ pos = savedPos;
+ return null;
+ }
+ consume(); // consume method open paren
+
+ // Collect method params until closing rparen
+ let functionParams = '';
+ while (pos < tokens.length) {
+ const t = peek()!;
+ if (t.type === 'rparen') {
+ break;
+ }
+ const tok = consume()!;
+ const v = tokenValue(tok);
+ if (v !== undefined) {
+ functionParams += v;
+ }
+ }
+
+ // Expect closing rparen for method call
+ if (peek()?.type !== 'rparen') {
+ pos = savedPos;
+ return null;
+ }
+ const methodCloseParen = consume()!; // consume method close paren
+
+ return { name: methodName, functionParams, endPos: methodCloseParen.end };
+ }
+
+ /**
+ * Try to parse a prompt function starting after the opening lparen.
+ * Returns the PromptFunctionNode if successful, or null if the pattern doesn't match
+ * (in which case `pos` is restored to `savedPos`).
+ */
+ function tryParsePromptFunction(lparenToken: Token & { type: 'lparen' }, savedPos: number): ASTNode | null {
+ const args: PromptFunctionArg[] = [];
+ let openQuoteChar: string | null = null;
+ let closeQuoteChar: string | null = null;
+ let pendingSeparator: string | undefined;
+
+ while (pos < tokens.length) {
+ // Skip whitespace before arg or closing paren
+ while (peek()?.type === 'whitespace') {
+ consume();
+ }
+
+ // Check for rparen (end of prompt function args)
+ if (peek()?.type === 'rparen') {
+ break;
+ }
+
+ // Expect comma separator between args
+ if (args.length > 0) {
+ if (isPunctValue(peek(), ',')) {
+ consume();
+ let sep = '';
+ while (peek()?.type === 'whitespace') {
+ const sepToken = consume()!;
+ const sepValue = tokenValue(sepToken);
+ if (sepValue !== undefined) {
+ sep += sepValue;
+ }
+ }
+ pendingSeparator = sep;
+ } else {
+ pos = savedPos;
+ return null;
+ }
+ }
+
+ // Expect opening quote
+ const openQuoteTok = peek();
+ if (!openQuoteTok || openQuoteTok.type !== 'punct') {
+ pos = savedPos;
+ return null;
+ }
+ const thisOpenQuote = tokenValue(openQuoteTok)!;
+ if (!OPEN_QUOTE_CHARS.has(thisOpenQuote)) {
+ pos = savedPos;
+ return null;
+ }
+
+ const thisCloseQuote = CLOSE_QUOTE_MAP[thisOpenQuote]!;
+ if (openQuoteChar === null) {
+ openQuoteChar = thisOpenQuote;
+ closeQuoteChar = thisCloseQuote;
+ } else if (thisOpenQuote !== openQuoteChar) {
+ // Mismatched quote style between args
+ pos = savedPos;
+ return null;
+ }
+
+ consume(); // consume opening quote
+ const contentStart = openQuoteTok.end;
+
+ // Collect tokens until closing quote
+ const argTokens: Token[] = [];
+ let contentEnd = contentStart;
+ while (pos < tokens.length) {
+ const t = peek();
+ if (isPunctValue(t, closeQuoteChar!)) {
+ contentEnd = t!.start;
+ break;
+ }
+ const consumed = consume()!;
+ argTokens.push(consumed);
+ contentEnd = consumed.end;
+ }
+
+ // Expect closing quote
+ if (!isPunctValue(peek(), closeQuoteChar!)) {
+ pos = savedPos;
+ return null;
+ }
+ consume(); // consume closing quote
+
+ // Parse sub-tokens as AST
+ const argNodes = parseTokens(argTokens);
+
+ args.push({
+ nodes: argNodes,
+ quote: openQuoteChar,
+ contentRange: { start: contentStart, end: contentEnd },
+ separator: pendingSeparator,
+ });
+ pendingSeparator = undefined;
+ }
+
+ if (args.length === 0) {
+ pos = savedPos;
+ return null;
+ }
+
+ // Expect rparen
+ if (peek()?.type !== 'rparen') {
+ pos = savedPos;
+ return null;
+ }
+ consume(); // consume rparen
+
+ // Parse .methodName(params) suffix
+ const methodTail = tryParseMethodTail(savedPos);
+ if (!methodTail) {
+ return null; // pos already restored by tryParseMethodTail
+ }
+
+ return {
+ type: 'prompt_function',
+ name: methodTail.name,
+ promptArgs: args,
+ functionParams: methodTail.functionParams,
+ range: { start: lparenToken.start, end: methodTail.endPos },
+ };
+ }
+
+ /**
+ * Try to parse an unquoted prompt function starting after the opening lparen.
+ * Unquoted prompt functions look like (arg1 words, arg2 words).method(params)
+ * where arguments are separated by commas without quotes.
+ * Returns the PromptFunctionNode if successful, or null if the pattern doesn't match
+ * (in which case `pos` is restored to `savedPos`).
+ */
+ function tryParseUnquotedPromptFunction(lparenToken: Token & { type: 'lparen' }, savedPos: number): ASTNode | null {
+ const args: PromptFunctionArg[] = [];
+ let pendingSeparator: string | undefined;
+
+ while (pos < tokens.length) {
+ // Check for rparen (end of prompt function args)
+ if (peek()?.type === 'rparen') {
+ break;
+ }
+
+ // Expect comma separator between args (consume the comma)
+ if (args.length > 0) {
+ if (isPunctValue(peek(), ',')) {
+ consume(); // consume comma
+ let sep = '';
+ while (peek()?.type === 'whitespace') {
+ const sepToken = consume()!;
+ const sepValue = tokenValue(sepToken);
+ if (sepValue !== undefined) {
+ sep += sepValue;
+ }
+ }
+ pendingSeparator = sep;
+ } else {
+ pos = savedPos;
+ return null;
+ }
+ }
+
+ // Collect tokens until comma or rparen (at nesting depth 0)
+ const argTokens: Token[] = [];
+ let contentStart: number | null = null;
+ let contentEnd: number | null = null;
+ let depth = 0;
+
+ while (pos < tokens.length) {
+ const t = peek()!;
+
+ if (t.type === 'lparen') {
+ depth++;
+ } else if (t.type === 'rparen') {
+ if (depth === 0) {
+ break; // End of all args
+ }
+ depth--;
+ } else if (isPunctValue(t, ',') && depth === 0) {
+ break; // End of this arg
+ }
+
+ if (contentStart === null) {
+ contentStart = t.start;
+ }
+ const consumed = consume()!;
+ argTokens.push(consumed);
+ contentEnd = consumed.end;
+ }
+
+ if (argTokens.length === 0) {
+ pos = savedPos;
+ return null;
+ }
+
+ // Trim leading/trailing whitespace tokens from the arg content
+ let firstNonWs = 0;
+ while (firstNonWs < argTokens.length && argTokens[firstNonWs]!.type === 'whitespace') {
+ firstNonWs++;
+ }
+ let lastNonWs = argTokens.length - 1;
+ while (lastNonWs >= 0 && argTokens[lastNonWs]!.type === 'whitespace') {
+ lastNonWs--;
+ }
+
+ const trimmedArgTokens = argTokens.slice(firstNonWs, lastNonWs + 1);
+ const trimmedStart = trimmedArgTokens.length > 0 ? trimmedArgTokens[0]!.start : contentStart!;
+ const trimmedEnd = trimmedArgTokens.length > 0 ? trimmedArgTokens[trimmedArgTokens.length - 1]!.end : contentEnd!;
+
+ // Parse sub-tokens as AST
+ const argNodes = parseTokens(trimmedArgTokens);
+
+ args.push({
+ nodes: argNodes,
+ quote: '', // Unquoted
+ contentRange: { start: trimmedStart, end: trimmedEnd },
+ separator: pendingSeparator,
+ });
+ pendingSeparator = undefined;
+ }
+
+ if (args.length < 2) {
+ // An unquoted prompt function must have at least 2 args (otherwise it's a regular group)
+ pos = savedPos;
+ return null;
+ }
+
+ // Expect rparen
+ if (peek()?.type !== 'rparen') {
+ pos = savedPos;
+ return null;
+ }
+ consume(); // consume rparen
+
+ // Parse .methodName(params) suffix
+ const methodTail = tryParseMethodTail(savedPos);
+ if (!methodTail) {
+ return null; // pos already restored by tryParseMethodTail
+ }
+
+ return {
+ type: 'prompt_function',
+ name: methodTail.name,
+ promptArgs: args,
+ functionParams: methodTail.functionParams,
+ range: { start: lparenToken.start, end: methodTail.endPos },
+ };
+ }
+
function parseGroup(): ASTNode[] {
const nodes: ASTNode[] = [];
@@ -254,6 +665,30 @@ export function parseTokens(tokens: Token[]): ASTNode[] {
}
case 'lparen': {
const lparen = consume() as Token & { type: 'lparen' };
+
+ // Try to parse as a quoted prompt function first
+ if (isQuotedPromptFunctionAhead()) {
+ const savedPos = pos;
+ const pfResult = tryParsePromptFunction(lparen, savedPos);
+ if (pfResult) {
+ nodes.push(pfResult);
+ break;
+ }
+ // pos was restored by tryParsePromptFunction on failure
+ }
+
+ // Try to parse as an unquoted prompt function
+ if (isUnquotedPromptFunctionAhead()) {
+ const savedPos = pos;
+ const pfResult = tryParseUnquotedPromptFunction(lparen, savedPos);
+ if (pfResult) {
+ nodes.push(pfResult);
+ break;
+ }
+ // pos was restored by tryParseUnquotedPromptFunction on failure
+ }
+
+ // Regular group parsing
const groupChildren = parseGroup();
let attention: Attention | undefined;
@@ -283,10 +718,10 @@ export function parseTokens(tokens: Token[]): ASTNode[] {
let end = lembed.end;
while (peek() && peek()!.type !== 'rembed') {
const embedToken = consume()!;
- embedValue +=
- embedToken.type === 'word' || embedToken.type === 'punct' || embedToken.type === 'whitespace'
- ? embedToken.value
- : '';
+ const v = tokenValue(embedToken);
+ if (v !== undefined) {
+ embedValue += v;
+ }
end = embedToken.end;
}
if (peek()?.type === 'rembed') {
@@ -341,47 +776,131 @@ export function parseTokens(tokens: Token[]): ASTNode[] {
return parseGroup();
}
+// #region Serialization
+
/**
- * Convert an AST back into a prompt string.
- * @param ast ASTNode[]
- * @returns string
+ * Visitor callbacks for AST serialization. All callbacks are optional.
+ * Called during traversal to allow tracking node positions in the output string.
*/
-export function serialize(ast: ASTNode[]): string {
- let prompt = '';
+type SerializeVisitor = {
+ /** Called after a node has been fully serialized, with its start and end positions in the output. */
+ onNode?: (node: ASTNode, start: number, end: number) => void;
+};
+
+/** Mutable buffer used by serializeCore so all recursive calls share the same position tracking. */
+type SerializeBuffer = { prompt: string };
+/**
+ * Shared serialization core. Converts an AST back into a prompt string,
+ * optionally calling visitor hooks for position tracking.
+ *
+ * Uses a shared mutable buffer so that node positions reported via
+ * `visitor.onNode` are always absolute offsets in the final output string,
+ * even for nodes nested inside groups or prompt function args.
+ */
+function serializeCore(ast: ASTNode[], visitor: SerializeVisitor | undefined, buf: SerializeBuffer): void {
for (const node of ast) {
+ const nodeStart = buf.prompt.length;
+
switch (node.type) {
case 'punct':
case 'whitespace': {
- prompt += node.value;
+ buf.prompt += node.value;
break;
}
case 'escaped_paren': {
- prompt += `\\${node.value}`;
+ buf.prompt += `\\${node.value}`;
break;
}
case 'word': {
- prompt += node.text;
+ buf.prompt += node.text;
if (node.attention) {
- prompt += String(node.attention);
+ buf.prompt += String(node.attention);
}
break;
}
case 'group': {
- prompt += '(';
- prompt += serialize(node.children);
- prompt += ')';
+ buf.prompt += '(';
+ serializeCore(node.children, visitor, buf);
+ buf.prompt += ')';
if (node.attention) {
- prompt += String(node.attention);
+ buf.prompt += String(node.attention);
}
break;
}
case 'embedding': {
- prompt += `<${node.value}>`;
+ buf.prompt += `<${node.value}>`;
+ break;
+ }
+ case 'prompt_function': {
+ buf.prompt += '(';
+ for (let i = 0; i < node.promptArgs.length; i++) {
+ if (i > 0) {
+ const sep = node.promptArgs[i]!.separator ?? ' ';
+ buf.prompt += `,${sep}`;
+ }
+ const arg = node.promptArgs[i]!;
+ buf.prompt += arg.quote;
+ serializeCore(arg.nodes, visitor, buf);
+ buf.prompt += CLOSE_QUOTE_MAP[arg.quote] ?? arg.quote;
+ }
+ buf.prompt += ').';
+ buf.prompt += node.name;
+ buf.prompt += '(';
+ buf.prompt += node.functionParams;
+ buf.prompt += ')';
break;
}
}
+
+ visitor?.onNode?.(node, nodeStart, buf.prompt.length);
+ }
+}
+
+/**
+ * Convert an AST back into a prompt string.
+ * @param ast ASTNode[]
+ * @returns string
+ */
+export function serialize(ast: ASTNode[]): string {
+ const buf: SerializeBuffer = { prompt: '' };
+ serializeCore(ast, undefined, buf);
+ return buf.prompt;
+}
+
+/**
+ * Serialize an AST to a prompt string while simultaneously computing the
+ * selection range from `isSelection` flags on nodes.
+ *
+ * This is more reliable than separate serialize + selection computation because
+ * the position tracking is guaranteed to match the serialized output.
+ */
+export function serializeWithSelection(ast: ASTNode[]): {
+ prompt: string;
+ selectionStart: number;
+ selectionEnd: number;
+} {
+ let selStart = Infinity;
+ let selEnd = -1;
+
+ const buf: SerializeBuffer = { prompt: '' };
+ serializeCore(
+ ast,
+ {
+ onNode(node, start, end) {
+ if (node.isSelection) {
+ selStart = Math.min(selStart, start);
+ selEnd = Math.max(selEnd, end);
+ }
+ },
+ },
+ buf
+ );
+
+ if (selStart === Infinity) {
+ selStart = 0;
+ selEnd = buf.prompt.length;
}
- return prompt;
+ return { prompt: buf.prompt, selectionStart: selStart, selectionEnd: selEnd };
}
diff --git a/invokeai/frontend/web/src/common/util/promptAttention.test.ts b/invokeai/frontend/web/src/common/util/promptAttention.test.ts
index ce3e8208ee..6e165872ec 100644
--- a/invokeai/frontend/web/src/common/util/promptAttention.test.ts
+++ b/invokeai/frontend/web/src/common/util/promptAttention.test.ts
@@ -2,170 +2,706 @@ import { describe, expect, it } from 'vitest';
import { adjustPromptAttention } from './promptAttention';
+/**
+ * Helper: select by substring match within the prompt.
+ * If `selected` is a string, finds it in the prompt and uses its position.
+ * If `selected` is a [start, end] tuple, uses those positions directly.
+ */
+function adj(
+ prompt: string,
+ selected: string | [number, number],
+ direction: 'increment' | 'decrement',
+ prefersNumericWeights = false
+) {
+ const [start, end] =
+ typeof selected === 'string' ? [prompt.indexOf(selected), prompt.indexOf(selected) + selected.length] : selected;
+ return adjustPromptAttention(prompt, start, end, direction, prefersNumericWeights);
+}
+
+/** Helper that calls adj with prefersNumericWeights=true */
+function adjNumeric(prompt: string, selected: string | [number, number], direction: 'increment' | 'decrement') {
+ return adj(prompt, selected, direction, true);
+}
+
describe('adjustPromptAttention', () => {
- describe('cross-boundary selection', () => {
- it('should split group and apply attention when selection spans from inside group to outside (increment)', () => {
- const prompt = '(a b)+ c';
- const result = adjustPromptAttention(prompt, 3, 8, 'increment');
+ // Basic Attention
+
+ describe('single word', () => {
+ 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)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adj(prompt, selected, direction).prompt).toBe(expected);
+ });
+ });
+
+ describe('multiple words', () => {
+ it.each([
+ ['hello world', [0, 11] as [number, number], 'increment', '(hello world)+'],
+ ['hello world', [0, 11] as [number, number], 'decrement', '(hello world)-'],
+ ] as const)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adj(prompt, selected, direction).prompt).toBe(expected);
+ });
+ });
+
+ describe('cursor at word-punctuation boundary', () => {
+ it('should select word, not punctuation, when cursor is between word and comma', () => {
+ // "one|, two" — cursor at position 3, between "one" (0-3) and "," (3-4)
+ expect(adj('one, two', [3, 3], 'increment').prompt).toBe('one+, two');
+ });
+
+ it('should select word, not punctuation, when cursor is between word and period', () => {
+ expect(adj('one. two', [3, 3], 'increment').prompt).toBe('one+. two');
+ });
+
+ it('should select word when cursor is at start of word after punctuation', () => {
+ // "one, |two" — cursor at position 5, between " " (4-5) and "two" (5-8)
+ expect(adj('one, two', [5, 5], 'increment').prompt).toBe('one, two+');
+ });
+
+ it('should still select punctuation when cursor is only touching punctuation', () => {
+ // Cursor in the middle of a run of punctuation with no adjacent word
+ // e.g. "one ,, two" cursor at position 5 — between "," (4-5) and "," (5-6)
+ // Both neighbors are punct, so no word to prefer — should still work
+ const result = adj('one ,, two', [5, 5], 'increment');
+ expect(result).toBeDefined();
+ });
+ });
+
+ // Existing Groups
- expect(result.prompt).toBe('(a b+ c)+');
+ describe('existing groups', () => {
+ it('should increment group when cursor is at group boundary', () => {
+ expect(adj('(hello world)+', [13, 14], 'increment').prompt).toBe('(hello world)++');
});
- it('should split group and apply attention when selection spans from inside group to outside (decrement)', () => {
- const prompt = '(a b)+ c';
- const result = adjustPromptAttention(prompt, 3, 8, 'decrement');
+ it('should remove group when attention becomes neutral', () => {
+ expect(adj('(hello world)+', [0, 14], 'decrement').prompt).toBe('hello world');
+ });
- expect(result.prompt).toBe('a+ b c-');
+ it('should increment inner word within group', () => {
+ const result = adj('(a b)+', [1, 2], 'increment');
+ expect(result.prompt).toBe('(a+ b)+');
});
+ });
- it('should split group when selection starts before group and ends inside (increment)', () => {
- const prompt = 'a (b c)+';
- const result = adjustPromptAttention(prompt, 0, 4, 'increment');
+ // Cross-Boundary Selection
- expect(result.prompt).toBe('(a b+ c)+');
+ describe('cross-boundary selection', () => {
+ it.each([
+ // Selection from inside group to outside
+ ['(a b)+ c', [3, 8], 'increment', '(a b+ c)+'],
+ ['(a b)+ c', [3, 8], 'decrement', 'a+ b c-'],
+ // Selection from outside to inside group
+ ['a (b c)+', [0, 4], 'increment', '(a b+ c)+'],
+ ['a (b c)+', [0, 4], 'decrement', 'a- b c+'],
+ // Nested groups
+ ['((a b)+)+ c', [2, 11], 'increment', '((a b)++ c)+'],
+ ['((a b)+)+ c', [2, 11], 'decrement', '(a b)+ c-'],
+ // Spanning multiple groups
+ ['(a)+ (b)+', [0, 9], 'increment', '(a b)++'],
+ ['(a)+ (b)+', [0, 9], 'decrement', 'a b'],
+ // Negative groups
+ ['(a b)- c', [3, 8], 'decrement', '(a b- c)-'],
+ ['(a b)- c', [3, 8], 'increment', 'a- b c+'],
+ // Multiple non-selected items in group
+ ['(a b c)+ d', [5, 10], 'decrement', '(a b)+ c d-'],
+ // Word with existing attention crossing boundary
+ ['c (d- e)+', [0, 5], 'increment', 'c+ d e+'],
+ // Complex multi-group
+ ['(a+ b)+ c (d- e)+', [8, 14], 'increment', '(a+ b c)+ d e+'],
+ ] as const)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adj(prompt, selected as string | [number, number], direction).prompt).toBe(expected);
});
+ });
- it('should split group when selection starts before group and ends inside (decrement)', () => {
- const prompt = 'a (b c)+';
- const result = adjustPromptAttention(prompt, 0, 4, 'decrement');
+ // Selection Preservation
- expect(result.prompt).toBe('a- b c+');
+ describe('selection preservation', () => {
+ it('should track selection when incrementing single word', () => {
+ const result = adj('hello world', 'hello', 'increment');
+ expect(result.prompt).toBe('hello+ world');
+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('hello+');
});
- it('should handle nested groups with cross-boundary selection (increment)', () => {
- const prompt = '((a b)+)+ c';
- const result = adjustPromptAttention(prompt, 2, 11, 'increment');
+ it('should track selection when incrementing full group', () => {
+ const result = adj('(hello world)+', [0, 14], 'increment');
+ expect(result.prompt).toBe('(hello world)++');
+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('(hello world)++');
+ });
- expect(result.prompt).toBe('((a b)++ c)+');
+ it('should track selection when splitting group', () => {
+ const result = adj('(a b)+', [1, 2], 'increment');
+ expect(result.prompt).toBe('(a+ b)+');
+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('a+');
});
+ });
- it('should handle nested groups with cross-boundary selection (decrement)', () => {
- const prompt = '((a b)+)+ c';
- const result = adjustPromptAttention(prompt, 2, 11, 'decrement');
+ // Numeric Attention Weights
+
+ describe('numeric attention weights', () => {
+ it.each([
+ // Increment / decrement numeric weights with additive step
+ ['(masterpiece)1.3', [0, 16], 'increment', '(masterpiece)1.4'],
+ ['(masterpiece)1.3', [0, 16], 'decrement', '(masterpiece)1.2'],
+ ['(high detail)1.2', [0, 16], 'increment', '(high detail)1.3'],
+ ['(sunny midday light)1.15', [0, 24], 'increment', '(sunny midday light)1.25'],
+ ['(sunny midday light)1.15', [0, 24], 'decrement', '(sunny midday light)1.05'],
+ ] as const)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adj(prompt, selected as [number, number], direction).prompt).toBe(expected);
+ });
+
+ it('should preserve non-selected numeric weights when adjusting elsewhere', () => {
+ const prompt = '(masterpiece)1.3, best quality';
+ const result = adj(prompt, 'best quality', 'increment');
+ expect(result.prompt).toContain('(masterpiece)1.3');
+ expect(result.prompt).not.toContain('masterpiece1.3');
+ });
- expect(result.prompt).toBe('(a b)+ c-');
+ it('should not produce floating point garbage', () => {
+ const prompt = '(high detail)1.2, oil painting';
+ const result = adj(prompt, 'oil painting', 'increment');
+ expect(result.prompt).toContain('(high detail)1.2');
+ expect(result.prompt).not.toMatch(/1\.19999/);
+ expect(result.prompt).not.toMatch(/1\.20000/);
});
- it('should handle selection spanning multiple groups (increment)', () => {
- const prompt = '(a)+ (b)+';
- const result = adjustPromptAttention(prompt, 0, 9, 'increment');
+ it('should preserve numeric weight 1.15 without corruption', () => {
+ const prompt = '(sunny midday light)1.15, landscape';
+ const result = adj(prompt, 'landscape', 'increment');
+ expect(result.prompt).toContain('(sunny midday light)1.15');
+ expect(result.prompt).not.toMatch(/1\.15005/);
+ });
- expect(result.prompt).toBe('(a b)++');
+ it('should normalize numeric 1.1 weight to + syntax', () => {
+ const prompt = '(lush rolling hills)1.1, landscape';
+ const result = adj(prompt, 'landscape', 'increment');
+ expect(result.prompt).toMatch(/\(lush rolling hills\)(\+|1\.1)/);
});
- it('should handle selection spanning multiple groups (decrement)', () => {
- const prompt = '(a)+ (b)+';
- const result = adjustPromptAttention(prompt, 0, 9, 'decrement');
+ it('should handle the full complex prompt without corrupting non-selected weights', () => {
+ const prompt =
+ '(masterpiece)1.3, best quality, (high detail)1.2, oil painting, (sunny midday light)1.15, an old stone castle standing on a hill, medieval architecture, weathered stone walls, (lush rolling hills)1.1, expansive landscape, clear blue sky';
+ const result = adj(prompt, 'clear blue sky', 'increment');
- expect(result.prompt).toBe('a b');
+ expect(result.prompt).toContain('(masterpiece)1.3');
+ expect(result.prompt).toContain('(high detail)1.2');
+ expect(result.prompt).toContain('(sunny midday light)1.15');
+ expect(result.prompt).toContain('(clear blue sky)+');
+ expect(result.prompt).not.toMatch(/\d\.\d{5,}/);
});
+ });
- it('should split negative group correctly (decrement on negative group)', () => {
- const prompt = '(a b)- c';
- const result = adjustPromptAttention(prompt, 3, 8, 'decrement');
+ // Prompt Functions
+
+ describe('prompt functions', () => {
+ describe('within a single argument', () => {
+ it.each([
+ // Single word inside an arg
+ ["('hello world', 'other').and()", 'hello', 'increment', "('hello+ world', 'other').and()"],
+ ["('hello world', 'other').and()", 'hello', 'decrement', "('hello- world', 'other').and()"],
+ // Multiple words in second arg
+ ["('a', 'hello world').or()", 'hello world', 'increment', "('a', '(hello world)+').or()"],
+ ["('a', 'hello world').or()", 'hello world', 'decrement', "('a', '(hello world)-').or()"],
+ // Single word in .blend()
+ ["('one two', 'three four').blend(0.7, 0.3)", 'two', 'increment', "('one two+', 'three four').blend(0.7, 0.3)"],
+ ] as const)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adj(prompt, selected, direction).prompt).toBe(expected);
+ });
+ });
- expect(result.prompt).toBe('(a b- c)-');
+ describe('across argument separator', () => {
+ it('should adjust both args simultaneously when selection spans separator (increment)', () => {
+ const prompt = "('one two', 'three four').and()";
+ // Select across the separator: "two', 'three"
+ 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()");
+ });
+
+ it('should adjust both args simultaneously when selection spans separator (decrement)', () => {
+ 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, 'decrement');
+ expect(result.prompt).toBe("('one two-', 'three- four').and()");
+ });
+
+ it('should adjust across separator for .or()', () => {
+ const prompt = "('alpha beta', 'gamma delta').or()";
+ const start = prompt.indexOf('beta');
+ const end = prompt.indexOf('gamma') + 'gamma'.length;
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toBe("('alpha beta+', 'gamma+ delta').or()");
+ });
+
+ it('should adjust across separator for .blend() preserving params', () => {
+ const prompt = "('one two', 'three four').blend(0.7, 0.3)";
+ 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').blend(0.7, 0.3)");
+ });
+
+ it('should handle repeated increment across separator', () => {
+ const prompt = "('one two+', 'three+ four').and()";
+ const start = prompt.indexOf('two');
+ const end = prompt.indexOf('three') + 'three'.length;
+ // "two+" is at the boundary, "three+" is at the boundary
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toBe("('one two++', 'three++ four').and()");
+ });
});
- it('should split negative group correctly (increment on negative group)', () => {
- const prompt = '(a b)- c';
- const result = adjustPromptAttention(prompt, 3, 8, 'increment');
+ describe('whole function selected', () => {
+ it('should increment all content in all args when whole function is selected', () => {
+ const prompt = "('one', 'two').and()";
+ const result = adjustPromptAttention(prompt, 0, prompt.length, 'increment');
+ expect(result.prompt).toBe("('one+', 'two+').and()");
+ });
+
+ it('should decrement all content in all args', () => {
+ const prompt = "('one', 'two').and()";
+ const result = adjustPromptAttention(prompt, 0, prompt.length, 'decrement');
+ expect(result.prompt).toBe("('one-', 'two-').and()");
+ });
+
+ it('should increment all args of .blend() preserving params', () => {
+ const prompt = "('one', 'two').blend(0.7, 0.3)";
+ const result = adjustPromptAttention(prompt, 0, prompt.length, 'increment');
+ expect(result.prompt).toBe("('one+', 'two+').blend(0.7, 0.3)");
+ });
+ });
- expect(result.prompt).toBe('a- b c+');
+ describe('prompt function embedded in larger prompt', () => {
+ it('should adjust only the targeted region outside the function', () => {
+ const prompt = "some text, ('a', 'b').and(), more text";
+ const result = adj(prompt, 'some', 'increment');
+ expect(result.prompt).toContain('some+');
+ expect(result.prompt).toContain("('a', 'b').and()");
+ });
+
+ it('should adjust only the targeted region inside the function', () => {
+ const prompt = "prefix ('alpha beta', 'gamma').and() suffix";
+ const result = adj(prompt, 'alpha', 'increment');
+ expect(result.prompt).toContain("'alpha+ beta'");
+ expect(result.prompt).toContain('prefix');
+ expect(result.prompt).toContain('suffix');
+ });
+
+ it('should adjust text outside and inside function when selection spans boundary', () => {
+ const prompt = "text ('one two', 'three').and()";
+ // Select from 'text' through 'one'
+ const start = prompt.indexOf('text');
+ const end = prompt.indexOf('one') + 'one'.length;
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toContain('text+');
+ expect(result.prompt).toContain("'one+ two'");
+ });
});
- it('should handle multiple non-selected items in group', () => {
- const prompt = '(a b c)+ d';
- const result = adjustPromptAttention(prompt, 5, 10, 'decrement');
+ describe('prompt function with existing attention inside args', () => {
+ it('should further increment already-weighted word inside arg', () => {
+ const prompt = "('hello+', 'world').and()";
+ // Select hello+ (the word with its weight marker)
+ const result = adj(prompt, 'hello+', 'increment');
+ expect(result.prompt).toBe("('hello++', 'world').and()");
+ });
+
+ it('should cancel attention to neutral inside arg', () => {
+ const prompt = "('hello+', 'world').and()";
+ const result = adj(prompt, 'hello+', 'decrement');
+ expect(result.prompt).toBe("('hello', 'world').and()");
+ });
+
+ it('should handle group attention inside arg', () => {
+ const prompt = "('(a b)+', 'c').and()";
+ // Select everything in first arg
+ const start = prompt.indexOf('(a b)+');
+ const end = start + '(a b)+'.length;
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toBe("('(a b)++', 'c').and()");
+ });
+ });
- expect(result.prompt).toBe('(a b)+ c d-');
+ describe('three-arg prompt functions', () => {
+ it('should adjust a word in one arg of a three-arg blend', () => {
+ const prompt = "('a', 'b', 'c').blend(0.5, 0.3, 0.2)";
+ const result = adj(prompt, 'b', 'increment');
+ expect(result.prompt).toBe("('a', 'b+', 'c').blend(0.5, 0.3, 0.2)");
+ });
+
+ it('should adjust across two separators in a three-arg blend', () => {
+ const prompt = "('aa bb', 'cc dd', 'ee ff').blend(0.5, 0.3, 0.2)";
+ // Select from bb through ee
+ const start = prompt.indexOf('bb');
+ const end = prompt.indexOf('ee') + 'ee'.length;
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toBe("('aa bb+', '(cc dd)+', 'ee+ ff').blend(0.5, 0.3, 0.2)");
+ });
});
- it('should handle word with existing attention in group when crossing boundary', () => {
- const prompt = 'c (d- e)+';
- const result = adjustPromptAttention(prompt, 0, 5, 'increment');
+ describe('unquoted prompt functions', () => {
+ it('should increment a word in unquoted .and()', () => {
+ const prompt = '(one, two).and()';
+ const result = adj(prompt, 'one', 'increment');
+ expect(result.prompt).toBe('(one+, two).and()');
+ });
+
+ it('should decrement a word in unquoted .and()', () => {
+ const prompt = '(one, two).and()';
+ const result = adj(prompt, 'one', 'decrement');
+ expect(result.prompt).toBe('(one-, two).and()');
+ });
+
+ it('should increment a word in unquoted multi-word arg', () => {
+ const prompt = '(hello world, foo bar).and()';
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe('(hello+ world, foo bar).and()');
+ });
+
+ it('should increment all args when whole unquoted function is selected', () => {
+ const prompt = '(one, two).and()';
+ const result = adjustPromptAttention(prompt, 0, prompt.length, 'increment');
+ expect(result.prompt).toBe('(one+, two+).and()');
+ });
+
+ it('should preserve unquoted prompt function when adjusting text outside', () => {
+ const prompt = 'prefix (a, b).and() suffix';
+ const result = adj(prompt, 'prefix', 'increment');
+ expect(result.prompt).toContain('(a, b).and()');
+ expect(result.prompt).toContain('prefix+');
+ });
+
+ it('should handle unquoted .blend() with params', () => {
+ const prompt = '(one two, three four).blend(0.7, 0.3)';
+ const result = adj(prompt, 'one', 'increment');
+ expect(result.prompt).toBe('(one+ two, three four).blend(0.7, 0.3)');
+ });
+
+ it('should adjust across separator in unquoted prompt function', () => {
+ 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).toBe('c+ d e+');
+ describe('curly-quoted prompt functions', () => {
+ it('should increment a word inside curly double-quoted arg', () => {
+ const prompt = '(\u201chello world\u201d, \u201cother\u201d).and()';
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe('(\u201chello+ world\u201d, \u201cother\u201d).and()');
+ });
+
+ it('should decrement a word inside curly double-quoted arg', () => {
+ const prompt = '(\u201chello world\u201d, \u201cother\u201d).and()';
+ const result = adj(prompt, 'hello', 'decrement');
+ expect(result.prompt).toBe('(\u201chello- world\u201d, \u201cother\u201d).and()');
+ });
+
+ it('should increment a word inside curly single-quoted arg', () => {
+ const prompt = '(\u2018hello world\u2019, \u2018other\u2019).and()';
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe('(\u2018hello+ world\u2019, \u2018other\u2019).and()');
+ });
+
+ it('should increment all args when whole curly-quoted function is selected', () => {
+ const prompt = '(\u201cone\u201d, \u201ctwo\u201d).and()';
+ const result = adjustPromptAttention(prompt, 0, prompt.length, 'increment');
+ expect(result.prompt).toBe('(\u201cone+\u201d, \u201ctwo+\u201d).and()');
+ });
+
+ it('should adjust across separator in curly double-quoted prompt function', () => {
+ const prompt = '(\u201cone two\u201d, \u201cthree four\u201d).and()';
+ const start = prompt.indexOf('two');
+ const end = prompt.indexOf('three') + 'three'.length;
+ const result = adjustPromptAttention(prompt, start, end, 'increment');
+ expect(result.prompt).toBe('(\u201cone two+\u201d, \u201cthree+ four\u201d).and()');
+ });
+
+ it('should preserve curly-quoted function when adjusting text outside', () => {
+ const prompt = 'prefix (\u201ca\u201d, \u201cb\u201d).and() suffix';
+ const result = adj(prompt, 'prefix', 'increment');
+ expect(result.prompt).toContain('(\u201ca\u201d, \u201cb\u201d).and()');
+ expect(result.prompt).toContain('prefix+');
+ });
+
+ it('should handle curly-quoted .blend() with params', () => {
+ const prompt = '(\u201cone two\u201d, \u201cthree four\u201d).blend(0.7, 0.3)';
+ const result = adj(prompt, 'one', 'increment');
+ expect(result.prompt).toBe('(\u201cone+ two\u201d, \u201cthree four\u201d).blend(0.7, 0.3)');
+ });
});
- it('should handle complex multi-group case', () => {
- const prompt = '(a+ b)+ c (d- e)+';
- const result = adjustPromptAttention(prompt, 8, 14, 'increment');
+ describe('newline before .method()', () => {
+ it('should increment a word in quoted prompt function with newline before .method()', () => {
+ const prompt = "('hello world', 'other')\n.and()";
+ const result = adj(prompt, 'hello', 'increment');
+ // Newline is normalized away in output
+ expect(result.prompt).toBe("('hello+ world', 'other').and()");
+ });
+
+ it('should increment a word in curly-quoted prompt function with newline before .method()', () => {
+ const prompt = '(\u201chello world\u201d, \u201cother\u201d)\n.and()';
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe('(\u201chello+ world\u201d, \u201cother\u201d).and()');
+ });
+
+ it('should increment a word in unquoted prompt function with newline before .method()', () => {
+ const prompt = '(hello, other)\n.and()';
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe('(hello+, other).and()');
+ });
+ });
- expect(result.prompt).toBe('(a+ b c)+ d e+');
+ describe('paragraph separators between args', () => {
+ it('should preserve newlines between quoted args when adjusting', () => {
+ const prompt = "('chunk 1\n\nline',\n 'chunk 2').and()";
+ const result = adj(prompt, 'chunk', 'increment');
+ expect(result.prompt).toBe("('chunk+ 1\n\nline',\n 'chunk 2').and()");
+ });
});
});
- describe('single word', () => {
- it('should add + when incrementing word without attention', () => {
- const prompt = 'hello world';
- const result = adjustPromptAttention(prompt, 0, 5, 'increment');
+ // Selection Preservation with Prompt Functions
- expect(result.prompt).toBe('hello+ world');
+ describe('selection preservation with prompt functions', () => {
+ it('should track selection for single word inside prompt function arg', () => {
+ const prompt = "('hello world', 'other').and()";
+ const result = adj(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe("('hello+ world', 'other').and()");
+ expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('hello+');
});
- it('should add - when decrementing word without attention', () => {
+ it('should track selection spanning across prompt function 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()");
+ // Selection should span from 'two+' through 'three+' (including structural chars between)
+ const sel = result.prompt.slice(result.selectionStart, result.selectionEnd);
+ expect(sel).toContain('two+');
+ expect(sel).toContain('three+');
+ });
+ });
+
+ // Edge Cases
+
+ describe('edge cases', () => {
+ it('should return prompt unchanged when no selection overlap', () => {
const prompt = 'hello world';
- const result = adjustPromptAttention(prompt, 0, 5, 'decrement');
+ const result = adjustPromptAttention(prompt, 5, 5, 'increment');
+ // Cursor at the boundary between hello and space — should still find a terminal
+ expect(result.prompt).toBeDefined();
+ });
- expect(result.prompt).toBe('hello- world');
+ it('should handle empty prompt', () => {
+ const result = adjustPromptAttention('', 0, 0, 'increment');
+ expect(result.prompt).toBe('');
+ });
+
+ it('should not modify prompt function structure when cursor is on structural char', () => {
+ const prompt = "('a', 'b').and()";
+ // Cursor on the dot between ) and and
+ const dotPos = prompt.indexOf('.and');
+ const result = adjustPromptAttention(prompt, dotPos, dotPos, 'increment');
+ // Should either not change or only affect content, not break the structure
+ expect(result.prompt).toContain('.and()');
});
});
- describe('existing group', () => {
- it('should adjust group attention when cursor is at group boundary', () => {
- const prompt = '(hello world)+';
- const result = adjustPromptAttention(prompt, 13, 14, 'increment');
+ // Numeric Weight Preference
+
+ describe('prefersNumericWeights', () => {
+ describe('single word (no existing attention)', () => {
+ it.each([
+ ['hello world', 'hello', 'increment', '(hello)1.1 world'],
+ ['hello world', 'hello', 'decrement', '(hello)0.9 world'],
+ ['hello world', 'world', 'increment', 'hello (world)1.1'],
+ ['hello world', 'world', 'decrement', 'hello (world)0.9'],
+ ] as const)('%s [%s] %s → %s', (prompt, selected, direction, expected) => {
+ expect(adjNumeric(prompt, selected, direction).prompt).toBe(expected);
+ });
+ });
- expect(result.prompt).toBe('(hello world)++');
+ describe('successive numeric adjustments', () => {
+ it('should use additive step on second increment', () => {
+ const result = adjNumeric('(hello)1.1 world', '(hello)1.1', 'increment');
+ expect(result.prompt).toBe('(hello)1.2 world');
+ });
+
+ it('should use additive step on second decrement', () => {
+ const result = adjNumeric('(hello)0.9 world', '(hello)0.9', 'decrement');
+ expect(result.prompt).toBe('(hello)0.8 world');
+ });
+
+ it('should return to neutral from 1.1 on decrement', () => {
+ const result = adjNumeric('(hello)1.1 world', '(hello)1.1', 'decrement');
+ expect(result.prompt).toBe('hello world');
+ });
});
- it('should remove group when attention becomes neutral', () => {
- const prompt = '(hello world)+';
- const result = adjustPromptAttention(prompt, 0, 14, 'decrement');
+ describe('does not convert existing +/- attention on unselected terminals', () => {
+ it('should preserve +/- on unselected word when adjusting another', () => {
+ const result = adjNumeric('hello+ world', 'world', 'increment');
+ expect(result.prompt).toContain('hello+');
+ expect(result.prompt).toContain('(world)1.1');
+ });
+
+ it('should preserve - on unselected word', () => {
+ const result = adjNumeric('hello- world', 'world', 'decrement');
+ expect(result.prompt).toContain('hello-');
+ expect(result.prompt).toContain('(world)0.9');
+ });
+ });
- expect(result.prompt).toBe('hello world');
+ describe('existing +/- attention on selected terminals', () => {
+ it('should increment existing + word with multiplicative step (respects existing style)', () => {
+ const result = adjNumeric('hello+ world', 'hello+', 'increment');
+ // The terminal already has explicit +/- attention, so it keeps that style
+ expect(result.prompt).toBe('hello++ world');
+ });
+
+ it('should decrement existing + word to neutral', () => {
+ const result = adjNumeric('hello+ world', 'hello+', 'decrement');
+ expect(result.prompt).toBe('hello world');
+ });
});
- });
- describe('multiple words without group', () => {
- it('should create new group with + when incrementing multiple words', () => {
- const prompt = 'hello world';
- const result = adjustPromptAttention(prompt, 0, 11, 'increment');
+ describe('existing numeric attention on selected terminals', () => {
+ it('should increment existing numeric weight additively', () => {
+ const result = adjNumeric('(detail)1.3 world', '(detail)1.3', 'increment');
+ expect(result.prompt).toBe('(detail)1.4 world');
+ });
- expect(result.prompt).toBe('(hello world)+');
+ it('should decrement existing numeric weight additively', () => {
+ const result = adjNumeric('(detail)1.3 world', '(detail)1.3', 'decrement');
+ expect(result.prompt).toBe('(detail)1.2 world');
+ });
});
- it('should create new group with - when decrementing multiple words', () => {
- const prompt = 'hello world';
- const result = adjustPromptAttention(prompt, 0, 11, 'decrement');
+ describe('multiple words selected', () => {
+ it('should wrap multiple words in numeric group on increment', () => {
+ const result = adjNumeric('hello world', [0, 11], 'increment');
+ expect(result.prompt).toBe('(hello world)1.1');
+ });
- expect(result.prompt).toBe('(hello world)-');
+ it('should wrap multiple words in numeric group on decrement', () => {
+ const result = adjNumeric('hello world', [0, 11], 'decrement');
+ expect(result.prompt).toBe('(hello world)0.9');
+ });
});
- });
- describe('selection preservation', () => {
- it('should preserve selection when incrementing single word', () => {
- const prompt = 'hello world';
- const result = adjustPromptAttention(prompt, 0, 5, 'increment');
- expect(result.prompt).toBe('hello+ world');
- expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('hello+');
+ describe('inside prompt functions', () => {
+ it('should use numeric format inside prompt function arg', () => {
+ const prompt = "('hello world', 'other').and()";
+ const result = adjNumeric(prompt, 'hello', 'increment');
+ expect(result.prompt).toBe("('(hello)1.1 world', 'other').and()");
+ });
+
+ it('should use numeric format across prompt function 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', true);
+ expect(result.prompt).toBe("('one (two)1.1', '(three)1.1 four').and()");
+ });
});
- it('should preserve selection when incrementing group', () => {
- const prompt = '(hello world)+';
- const result = adjustPromptAttention(prompt, 0, 14, 'increment');
- expect(result.prompt).toBe('(hello world)++');
- expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('(hello world)++');
+ describe('group splitting inside prompt function args', () => {
+ it('should correctly split weighted group when decrementing a single word inside it', () => {
+ const prompt =
+ '("high detail, (cinematic lighting)1.25, soft volumetric light, (sharp focus)+, professional photography", "a young woman with balanced natural proportions, medium length brown hair, neutral expression, casual modern clothing", "subtle rim light, shallow depth of field, natural skin texture, clean background").and()';
+ const result = adj(prompt, 'lighting', 'decrement');
+ // "lighting" gets decremented from 1.25 → 1.25/1.1 ≈ 1.1364
+ // "cinematic" stays at 1.25
+ // The key thing: no space should be lost/misplaced
+ expect(result.prompt).toContain('(cinematic)1.25');
+ expect(result.prompt).toContain('lighting)');
+ // Verify there's a space between the cinematic group and lighting group
+ const cinIdx = result.prompt.indexOf('(cinematic)1.25');
+ const afterCinematic = result.prompt.substring(
+ cinIdx + '(cinematic)1.25'.length,
+ cinIdx + '(cinematic)1.25'.length + 2
+ );
+ expect(afterCinematic).toMatch(/^ /); // Should start with a space
+ });
+
+ it('should rejoin groups when incrementing back to the same weight', () => {
+ const prompt =
+ '("high detail, (cinematic lighting)1.25, soft volumetric light, (sharp focus)+, professional photography", "a young woman with balanced natural proportions, medium length brown hair, neutral expression, casual modern clothing", "subtle rim light, shallow depth of field, natural skin texture, clean background").and()';
+ // Decrement "lighting" to split the group
+ const step1 = adj(prompt, 'lighting', 'decrement');
+ expect(step1.prompt).toContain('(cinematic)1.25');
+ // Now increment "lighting" back — should rejoin into (cinematic lighting)1.25
+ const step2 = adj(step1.prompt, 'lighting', 'increment');
+ expect(step2.prompt).toContain('(cinematic lighting)1.25');
+ });
});
- it('should preserve selection when splitting group', () => {
- const prompt = '(a b)+';
- const result = adjustPromptAttention(prompt, 1, 2, 'increment'); // Select 'a' (index 1 to 2)
- // 'a' becomes 1.21, 'b' stays 1.1
- // Result: (a+ b)+ which is equivalent to a++ b+
- expect(result.prompt).toBe('(a+ b)+');
- expect(result.prompt.slice(result.selectionStart, result.selectionEnd)).toBe('a+');
+ describe('numeric group whitespace trimming', () => {
+ it('should not capture trailing whitespace inside numeric weighted groups', () => {
+ // (foo bar)1.3 → decrement "bar" → (foo)1.3 (bar)X, with space between
+ const result = adj('(foo bar)1.3', 'bar', 'decrement');
+ expect(result.prompt).toContain('(foo)1.3');
+ // Space should be outside the group, not inside
+ expect(result.prompt).not.toContain('(foo )');
+ expect(result.prompt).toMatch(/\(foo\)1\.3 /);
+ });
+
+ it('should not capture leading whitespace inside numeric weighted groups', () => {
+ // (foo bar)1.3 → decrement "foo" → (foo)X (bar)1.3, with space between
+ const result = adj('(foo bar)1.3', 'foo', 'decrement');
+ expect(result.prompt).toContain('(bar)1.3');
+ // Space should be outside the group, not inside
+ expect(result.prompt).not.toContain('( bar)');
+ expect(result.prompt).toMatch(/ \(bar\)1\.3/);
+ });
+ });
+
+ describe('numeric group conjoining', () => {
+ it('should merge adjacent same-weight numeric groups back together', () => {
+ // Two separate groups with same weight should conjoin into one
+ const result = adj('(foo)1.25 (bar)1.25', [0, 19], 'increment');
+ // Both words get the same increment, so they should stay in one group
+ expect(result.prompt).not.toContain(') (');
+ });
+
+ it('should merge adjacent same-weight groups when incrementing to match', () => {
+ // Start with (foo bar)1.3, decrement "bar", then increment it back
+ const step1 = adj('(foo bar)1.3', 'bar', 'decrement');
+ // Now increment "bar" back — it should rejoin into a single group
+ const step2 = adj(step1.prompt, 'bar', 'increment');
+ expect(step2.prompt).toBe('(foo bar)1.3');
+ });
+
+ it('should merge inside prompt function args', () => {
+ const prompt = '("(cinematic)1.25 (lighting)1.25", "other").and()';
+ const start = prompt.indexOf('cinematic');
+ const end = prompt.indexOf('lighting') + 'lighting'.length;
+ const result = adj(prompt, [start, end], 'increment');
+ // Both get incremented to same weight, should be one group
+ expect(result.prompt).not.toMatch(/\)\d[.\d]* \(/);
+ });
+ });
+
+ describe('without prefersNumericWeights (default behavior unchanged)', () => {
+ it('should still use +/- syntax by default', () => {
+ expect(adj('hello world', 'hello', 'increment').prompt).toBe('hello+ world');
+ expect(adj('hello world', 'hello', 'decrement').prompt).toBe('hello- world');
+ });
+
+ it('should still use +/- for multiple words by default', () => {
+ expect(adj('hello world', [0, 11], 'increment').prompt).toBe('(hello world)+');
+ });
});
});
});
diff --git a/invokeai/frontend/web/src/common/util/promptAttention.ts b/invokeai/frontend/web/src/common/util/promptAttention.ts
index 65f25b1606..baaafdb9d6 100644
--- a/invokeai/frontend/web/src/common/util/promptAttention.ts
+++ b/invokeai/frontend/web/src/common/util/promptAttention.ts
@@ -1,125 +1,350 @@
import { logger } from 'app/logging/logger';
import { serializeError } from 'serialize-error';
-import { type ASTNode, type Attention, parseTokens, serialize, tokenize } from './promptAST';
+import {
+ type ASTNode,
+ type Attention,
+ parseTokens,
+ type PromptFunctionArg,
+ serializeWithSelection,
+ tokenize,
+} from './promptAST';
-const log = logger('events');
+const log = logger('generation');
type AttentionDirection = 'increment' | 'decrement';
type AdjustmentResult = { prompt: string; selectionStart: number; selectionEnd: number };
const ATTENTION_STEP = 1.1;
+const NUMERIC_ATTENTION_STEP = 0.1;
+
+/** Tolerance for floating-point weight comparisons. */
+const WEIGHT_TOLERANCE = 0.001;
+
+/** Tolerance for checking if a weight is a power of ATTENTION_STEP. */
+const STEP_COUNT_TOLERANCE = 0.005;
+
+// #region Weight Helpers
+
+/**
+ * Check if a weight is approximately ATTENTION_STEP^n for some integer n.
+ * Returns n if so, or null if the weight is not a power of ATTENTION_STEP.
+ */
+function getAttentionStepCount(weight: number): number | null {
+ if (weight <= 0) {
+ return null;
+ }
+ if (Math.abs(weight - 1.0) < WEIGHT_TOLERANCE) {
+ return 0;
+ }
+ const n = Math.round(Math.log(weight) / Math.log(ATTENTION_STEP));
+ if (n === 0) {
+ return null;
+ }
+ const expected = Math.pow(ATTENTION_STEP, n);
+ if (Math.abs(expected - weight) < STEP_COUNT_TOLERANCE) {
+ return n;
+ }
+ return null;
+}
+
+/**
+ * Convert an Attention value ('+', '--', 1.2, etc.) into a numeric multiplier.
+ */
+function parseAttention(attention: Attention): number {
+ if (typeof attention === 'number') {
+ return attention;
+ }
+ if (attention.startsWith('+')) {
+ return Math.pow(ATTENTION_STEP, attention.length);
+ }
+ if (attention.startsWith('-')) {
+ return Math.pow(ATTENTION_STEP, -attention.length);
+ }
+ const num = Number(attention);
+ return isNaN(num) ? 1.0 : num;
+}
+
+/**
+ * Combine an existing attention value with an additional '+' or '-' level.
+ * Handles cancellation: e.g. '++' + '-' → '+', '+' + '-' → undefined (neutral).
+ */
+function addAttention(current: Attention | undefined, added: '+' | '-'): Attention | undefined {
+ if (!current) {
+ return added;
+ }
+ if (typeof current === 'number') {
+ if (added === '+') {
+ return Number((current * ATTENTION_STEP).toFixed(4));
+ }
+ return Number((current / ATTENTION_STEP).toFixed(4));
+ }
+ // Check if the added direction cancels the current one
+ const isCancel = (current.startsWith('+') && added === '-') || (current.startsWith('-') && added === '+');
+ if (isCancel) {
+ const res = current.substring(1);
+ return res === '' ? undefined : res;
+ }
+ return `${current}${added}`;
+}
+
+// #region Terminal Type
+
+type Terminal = {
+ text: string;
+ type: ASTNode['type'];
+ weight: number;
+ range: { start: number; end: number };
+ hasExplicitAttention: boolean;
+ hasNumericAttention: boolean;
+ parentRange?: { start: number; end: number };
+ isSelected: boolean;
+};
+
+// #region Main Entry Point
/**
* Adjusts the attention of the prompt at the current cursor/selection position.
+ * Supports regular prompts and prompt functions (.and(), .or(), .blend()).
+ *
+ * When a selection spans across a prompt function's argument separator, each
+ * affected argument is adjusted independently and simultaneously.
*/
export function adjustPromptAttention(
prompt: string,
selectionStart: number,
selectionEnd: number,
- direction: AttentionDirection
+ direction: AttentionDirection,
+ prefersNumericWeights = false
): AdjustmentResult {
try {
const tokens = tokenize(prompt);
const ast = parseTokens(tokens);
- const terminals = flattenAST(ast);
- let selectedTerminals = terminals.filter((t) => {
- const isSelected =
- (t.range.start < selectionEnd && t.range.end > selectionStart) ||
- (selectionStart === selectionEnd && t.range.start <= selectionStart && t.range.end >= selectionStart);
-
- if (!isSelected) {
- return false;
- }
-
- if (t.parentRange) {
- const parentContainsSelection = t.parentRange.start <= selectionStart && t.parentRange.end >= selectionEnd;
- const selectionCoversParent = selectionStart <= t.parentRange.start && selectionEnd >= t.parentRange.end;
-
- if (!parentContainsSelection && !selectionCoversParent) {
- // Partial overlap.
- if (t.hasExplicitAttention) {
- return false; // Don't modify explicit weight in partial group
+ const regions = extractRegions(ast);
+ const processedNodes: ASTNode[] = [];
+ let anyModified = false;
+
+ for (const region of regions) {
+ if (region.type === 'normal') {
+ const clipped = clipSelection(selectionStart, selectionEnd, region.range);
+ if (clipped) {
+ const result = adjustRegionNodes(region.nodes, clipped.start, clipped.end, direction, prefersNumericWeights);
+ if (result.modified) {
+ anyModified = true;
}
+ processedNodes.push(...result.nodes);
+ } else {
+ processedNodes.push(...region.nodes);
+ }
+ } else {
+ // prompt_function region
+ const pfNode = region.node;
+ const clipped = clipSelection(selectionStart, selectionEnd, pfNode.range);
+ if (clipped) {
+ const result = adjustPromptFunctionNode(pfNode, clipped.start, clipped.end, direction, prefersNumericWeights);
+ if (result.modified) {
+ anyModified = true;
+ }
+ processedNodes.push(result.node);
+ } else {
+ processedNodes.push(pfNode);
}
}
- return true;
- });
+ }
- for (const t of selectedTerminals) {
- t.isSelected = true;
+ if (!anyModified) {
+ return { prompt, selectionStart, selectionEnd };
}
- if (selectedTerminals.length === 0) {
- const selectedGroup = findSelectedGroup(ast, selectionStart, selectionEnd);
- if (selectedGroup) {
- selectedTerminals = terminals.filter(
- (t) => t.range.start >= selectedGroup.range.start && t.range.end <= selectedGroup.range.end
- );
- for (const t of selectedTerminals) {
- t.isSelected = true;
- }
- }
+ return serializeWithSelection(processedNodes);
+ } catch (e) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ log.error({ error: serializeError(e) as any }, 'Failed to adjust prompt attention');
+ return { prompt, selectionStart, selectionEnd };
+ }
+}
+
+// #region Region Extraction
+
+type Region =
+ | { type: 'normal'; nodes: ASTNode[]; range: { start: number; end: number } }
+ | { type: 'prompt_function'; node: ASTNode & { type: 'prompt_function' } };
+
+/**
+ * Split the top-level AST into contiguous "normal" regions and prompt function regions.
+ * This allows us to process prompt function arguments independently.
+ */
+function extractRegions(ast: ASTNode[]): Region[] {
+ const regions: Region[] = [];
+ let currentNormal: ASTNode[] = [];
+
+ const flushNormal = () => {
+ if (currentNormal.length > 0) {
+ const first = currentNormal[0]!;
+ const last = currentNormal[currentNormal.length - 1]!;
+ regions.push({
+ type: 'normal',
+ nodes: currentNormal,
+ range: { start: first.range.start, end: last.range.end },
+ });
+ currentNormal = [];
}
+ };
- if (selectedTerminals.length === 0) {
- return { prompt, selectionStart, selectionEnd };
+ for (const node of ast) {
+ if (node.type === 'prompt_function') {
+ flushNormal();
+ regions.push({ type: 'prompt_function', node });
+ } else {
+ currentNormal.push(node);
}
+ }
+ flushNormal();
- for (const terminal of selectedTerminals) {
- if (direction === 'increment') {
- terminal.weight *= ATTENTION_STEP;
- } else {
- terminal.weight /= ATTENTION_STEP;
+ return regions;
+}
+
+/**
+ * Clip a selection range to a target range. Returns null if there is no overlap.
+ * For cursor positions (start === end), checks containment including boundaries.
+ */
+function clipSelection(
+ selStart: number,
+ selEnd: number,
+ range: { start: number; end: number }
+): { start: number; end: number } | null {
+ if (selStart === selEnd) {
+ // Cursor position: check if within range (inclusive of boundaries)
+ if (selStart >= range.start && selStart <= range.end) {
+ return { start: selStart, end: selEnd };
+ }
+ return null;
+ }
+ const clippedStart = Math.max(selStart, range.start);
+ const clippedEnd = Math.min(selEnd, range.end);
+ if (clippedStart >= clippedEnd) {
+ return null;
+ }
+ return { start: clippedStart, end: clippedEnd };
+}
+
+// #region Prompt Function Handling
+
+/**
+ * Adjust attention within a prompt function node by processing each argument
+ * whose content range overlaps the selection independently.
+ * Returns the (possibly updated) node and whether any modification was made.
+ */
+function adjustPromptFunctionNode(
+ pf: ASTNode & { type: 'prompt_function' },
+ selStart: number,
+ selEnd: number,
+ direction: AttentionDirection,
+ prefersNumericWeights = false
+): { node: ASTNode & { type: 'prompt_function' }; modified: boolean } {
+ let modified = false;
+ const newArgs: PromptFunctionArg[] = pf.promptArgs.map((arg) => {
+ const clipped = clipSelection(selStart, selEnd, arg.contentRange);
+ if (clipped) {
+ const result = adjustRegionNodes(arg.nodes, clipped.start, clipped.end, direction, prefersNumericWeights);
+ if (result.modified) {
+ modified = true;
+ return { ...arg, nodes: result.nodes };
}
}
+ return arg;
+ });
- const newAST = groupTerminals(terminals);
- const newPrompt = serialize(newAST);
- const newSelection = calculateSelectionRange(newAST);
+ if (!modified) {
+ return { node: pf, modified: false };
+ }
- return {
- prompt: newPrompt,
- selectionStart: newSelection.start,
- selectionEnd: newSelection.end,
- };
- } catch (e) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- log.error({ error: serializeError(e) as any }, 'Failed to adjust prompt attention');
- return { prompt, selectionStart, selectionEnd };
+ return { node: { ...pf, promptArgs: newArgs }, modified: true };
+}
+
+// #region Core Attention Adjustment
+
+/**
+ * Adjust attention for a set of AST nodes (a "region") given a selection range.
+ * This is the core flatten → select → adjust → regroup pipeline.
+ * Returns the adjusted nodes and whether any modification was made.
+ */
+function adjustRegionNodes(
+ nodes: ASTNode[],
+ selStart: number,
+ selEnd: number,
+ direction: AttentionDirection,
+ prefersNumericWeights = false
+): { nodes: ASTNode[]; modified: boolean } {
+ const terminals = flattenAST(nodes);
+
+ let selectedTerminals = selectTerminals(terminals, selStart, selEnd);
+
+ // Fallback: if no terminals were selected, try to find an overlapping group
+ if (selectedTerminals.length === 0) {
+ const group = findSelectedGroup(nodes, selStart, selEnd);
+ if (group) {
+ selectedTerminals = terminals.filter((t) => t.range.start >= group.range.start && t.range.end <= group.range.end);
+ }
}
+
+ if (selectedTerminals.length === 0) {
+ return { nodes, modified: false };
+ }
+
+ for (const t of selectedTerminals) {
+ t.isSelected = true;
+ // When the user prefers numeric weights and the terminal doesn't already
+ // have explicit attention, mark it as numeric so adjustWeights uses
+ // additive steps and groupTerminals emits numeric syntax.
+ if (prefersNumericWeights && !t.hasExplicitAttention) {
+ t.hasNumericAttention = true;
+ }
+ }
+
+ adjustWeights(selectedTerminals, direction);
+
+ return { nodes: groupTerminals(terminals), modified: true };
}
-type Terminal = {
- text: string;
- type: ASTNode['type'];
- weight: number;
- range: { start: number; end: number };
- hasExplicitAttention: boolean;
- parentRange?: { start: number; end: number };
- isSelected: boolean;
-};
+// #region Flatten AST to Terminals
-function flattenAST(ast: ASTNode[], currentWeight = 1.0, parentRange?: { start: number; end: number }): Terminal[] {
- let terminals: Terminal[] = [];
+/**
+ * Flatten an AST into a flat list of terminals, computing the effective weight
+ * of each terminal by accumulating attention from ancestor groups.
+ */
+function flattenAST(
+ ast: ASTNode[],
+ currentWeight = 1.0,
+ parentRange?: { start: number; end: number },
+ numericAttention = false
+): Terminal[] {
+ const terminals: Terminal[] = [];
for (const node of ast) {
let nodeWeight = currentWeight;
- if ('attention' in node && node.attention) {
+ let nodeNumericAttention = numericAttention;
+ if ((node.type === 'word' || node.type === 'group') && node.attention) {
nodeWeight *= parseAttention(node.attention);
+ nodeNumericAttention = typeof node.attention === 'number';
}
if (node.type === 'group') {
- terminals.push(...flattenAST(node.children, nodeWeight, node.range));
+ terminals.push(...flattenAST(node.children, nodeWeight, node.range, nodeNumericAttention));
+ } else if (node.type === 'prompt_function') {
+ // Prompt functions should not appear inside regions being flattened;
+ // they are handled at the region level. If one somehow appears, skip it.
+ continue;
} else {
terminals.push({
text: node.type === 'word' ? node.text : node.value,
type: node.type,
weight: nodeWeight,
range: node.range,
- hasExplicitAttention: 'attention' in node && !!node.attention,
- parentRange: parentRange,
+ hasExplicitAttention: node.type === 'word' && !!node.attention,
+ hasNumericAttention: nodeNumericAttention,
+ parentRange,
isSelected: false,
});
}
@@ -127,117 +352,148 @@ function flattenAST(ast: ASTNode[], currentWeight = 1.0, parentRange?: { start:
return terminals;
}
-function findSelectedGroup(nodes: ASTNode[], start: number, end: number): ASTNode | null {
- for (const node of nodes) {
- if (node.type === 'group') {
- const foundInChildren = findSelectedGroup(node.children, start, end);
- if (foundInChildren) {
- return foundInChildren;
- }
+// #region Terminal Selection
- if (rangesOverlap(node.range, { start, end })) {
- return node;
+/**
+ * Find terminals that overlap the selection range and should be affected
+ * by the attention adjustment. Handles partial group overlap carefully:
+ * terminals with explicit attention inside partially-overlapping groups
+ * are excluded to avoid corrupting explicit weights.
+ *
+ * When the cursor is at a boundary between two tokens (e.g. "word|,"),
+ * both tokens technically overlap the cursor position. In this case we
+ * prefer word/embedding terminals over punctuation/whitespace so that
+ * adjusting attention at a word boundary doesn't accidentally include
+ * adjacent punctuation.
+ */
+function selectTerminals(terminals: Terminal[], selStart: number, selEnd: number): Terminal[] {
+ const result = terminals.filter((t) => {
+ const isOverlapping =
+ (t.range.start < selEnd && t.range.end > selStart) ||
+ (selStart === selEnd && t.range.start <= selStart && t.range.end >= selStart);
+
+ if (!isOverlapping) {
+ return false;
+ }
+
+ if (t.parentRange) {
+ const parentContainsSelection = t.parentRange.start <= selStart && t.parentRange.end >= selEnd;
+ const selectionCoversParent = selStart <= t.parentRange.start && selEnd >= t.parentRange.end;
+
+ if (!parentContainsSelection && !selectionCoversParent) {
+ // Partial overlap between selection and parent group
+ if (t.hasExplicitAttention) {
+ return false; // Don't modify explicit weight in partially-overlapping group
+ }
}
}
+ return true;
+ });
+
+ // When the cursor is at a token boundary (no selection range), multiple tokens
+ // can match. Prefer word/embedding terminals over punctuation/whitespace.
+ if (selStart === selEnd && result.length > 1) {
+ const contentTerminals = result.filter((t) => t.type === 'word' || t.type === 'embedding');
+ if (contentTerminals.length > 0) {
+ return contentTerminals;
+ }
}
- return null;
-}
-function rangesOverlap(a: { start: number; end: number }, b: { start: number; end: number }) {
- return a.start < b.end && a.end > b.start;
+ return result;
}
-function parseAttention(attention: Attention): number {
- if (typeof attention === 'number') {
- return attention;
- }
- if (attention.startsWith('+')) {
- return Math.pow(ATTENTION_STEP, attention.length);
- }
- if (attention.startsWith('-')) {
- return Math.pow(ATTENTION_STEP, -attention.length);
- }
- const num = Number(attention);
- return isNaN(num) ? 1.0 : num;
-}
+// #region Weight Adjustment
-function calculateSelectionRange(nodes: ASTNode[]): { start: number; end: number } {
- let selectionStart = Infinity;
- let selectionEnd = -1;
- let currentPos = 0;
-
- function traverse(nodes: ASTNode[]) {
- for (const node of nodes) {
- if (node.isSelection) {
- const len = serialize([node]).length;
- selectionStart = Math.min(selectionStart, currentPos);
- selectionEnd = Math.max(selectionEnd, currentPos + len);
- currentPos += len;
+/**
+ * Apply weight changes to the selected terminals based on direction.
+ * Numeric weights use additive steps; +/- syntax uses multiplicative steps.
+ * All results are rounded to 4 decimal places to prevent floating-point drift.
+ */
+function adjustWeights(terminals: Terminal[], direction: AttentionDirection): void {
+ for (const terminal of terminals) {
+ if (terminal.hasNumericAttention) {
+ // Additive step for explicit numeric weights (e.g. 1.1 → 1.2)
+ if (direction === 'increment') {
+ terminal.weight = Number((terminal.weight + NUMERIC_ATTENTION_STEP).toFixed(4));
} else {
- if (node.type === 'group') {
- // Group is not fully selected, but children might be.
- // Group structure: "(" + children + ")" + attention
- currentPos += 1; // '('
- traverse(node.children);
- currentPos += 1; // ')'
- if (node.attention) {
- currentPos += String(node.attention).length;
- }
- } else {
- // Leaf node not selected.
- const len = serialize([node]).length;
- currentPos += len;
- }
+ terminal.weight = Number((terminal.weight - NUMERIC_ATTENTION_STEP).toFixed(4));
+ }
+ } else {
+ // Multiplicative step for +/- syntax weights, rounded to prevent drift
+ if (direction === 'increment') {
+ terminal.weight = Number((terminal.weight * ATTENTION_STEP).toFixed(4));
+ } else {
+ terminal.weight = Number((terminal.weight / ATTENTION_STEP).toFixed(4));
}
}
}
+}
- traverse(nodes);
+// #region Find Selected Group (fallback)
- if (selectionStart === Infinity) {
- return { start: 0, end: serialize(nodes).length };
+/**
+ * When no terminals directly overlap the selection (e.g. cursor is on a group
+ * boundary character), find the innermost group that overlaps the selection.
+ */
+function findSelectedGroup(nodes: ASTNode[], start: number, end: number): ASTNode | null {
+ for (const node of nodes) {
+ if (node.type === 'group') {
+ const foundInChildren = findSelectedGroup(node.children, start, end);
+ if (foundInChildren) {
+ return foundInChildren;
+ }
+ if (node.range.start < end && node.range.end > start) {
+ return node;
+ }
+ }
}
- return { start: selectionStart, end: selectionEnd };
+ return null;
}
+// #region Regroup Terminals into AST
+
+/**
+ * Reconstruct an AST from a flat list of terminals with adjusted weights.
+ * Groups consecutive terminals with compatible weights using +/- or numeric syntax.
+ *
+ * Note: Reconstructed group nodes use `range: { start: 0, end: 0 }` as a sentinel
+ * value since the original source positions are no longer meaningful after regrouping.
+ * These nodes are only used for serialization output, never for source-position lookups.
+ */
function groupTerminals(terminals: Terminal[]): ASTNode[] {
if (terminals.length === 0) {
return [];
}
+ /** Sentinel range for reconstructed nodes whose original positions are not applicable. */
+ const NO_RANGE = { start: 0, end: 0 };
+
const nodes: ASTNode[] = [];
let i = 0;
+
while (i < terminals.length) {
const t = terminals[i]!;
const weight = t.weight;
-
- const findRunEnd = (predicate: (w: number) => boolean) => {
- let j = i;
- while (j < terminals.length) {
- const next = terminals[j]!;
- if (predicate(next.weight)) {
- j++;
- } else if (next.type === 'whitespace') {
- let k = j + 1;
- while (k < terminals.length && terminals[k]!.type === 'whitespace') {
- k++;
- }
- if (k < terminals.length && predicate(terminals[k]!.weight)) {
- j = k;
- } else {
- break;
- }
- } else {
- break;
+ const stepCount = getAttentionStepCount(weight);
+
+ // ── +/- attention (weight is a non-zero power of ATTENTION_STEP) ──
+ // Skip this branch if the terminal prefers numeric format to avoid an
+ // infinite loop (predicate would reject it, findRunEnd returns i, i never advances).
+ if (stepCount !== null && stepCount !== 0 && !t.hasNumericAttention) {
+ const isPositive = stepCount > 0;
+ const sign: '+' | '-' = isPositive ? '+' : '-';
+ const predicate = (t: Terminal): boolean => {
+ if (t.hasNumericAttention) {
+ return false; // Numeric-preference terminals should not join +/- runs
}
- }
- return j;
- };
+ const sc = getAttentionStepCount(t.weight);
+ return sc !== null && (isPositive ? sc > 0 : sc < 0);
+ };
+ const factor = isPositive ? ATTENTION_STEP : 1 / ATTENTION_STEP;
- // Check for + (>= 1.1)
- if (weight >= ATTENTION_STEP - 0.001) {
- const j = findRunEnd((w) => w >= ATTENTION_STEP - 0.001);
+ const j = findRunEnd(terminals, i, predicate);
+ // Trim whitespace from the content run boundaries
let runStart = i;
let runEnd = j;
while (runStart < runEnd && terminals[runStart]!.type === 'whitespace') {
@@ -247,28 +503,31 @@ function groupTerminals(terminals: Terminal[]): ASTNode[] {
runEnd--;
}
+ // Emit leading whitespace as standalone nodes
for (let k = i; k < runStart; k++) {
nodes.push(createNodeFromTerminal(terminals[k]!));
}
if (runStart < runEnd) {
- const slice = terminals.slice(runStart, runEnd).map((t) => ({ ...t, weight: t.weight / ATTENTION_STEP }));
+ // Factor out one level of attention and recurse
+ const slice = terminals.slice(runStart, runEnd).map((t) => ({ ...t, weight: t.weight / factor }));
const children = groupTerminals(slice);
const isSelection = slice.every((t) => t.isSelected);
if (children.length === 1) {
const child = children[0]!;
if (child.type === 'word' || child.type === 'group') {
- const newAttention = addAttention(child.attention, '+');
- nodes.push({ ...child, attention: newAttention });
+ const newAttention = addAttention(child.attention, sign);
+ nodes.push({ ...child, attention: newAttention, isSelection: isSelection || undefined });
} else {
- nodes.push({ type: 'group', children, attention: '+', range: { start: 0, end: 0 }, isSelection });
+ nodes.push({ type: 'group', children, attention: sign, range: NO_RANGE, isSelection });
}
} else {
- nodes.push({ type: 'group', children, attention: '+', range: { start: 0, end: 0 }, isSelection });
+ nodes.push({ type: 'group', children, attention: sign, range: NO_RANGE, isSelection });
}
}
+ // Emit trailing whitespace as standalone nodes
for (let k = runEnd; k < j; k++) {
nodes.push(createNodeFromTerminal(terminals[k]!));
}
@@ -277,10 +536,18 @@ function groupTerminals(terminals: Terminal[]): ASTNode[] {
continue;
}
- // Check for - (<= 0.909)
- if (weight <= 1 / ATTENTION_STEP + 0.001) {
- const j = findRunEnd((w) => w <= 1 / ATTENTION_STEP + 0.001);
+ // ── Neutral weight (≈ 1.0) ──
+ if (Math.abs(weight - 1.0) < WEIGHT_TOLERANCE) {
+ nodes.push(createNodeFromTerminal(t));
+ i++;
+ continue;
+ }
+
+ // ── Numeric weight (not a power of ATTENTION_STEP) ──
+ {
+ const j = findRunEnd(terminals, i, (t) => Math.abs(t.weight - weight) < WEIGHT_TOLERANCE);
+ // Trim whitespace from the content run boundaries (same as +/- branch)
let runStart = i;
let runEnd = j;
while (runStart < runEnd && terminals[runStart]!.type === 'whitespace') {
@@ -290,113 +557,82 @@ function groupTerminals(terminals: Terminal[]): ASTNode[] {
runEnd--;
}
+ // Emit leading whitespace as standalone nodes
for (let k = i; k < runStart; k++) {
nodes.push(createNodeFromTerminal(terminals[k]!));
}
if (runStart < runEnd) {
- const slice = terminals.slice(runStart, runEnd).map((t) => ({ ...t, weight: t.weight * ATTENTION_STEP }));
- const children = groupTerminals(slice);
- const isSelection = slice.every((t) => t.isSelected);
+ const groupSlice = terminals.slice(runStart, runEnd).map((t) => ({ ...t, weight: 1.0 }));
+ const children = groupTerminals(groupSlice);
+ const isSelection = groupSlice.every((t) => t.isSelected);
+ const weightNum = Number(weight.toFixed(4));
- if (children.length === 1) {
- const child = children[0]!;
- if (child.type === 'word' || child.type === 'group') {
- const newAttention = addAttention(child.attention, '-');
- nodes.push({ ...child, attention: newAttention });
- } else {
- nodes.push({ type: 'group', children, attention: '-', range: { start: 0, end: 0 }, isSelection });
- }
- } else {
- nodes.push({ type: 'group', children, attention: '-', range: { start: 0, end: 0 }, isSelection });
- }
+ nodes.push({ type: 'group', children, attention: weightNum, range: NO_RANGE, isSelection });
}
+ // Emit trailing whitespace as standalone nodes
for (let k = runEnd; k < j; k++) {
nodes.push(createNodeFromTerminal(terminals[k]!));
}
i = j;
- continue;
}
+ }
+ return nodes;
+}
- // Residual or 1.0
- if (Math.abs(weight - 1.0) < 0.001) {
- nodes.push(createNodeFromTerminal(t));
- i++;
- } else {
- let j = i;
- while (j < terminals.length && Math.abs(terminals[j]!.weight - weight) < 0.001) {
- j++;
+/**
+ * Find the end of a "run" of terminals whose weights satisfy a predicate.
+ * Whitespace terminals are included if the next non-whitespace terminal also satisfies the predicate.
+ * Note: The returned index may point to a whitespace token that is NOT included in the run;
+ * the caller is responsible for trimming trailing whitespace from the run boundaries.
+ */
+function findRunEnd(terminals: Terminal[], start: number, predicate: (t: Terminal) => boolean): number {
+ let j = start;
+ while (j < terminals.length) {
+ const next = terminals[j]!;
+ if (predicate(next)) {
+ j++;
+ } else if (next.type === 'whitespace') {
+ // Look ahead past consecutive whitespace
+ let k = j + 1;
+ while (k < terminals.length && terminals[k]!.type === 'whitespace') {
+ k++;
}
-
- const groupTerminalsSlice = terminals.slice(i, j).map((t) => ({ ...t, weight: 1.0 }));
- const children = groupTerminals(groupTerminalsSlice);
- const isSelection = groupTerminalsSlice.every((t) => t.isSelected);
-
- const weightStr = Number(weight.toFixed(4));
-
- if (children.length === 1) {
- const child = children[0]!;
- if (child.type === 'word' || child.type === 'group') {
- nodes.push({ ...child, attention: weightStr });
- } else {
- nodes.push({ type: 'group', children, attention: weightStr, range: { start: 0, end: 0 }, isSelection });
- }
+ if (k < terminals.length && predicate(terminals[k]!)) {
+ j = k;
} else {
- nodes.push({ type: 'group', children, attention: weightStr, range: { start: 0, end: 0 }, isSelection });
+ break;
}
- i = j;
+ } else {
+ break;
}
}
- return nodes;
+ return j;
}
+/**
+ * Convert a Terminal back into a leaf ASTNode.
+ */
function createNodeFromTerminal(t: Terminal): ASTNode {
- if (t.type === 'word') {
- return { type: 'word', text: t.text, range: t.range, isSelection: t.isSelected };
- }
- if (t.type === 'whitespace') {
- return { type: 'whitespace', value: t.text, range: t.range, isSelection: t.isSelected };
- }
- if (t.type === 'punct') {
- return { type: 'punct', value: t.text, range: t.range, isSelection: t.isSelected };
- }
- if (t.type === 'embedding') {
- return { type: 'embedding', value: t.text, range: t.range, isSelection: t.isSelected };
- }
- if (t.type === 'escaped_paren') {
- return { type: 'escaped_paren', value: t.text as '(' | ')', range: t.range, isSelection: t.isSelected };
- }
- return { type: 'word', text: t.text, range: t.range, isSelection: t.isSelected };
-}
-
-function addAttention(current: Attention | undefined, added: string): Attention | undefined {
- if (!current) {
- return added;
- }
- if (typeof current === 'number') {
- if (added === '+') {
- return current * ATTENTION_STEP;
- }
- if (added === '-') {
- return current / ATTENTION_STEP;
- }
- return current;
- }
- if (added === '+') {
- if (current.startsWith('-')) {
- const res = current.substring(1);
- return res === '' ? undefined : res;
- }
- return `${current}+`;
- }
- if (added === '-') {
- if (current.startsWith('+')) {
- const res = current.substring(1);
- return res === '' ? undefined : res;
- }
- return `${current}-`;
+ switch (t.type) {
+ case 'word':
+ return { type: 'word', text: t.text, range: t.range, isSelection: t.isSelected || undefined };
+ case 'whitespace':
+ return { type: 'whitespace', value: t.text, range: t.range, isSelection: t.isSelected || undefined };
+ case 'punct':
+ return { type: 'punct', value: t.text, range: t.range, isSelection: t.isSelected || undefined };
+ case 'embedding':
+ return { type: 'embedding', value: t.text, range: t.range, isSelection: t.isSelected || undefined };
+ case 'escaped_paren':
+ return {
+ type: 'escaped_paren',
+ value: t.text as '(' | ')',
+ range: t.range,
+ isSelection: t.isSelected || undefined,
+ };
+ default:
+ return { type: 'word', text: t.text, range: t.range, isSelection: t.isSelected || undefined };
}
- return current;
}
diff --git a/invokeai/frontend/web/src/features/prompt/usePromptAttentionHotkeys.ts b/invokeai/frontend/web/src/features/prompt/usePromptAttentionHotkeys.ts
index 545857b9e2..7959c06b5b 100644
--- a/invokeai/frontend/web/src/features/prompt/usePromptAttentionHotkeys.ts
+++ b/invokeai/frontend/web/src/features/prompt/usePromptAttentionHotkeys.ts
@@ -1,5 +1,7 @@
+import { useAppSelector } from 'app/store/storeHooks';
import { adjustPromptAttention } from 'common/util/promptAttention';
import { useRegisteredHotkeys } from 'features/system/components/HotkeysModal/useHotkeyData';
+import { selectSystemPrefersNumericAttentionWeights } from 'features/system/store/systemSlice';
import type { RefObject } from 'react';
import { useCallback } from 'react';
@@ -18,6 +20,7 @@ export const usePromptAttentionHotkeys = ({
onPromptChange: _onPromptChange,
}: UsePromptAttentionHotkeysArgs) => {
const isPromptFocused = useCallback(() => document.activeElement === textareaRef.current, [textareaRef]);
+ const prefersNumericWeights = useAppSelector(selectSystemPrefersNumericAttentionWeights);
const handleAttentionAdjustment = useCallback(
(direction: 'increment' | 'decrement') => {
@@ -26,7 +29,13 @@ export const usePromptAttentionHotkeys = ({
return;
}
- const result = adjustPromptAttention(textarea.value, textarea.selectionStart, textarea.selectionEnd, direction);
+ const result = adjustPromptAttention(
+ textarea.value,
+ textarea.selectionStart,
+ textarea.selectionEnd,
+ direction,
+ prefersNumericWeights
+ );
// Use execCommand to make the change undo-able by the browser.
// This triggers the textarea's native onChange, which syncs React state.
@@ -37,7 +46,7 @@ export const usePromptAttentionHotkeys = ({
// Restore the selection to cover the adjusted portion
textarea.setSelectionRange(result.selectionStart, result.selectionEnd);
},
- [textareaRef]
+ [textareaRef, prefersNumericWeights]
);
useRegisteredHotkeys({
@@ -50,7 +59,7 @@ export const usePromptAttentionHotkeys = ({
}
},
options: { preventDefault: true, enableOnFormTags: ['TEXTAREA'] },
- dependencies: [isPromptFocused, handleAttentionAdjustment],
+ dependencies: [isPromptFocused, handleAttentionAdjustment, prefersNumericWeights],
});
useRegisteredHotkeys({
@@ -63,6 +72,6 @@ export const usePromptAttentionHotkeys = ({
}
},
options: { preventDefault: true, enableOnFormTags: ['TEXTAREA'] },
- dependencies: [isPromptFocused, handleAttentionAdjustment],
+ dependencies: [isPromptFocused, handleAttentionAdjustment, prefersNumericWeights],
});
};
diff --git a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx
index 6c7ebada8f..b95d2adb47 100644
--- a/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx
+++ b/invokeai/frontend/web/src/features/system/components/SettingsModal/SettingsModal.tsx
@@ -27,6 +27,7 @@ import { SettingsDeveloperLogNamespaces } from 'features/system/components/Setti
import { useClearIntermediates } from 'features/system/components/SettingsModal/useClearIntermediates';
import { StickyScrollable } from 'features/system/components/StickyScrollable';
import {
+ selectSystemPrefersNumericAttentionWeights,
selectSystemShouldAntialiasProgressImage,
selectSystemShouldConfirmOnDelete,
selectSystemShouldConfirmOnNewSession,
@@ -36,6 +37,7 @@ import {
selectSystemShouldShowInvocationProgressDetail,
selectSystemShouldUseNSFWChecker,
selectSystemShouldUseWatermarker,
+ setPrefersNumericAttentionStyle,
setShouldConfirmOnDelete,
setShouldEnableInformationalPopovers,
setShouldEnableModelDescriptions,
@@ -71,6 +73,7 @@ const SettingsModal = (props: { children: ReactElement }) => {
const settingsModal = useSettingsModal();
const refreshModal = useRefreshAfterResetModal();
+ const prefersNumericAttentionWeights = useAppSelector(selectSystemPrefersNumericAttentionWeights);
const shouldUseCpuNoise = useAppSelector(selectShouldUseCPUNoise);
const shouldConfirmOnDelete = useAppSelector(selectSystemShouldConfirmOnDelete);
const shouldShowProgressInViewer = useAppSelector(selectShouldShowProgressInViewer);
@@ -162,6 +165,13 @@ const SettingsModal = (props: { children: ReactElement }) => {
[dispatch]
);
+ const handleChangePreferAttentionStyleNumeric = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ dispatch(setPrefersNumericAttentionStyle(e.target.checked));
+ },
+ [dispatch]
+ );
+
return (
<>
{cloneElement(props.children, {
@@ -250,6 +260,16 @@ const SettingsModal = (props: { children: ReactElement }) => {
</FormControl>
</StickyScrollable>
+ <StickyScrollable title={t('settings.prompt')}>
+ <FormControl>
+ <FormLabel>{t('settings.preferAttentionStyleNumeric')}</FormLabel>
+ <Switch
+ isChecked={prefersNumericAttentionWeights}
+ onChange={handleChangePreferAttentionStyleNumeric}
+ />
+ </FormControl>
+ </StickyScrollable>
+
<StickyScrollable title={t('settings.developer')}>
<SettingsDeveloperLogIsEnabled />
<SettingsDeveloperLogLevel />
diff --git a/invokeai/frontend/web/src/features/system/store/systemSlice.ts b/invokeai/frontend/web/src/features/system/store/systemSlice.ts
index 1cc22c8dea..e4346a1794 100644
--- a/invokeai/frontend/web/src/features/system/store/systemSlice.ts
+++ b/invokeai/frontend/web/src/features/system/store/systemSlice.ts
@@ -26,6 +26,7 @@ const getInitialState = (): SystemState => ({
logNamespaces: [...zLogNamespace.options],
shouldShowInvocationProgressDetail: false,
shouldHighlightFocusedRegions: false,
+ prefersNumericAttentionWeights: false,
});
const slice = createSlice({
@@ -69,6 +70,9 @@ const slice = createSlice({
shouldConfirmOnNewSessionToggled(state) {
state.shouldConfirmOnNewSession = !state.shouldConfirmOnNewSession;
},
+ setPrefersNumericAttentionStyle(state, action: PayloadAction<boolean>) {
+ state.prefersNumericAttentionWeights = action.payload;
+ },
setShouldShowInvocationProgressDetail(state, action: PayloadAction<boolean>) {
state.shouldShowInvocationProgressDetail = action.payload;
},
@@ -91,6 +95,7 @@ export const {
setShouldEnableModelDescriptions,
shouldConfirmOnNewSessionToggled,
setShouldShowInvocationProgressDetail,
+ setPrefersNumericAttentionStyle,
setShouldHighlightFocusedRegions,
} = slice.actions;
@@ -136,6 +141,9 @@ export const selectSystemShouldEnableModelDescriptions = createSystemSelector(
export const selectSystemShouldEnableHighlightFocusedRegions = createSystemSelector(
(system) => system.shouldHighlightFocusedRegions
);
+export const selectSystemPrefersNumericAttentionWeights = createSystemSelector(
+ (system) => system.prefersNumericAttentionWeights
+);
export const selectSystemShouldConfirmOnNewSession = createSystemSelector((system) => system.shouldConfirmOnNewSession);
export const selectSystemShouldShowInvocationProgressDetail = createSystemSelector(
(system) => system.shouldShowInvocationProgressDetail
diff --git a/invokeai/frontend/web/src/features/system/store/types.ts b/invokeai/frontend/web/src/features/system/store/types.ts
index 3eaf8628c6..4cf4fb784b 100644
--- a/invokeai/frontend/web/src/features/system/store/types.ts
+++ b/invokeai/frontend/web/src/features/system/store/types.ts
@@ -44,5 +44,6 @@ export const zSystemState = z.object({
logNamespaces: z.array(zLogNamespace),
shouldShowInvocationProgressDetail: z.boolean(),
shouldHighlightFocusedRegions: z.boolean(),
+ prefersNumericAttentionWeights: z.boolean(),
});
export type SystemState = z.infer<typeof zSystemState>;