Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(prompts): give each system prompt its own Expand Prompt output cap
Lincoln Stein42ab6b1f01bf
diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex 019a5ff11a..aeabc541e2 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -17,6 +17,11 @@ from invokeai.app.api.routers.image_move_maintenance import assert_image_move_mafrom invokeai.app.services.events.events_base import EventServiceBasefrom invokeai.app.services.image_files.image_files_common import ImageFileNotFoundExceptionfrom invokeai.app.services.model_records.model_records_base import UnknownModelException+from invokeai.app.services.system_prompt_records.system_prompt_records_common import (+ EXPAND_PROMPT_MAX_TOKENS_DEFAULT,+ EXPAND_PROMPT_MAX_TOKENS_MAX,+ EXPAND_PROMPT_MAX_TOKENS_MIN,+)from invokeai.app.services.wildcard_records.wildcard_records_common import build_wildcard_managerfrom invokeai.app.util.dynamicprompts import expand_dynamic_promptfrom invokeai.app.util.misc import SEED_MAX, get_random_seed@@ -71,7 +76,15 @@ def parse_dynamicprompts(class ExpandPromptRequest(BaseModel):prompt: strmodel_key: str- max_tokens: int = Field(default=300, ge=1, le=2048)+ max_tokens: int = Field(+ default=EXPAND_PROMPT_MAX_TOKENS_DEFAULT,+ ge=EXPAND_PROMPT_MAX_TOKENS_MIN,+ le=EXPAND_PROMPT_MAX_TOKENS_MAX,+ description=(+ "Cap on the tokens the LLM may emit. Clients that expand with a stored system prompt "+ "send that prompt's own `max_tokens` here; omitting it uses the default."+ ),+ )system_prompt: str | None = Noneseed: int | None = Field(default=None, ge=0, le=SEED_MAX, description="Seed for reproducible text generation")task_id: str | None = Field(diff --git a/invokeai/app/invocations/text_llm.py b/invokeai/app/invocations/text_llm.pyindex 036591bdd1..1d6c99d2e7 100644--- a/invokeai/app/invocations/text_llm.py+++ b/invokeai/app/invocations/text_llm.py@@ -7,6 +7,9 @@ from invokeai.app.invocations.model import ModelIdentifierFieldfrom invokeai.app.invocations.primitives import StringOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.services.system_prompt_records.system_prompt_records_common import (+ EXPAND_PROMPT_MAX_TOKENS_DEFAULT,+ EXPAND_PROMPT_MAX_TOKENS_MAX,+ EXPAND_PROMPT_MAX_TOKENS_MIN,SystemPromptNotFoundError,SystemPromptRecordDTO,)@@ -70,9 +73,9 @@ class TextLLMInvocation(BaseInvocation):ui_model_type=ModelType.TextLLM,)max_tokens: int = InputField(- default=300,- ge=1,- le=2048,+ default=EXPAND_PROMPT_MAX_TOKENS_DEFAULT,+ ge=EXPAND_PROMPT_MAX_TOKENS_MIN,+ le=EXPAND_PROMPT_MAX_TOKENS_MAX,description="Maximum number of tokens to generate.",)seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)@@ -95,7 +98,7 @@ class TextLLMInvocation(BaseInvocation):title="Text LLM (with System Prompt Preset)",tags=["llm", "text", "prompt", "preset", "template"],category="llm",- version="1.1.0",+ version="1.2.0",classification=Classification.Beta,)class TextLLMWithPresetInvocation(BaseInvocation):@@ -124,11 +127,12 @@ class TextLLMWithPresetInvocation(BaseInvocation):description=FieldDescriptions.text_llm_model,ui_model_type=ModelType.TextLLM,)- max_tokens: int = InputField(- default=300,- ge=1,- le=2048,- description="Maximum number of tokens to generate.",+ max_tokens: int | None = InputField(+ default=None,+ ge=EXPAND_PROMPT_MAX_TOKENS_MIN,+ le=EXPAND_PROMPT_MAX_TOKENS_MAX,+ description="Maximum number of tokens to generate. Leave unset to use the preset's own cap, "+ f"or {EXPAND_PROMPT_MAX_TOKENS_DEFAULT} if it does not set one.",)seed: int = InputField(default=0, ge=0, le=SEED_MAX, description=FieldDescriptions.seed)@@ -174,7 +178,17 @@ class TextLLMWithPresetInvocation(BaseInvocation):text_llm_model=self.text_llm_model,prompt=self.prompt,system_prompt=record.content,- max_tokens=self.max_tokens,+ # The preset carries its own output-length cap (structured prompts need more room+ # than the default), so an unset field defers to it rather than to a fixed number.+ # An explicit field value still wins -- it is the node author overriding the preset.+ max_tokens=self._resolve_max_tokens(record),seed=self.seed,)return StringOutput(value=output)++ def _resolve_max_tokens(self, record: SystemPromptRecordDTO) -> int:+ if self.max_tokens is not None:+ return self.max_tokens+ if record.max_tokens is not None:+ return record.max_tokens+ return EXPAND_PROMPT_MAX_TOKENS_DEFAULTdiff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_09_add_system_prompt_max_tokens.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_09_add_system_prompt_max_tokens.pynew file mode 100644index 0000000000..8243fecabc--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_09_add_system_prompt_max_tokens.py@@ -0,0 +1,53 @@+"""Give each system prompt its own optional cap on the Expand Prompt LLM's output length.++Expand Prompt asks the text LLM for at most ``EXPAND_PROMPT_MAX_TOKENS_DEFAULT`` (300) new+tokens. That suits the one-paragraph rewrites the original seeded prompts produce, but truncates+prompts that are structurally longer by design -- the MiniMax H3 Ref2VA prompt emits six labelled+sections and routinely needs more.++The cap therefore becomes a property of the system prompt: ``max_tokens`` is NULL for every+existing row (meaning "use the default"), and is set to 500 for the Ref2VA prompt.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_07_add_minimax_h3_ref2va_system_prompt import (+ MINIMAX_H3_REF2VA_PROMPT_ID,+)+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration++MINIMAX_H3_REF2VA_MAX_TOKENS = 500+"""Headroom for the six-section structured prompt, measured against the seeded example."""+++class AddSystemPromptMaxTokensCallback:+ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute("PRAGMA table_info(system_prompts);")+ # SQLite has no ADD COLUMN IF NOT EXISTS. The migrator already guarantees this callback+ # runs at most once per database and rolls the whole thing back on failure, so this guard+ # is for a hand-modified database only -- not a sequence the app can produce.+ if "max_tokens" not in {row[1] for row in cursor.fetchall()}:+ cursor.execute("ALTER TABLE system_prompts ADD COLUMN max_tokens INTEGER;")++ # Every row is NULL immediately after the ALTER above, so the IS NULL scope only matters+ # if the column already existed -- see the guard above. Kept so that re-running the+ # callback by hand cannot overwrite a cap the user has since chosen.+ cursor.execute(+ """--sql+ UPDATE system_prompts SET max_tokens = ? WHERE id = ? AND max_tokens IS NULL;+ """,+ (MINIMAX_H3_REF2VA_MAX_TOKENS, MINIMAX_H3_REF2VA_PROMPT_ID),+ )+++def build_migration() -> Migration:+ """Add ``system_prompts.max_tokens`` and give the Ref2VA prompt the room it needs.++ Depends on the Ref2VA seed rather than on the table creation: the row it raises the cap on+ must already exist.+ """+ return Migration(+ id="2026_09_09_add_system_prompt_max_tokens",+ depends_on="2026_09_07_add_minimax_h3_ref2va_system_prompt",+ callback=AddSystemPromptMaxTokensCallback(),+ )diff --git a/invokeai/app/services/system_prompt_records/system_prompt_records_common.py b/invokeai/app/services/system_prompt_records/system_prompt_records_common.pyindex f25bc99085..9770f7728c 100644--- a/invokeai/app/services/system_prompt_records/system_prompt_records_common.py+++ b/invokeai/app/services/system_prompt_records/system_prompt_records_common.py@@ -3,6 +3,18 @@ from typing import Any, Optionalfrom pydantic import BaseModel, Field, TypeAdapter+EXPAND_PROMPT_MAX_TOKENS_DEFAULT = 300+"""Output-length cap applied to Expand Prompt when the selected system prompt names none.++Lives here rather than in the router so the storage layer, the request model and the migration+that seeds per-prompt caps all agree on one number without the API module having to be imported+(it pulls in the ML stack).+"""++EXPAND_PROMPT_MAX_TOKENS_MIN = 1+EXPAND_PROMPT_MAX_TOKENS_MAX = 2048+"""Bounds a per-prompt cap must fall inside; also the bounds the expand-prompt request enforces."""+SYSTEM_PROMPT_DEFAULT_USER_ID = "system""""Owner of the seeded default prompts.@@ -24,12 +36,30 @@ class SystemPromptNotAuthorizedError(Exception):class SystemPromptWithoutId(BaseModel, extra="forbid"):name: str = Field(min_length=1, description="The name of the system prompt.")content: str = Field(min_length=1, description="The system prompt content.")+ max_tokens: Optional[int] = Field(+ default=None,+ ge=EXPAND_PROMPT_MAX_TOKENS_MIN,+ le=EXPAND_PROMPT_MAX_TOKENS_MAX,+ description=(+ "Cap on the tokens the LLM may emit when expanding with this prompt. "+ f"Null means use the default of {EXPAND_PROMPT_MAX_TOKENS_DEFAULT}."+ ),+ )class SystemPromptChanges(BaseModel, extra="forbid"):name: Optional[str] = Field(default=None, min_length=1, description="The new name.")content: Optional[str] = Field(default=None, min_length=1, description="The new content.")is_public: Optional[bool] = Field(default=None, description="Whether the prompt is shared with all users.")+ max_tokens: Optional[int] = Field(+ default=None,+ ge=EXPAND_PROMPT_MAX_TOKENS_MIN,+ le=EXPAND_PROMPT_MAX_TOKENS_MAX,+ description=(+ "The new output-token cap. Unlike the other fields, an explicitly supplied null is a "+ "change -- it clears the cap back to the default; omitting the field leaves it alone."+ ),+ )class SystemPromptRecordDTO(SystemPromptWithoutId):diff --git a/invokeai/app/services/system_prompt_records/system_prompt_records_sqlite.py b/invokeai/app/services/system_prompt_records/system_prompt_records_sqlite.pyindex cfe14a48fb..e7f05887dd 100644--- a/invokeai/app/services/system_prompt_records/system_prompt_records_sqlite.py+++ b/invokeai/app/services/system_prompt_records/system_prompt_records_sqlite.py@@ -41,10 +41,17 @@ class SqliteSystemPromptRecordsStorage(SystemPromptRecordsStorageBase):with self._db.transaction() as cursor:cursor.execute("""--sql- INSERT INTO system_prompts (id, name, content, user_id, is_public)- VALUES (?, ?, ?, ?, ?);+ INSERT INTO system_prompts (id, name, content, user_id, is_public, max_tokens)+ VALUES (?, ?, ?, ?, ?, ?);""",- (system_prompt_id, system_prompt.name, system_prompt.content, user_id, is_public),+ (+ system_prompt_id,+ system_prompt.name,+ system_prompt.content,+ user_id,+ is_public,+ system_prompt.max_tokens,+ ),)return self.get(system_prompt_id)@@ -84,6 +91,14 @@ class SqliteSystemPromptRecordsStorage(SystemPromptRecordsStorageBase):f"UPDATE system_prompts SET is_public = ? WHERE id = ?{scope_clause};",(changes.is_public, system_prompt_id, *scope_args),)+ # `max_tokens` is the one field whose null is a value rather than "no change": it means+ # "drop back to the endpoint default". `is not None` would make a cap unclearable once+ # set, so the presence of the key in the request body decides instead.+ if "max_tokens" in changes.model_fields_set:+ cursor.execute(+ f"UPDATE system_prompts SET max_tokens = ? WHERE id = ?{scope_clause};",+ (changes.max_tokens, system_prompt_id, *scope_args),+ )return self.get(system_prompt_id)def delete(self, system_prompt_id: str, user_id: Optional[str] = None) -> None:diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 3c91d6a743..005b594fb8 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -29181,6 +29181,7 @@"maximum": 2048.0,"minimum": 1.0,"title": "Max Tokens",+ "description": "Cap on the tokens the LLM may emit. Clients that expand with a stored system prompt send that prompt's own `max_tokens` here; omitting it uses the default.","default": 300},"system_prompt": {@@ -90834,6 +90835,20 @@],"title": "Is Public","description": "Whether the prompt is shared with all users."+ },+ "max_tokens": {+ "anyOf": [+ {+ "type": "integer",+ "maximum": 2048.0,+ "minimum": 1.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Max Tokens",+ "description": "The new output-token cap. Unlike the other fields, an explicitly supplied null is a change -- it clears the cap back to the default; omitting the field leaves it alone."}},"additionalProperties": false,@@ -90867,6 +90882,20 @@"title": "Content","description": "The system prompt content."},+ "max_tokens": {+ "anyOf": [+ {+ "type": "integer",+ "maximum": 2048.0,+ "minimum": 1.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Max Tokens",+ "description": "Cap on the tokens the LLM may emit when expanding with this prompt. Null means use the default of 300."+ },"id": {"type": "string","title": "Id",@@ -90913,6 +90942,20 @@"minLength": 1,"title": "Content","description": "The system prompt content."+ },+ "max_tokens": {+ "anyOf": [+ {+ "type": "integer",+ "maximum": 2048.0,+ "minimum": 1.0+ },+ {+ "type": "null"+ }+ ],+ "title": "Max Tokens",+ "description": "Cap on the tokens the LLM may emit when expanding with this prompt. Null means use the default of 300."}},"additionalProperties": false,@@ -93010,16 +93053,23 @@"ui_model_type": ["text_llm"]},"max_tokens": {- "default": 300,- "description": "Maximum number of tokens to generate.",+ "anyOf": [+ {+ "maximum": 2048,+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Maximum number of tokens to generate. Leave unset to use the preset's own cap, or 300 if it does not set one.","field_kind": "input","input": "any",- "maximum": 2048,- "minimum": 1,- "orig_default": 300,+ "orig_default": null,"orig_required": false,- "title": "Max Tokens",- "type": "integer"+ "title": "Max Tokens"},"seed": {"default": 0,@@ -93045,7 +93095,7 @@"tags": ["llm", "text", "prompt", "preset", "template"],"title": "Text LLM (with System Prompt Preset)","type": "object",- "version": "1.1.0",+ "version": "1.2.0","output": {"$ref": "#/components/schemas/StringOutput"}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex b518139f96..a0756ef06d 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -11376,6 +11376,7 @@ export type components = {model_key: string;/*** Max Tokens+ * @description Cap on the tokens the LLM may emit. Clients that expand with a stored system prompt send that prompt's own `max_tokens` here; omitting it uses the default.* @default 300*/max_tokens?: number;@@ -39692,6 +39693,11 @@ export type components = {* @description Whether the prompt is shared with all users.*/is_public?: boolean | null;+ /**+ * Max Tokens+ * @description The new output-token cap. Unlike the other fields, an explicitly supplied null is a change -- it clears the cap back to the default; omitting the field leaves it alone.+ */+ max_tokens?: number | null;};/*** SystemPromptField@@ -39716,6 +39722,11 @@ export type components = {* @description The system prompt content.*/content: string;+ /**+ * Max Tokens+ * @description Cap on the tokens the LLM may emit when expanding with this prompt. Null means use the default of 300.+ */+ max_tokens?: number | null;/*** Id* @description The system prompt ID.@@ -39756,6 +39767,11 @@ export type components = {* @description The system prompt content.*/content: string;+ /**+ * Max Tokens+ * @description Cap on the tokens the LLM may emit when expanding with this prompt. Null means use the default of 300.+ */+ max_tokens?: number | null;};/** T2IAdapterField */T2IAdapterField: {@@ -40983,10 +40999,10 @@ export type components = {text_llm_model?: components["schemas"]["ModelIdentifierField"] | null;/*** Max Tokens- * @description Maximum number of tokens to generate.- * @default 300+ * @description Maximum number of tokens to generate. Leave unset to use the preset's own cap, or 300 if it does not set one.+ * @default null*/- max_tokens?: number;+ max_tokens?: number | null;/*** Seed* @description Seed for random number generationdiff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 9faafcbd3a..6fb11ed9d3 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1972,6 +1972,9 @@"namePlaceholder": "Concise and literal","content": "Instructions","contentPlaceholder": "Describe how the model should rewrite the prompt.",+ "maxTokens": "Max output length",+ "maxTokensHelp": "Tokens the model may generate with this prompt. Leave empty for the default ({{tokens}}).",+ "maxTokensInvalid": "Enter a whole number between {{min}} and {{max}}, or leave it empty.","none": "No system prompts","shared": "Shared","deleteTitle": "Delete system prompt",diff --git a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.tsindex 304c9f4f68..87916acc0b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.test.ts@@ -3,8 +3,11 @@ import { describe, expect, it } from 'vitest';import {classifySystemPrompts,isOwnedSystemPrompt,+ parseMaxTokensInput,requireOwnedSystemPrompt,resolveSelectedSystemPromptId,+ SYSTEM_PROMPT_MAX_TOKENS_MAX,+ SYSTEM_PROMPT_MAX_TOKENS_MIN,SystemPromptOwnershipError,} from './systemPrompts';@@ -85,3 +88,28 @@ describe('resolveSelectedSystemPromptId', () => {expect(resolveSelectedSystemPromptId([], null)).toBeNull();});});++describe('parseMaxTokensInput', () => {+ it('reads an empty field as "use the backend default"', () => {+ expect(parseMaxTokensInput('')).toBeNull();+ expect(parseMaxTokensInput(' ')).toBeNull();+ });++ it('accepts a whole number inside the range the endpoint enforces', () => {+ expect(parseMaxTokensInput('500')).toBe(500);+ expect(parseMaxTokensInput(String(SYSTEM_PROMPT_MAX_TOKENS_MIN))).toBe(SYSTEM_PROMPT_MAX_TOKENS_MIN);+ expect(parseMaxTokensInput(String(SYSTEM_PROMPT_MAX_TOKENS_MAX))).toBe(SYSTEM_PROMPT_MAX_TOKENS_MAX);+ });++ it('rejects values the endpoint would 422 on', () => {+ expect(parseMaxTokensInput('0')).toBe('invalid');+ expect(parseMaxTokensInput(String(SYSTEM_PROMPT_MAX_TOKENS_MAX + 1))).toBe('invalid');+ });++ it('rejects anything that is not a plain integer', () => {+ // All of these survive `Number()`, and none of them is a token count someone meant to type.+ for (const raw of ['12e2', '1.5', '-5', '0x10', 'abc', '5 0']) {+ expect(parseMaxTokensInput(raw)).toBe('invalid');+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.tsindex 44147a34fd..a0db8deebd 100644--- a/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/systemPrompts.ts@@ -79,3 +79,44 @@ export const resolveSelectedSystemPromptId = (return prompts[0]?.id ?? null;};++/**+ * Bounds the Expand Prompt endpoint enforces on a per-prompt output-token cap+ * (`ExpandPromptRequest.max_tokens`). Kept here so the editor can reject a bad value in place+ * rather than surfacing a 422.+ */+export const SYSTEM_PROMPT_MAX_TOKENS_MIN = 1;+export const SYSTEM_PROMPT_MAX_TOKENS_MAX = 2048;+/** What the backend uses when a prompt names no cap of its own. Shown as the field's placeholder. */+export const SYSTEM_PROMPT_MAX_TOKENS_DEFAULT = 300;++/** `null` = leave it to the backend default; `'invalid'` = not saveable. */+export type ParsedMaxTokens = number | null | 'invalid';++/**+ * Reads the editor's max-tokens input.+ *+ * The draft holds the raw string rather than a number so a half-typed value is never clamped+ * out from under the user; the result is only interpreted on save.+ */+export const parseMaxTokensInput = (raw: string): ParsedMaxTokens => {+ const trimmed = raw.trim();++ if (trimmed === '') {+ return null;+ }++ // Deliberately strict: `Number('12e3')` and `Number(' 12 ')` both parse, and neither is a+ // token count anyone meant to type.+ if (!/^\d+$/.test(trimmed)) {+ return 'invalid';+ }++ const parsed = Number(trimmed);++ if (parsed < SYSTEM_PROMPT_MAX_TOKENS_MIN || parsed > SYSTEM_PROMPT_MAX_TOKENS_MAX) {+ return 'invalid';+ }++ return parsed;+};diff --git a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.tsnew file mode 100644index 0000000000..025b67b961--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const transport = vi.hoisted(() => ({+ apiFetch: vi.fn(),+ apiFetchJson: vi.fn(),+}));++vi.mock('@platform/transport/http', () => ({+ absolutizeApiUrl: (path: string) => path,+ apiFetch: transport.apiFetch,+ apiFetchJson: transport.apiFetchJson,+}));++vi.mock('@platform/state/accountLifecycle', () => ({+ assertAccountScopeCurrent: vi.fn(),+ captureAccountScope: () => ({ signal: new AbortController().signal }),+}));++import { createSystemPrompt, updateSystemPrompt } from './systemPrompts';++const dto = {+ content: 'Rewrite the prompt.',+ id: 'prompt-1',+ is_public: true,+ max_tokens: 500,+ name: 'Ref2VA',+ user_id: 'system',+};++const sentBody = (): Record<string, unknown> => {+ const init = transport.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined;++ return JSON.parse(init?.body as string) as Record<string, unknown>;+};++beforeEach(() => {+ transport.apiFetch.mockReset();+ transport.apiFetchJson.mockReset();+ transport.apiFetchJson.mockResolvedValue(dto);+});++describe('system prompt max_tokens', () => {+ it('maps a stored cap onto the record', async () => {+ const created = await createSystemPrompt({ content: dto.content, maxTokens: 500, name: dto.name });++ expect(created.maxTokens).toBe(500);+ });++ it('reads a prompt with no cap as null', async () => {+ transport.apiFetchJson.mockResolvedValue({ ...dto, max_tokens: null });++ const created = await createSystemPrompt({ content: dto.content, maxTokens: null, name: dto.name });++ expect(created.maxTokens).toBeNull();+ });++ it('sends the cap on create', async () => {+ await createSystemPrompt({ content: dto.content, maxTokens: 500, name: dto.name });++ expect(sentBody().max_tokens).toBe(500);+ });++ it('sends an explicit null on update so a cap can be cleared', async () => {+ // The backend distinguishes a present null ("back to the default") from an omitted key+ // ("leave it alone"), so the key must survive JSON.stringify.+ await updateSystemPrompt('prompt-1', { content: dto.content, maxTokens: null, name: dto.name });++ const body = sentBody();++ expect('max_tokens' in body).toBe(true);+ expect(body.max_tokens).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.tsindex 1430a21739..0e477825d4 100644--- a/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/systemPrompts.ts@@ -12,6 +12,7 @@ interface SystemPromptDTO {content: string;user_id: string;is_public: boolean;+ max_tokens: number | null;}export interface SystemPromptRecord {@@ -20,11 +21,14 @@ export interface SystemPromptRecord {content: string;userId: string;isPublic: boolean;+ /** Cap on the tokens Expand Prompt may generate with this prompt; null means the backend default. */+ maxTokens: number | null;}export interface SystemPromptDraft {name: string;content: string;+ maxTokens: number | null;}export const systemPromptKeys = {@@ -36,6 +40,8 @@ const mapSystemPrompt = (dto: SystemPromptDTO): SystemPromptRecord => ({content: dto.content,id: dto.id,isPublic: dto.is_public,+ // Absent on a backend older than the column; treated the same as an unset cap.+ maxTokens: dto.max_tokens ?? null,name: dto.name,userId: dto.user_id,});@@ -61,7 +67,7 @@ export const systemPromptsQueryOptions = () =>export const createSystemPrompt = async (draft: SystemPromptDraft): Promise<SystemPromptRecord> =>mapSystemPrompt(await apiFetchJson<SystemPromptDTO>(`${SYSTEM_PROMPTS_BASE}/`, {- body: JSON.stringify({ content: draft.content, name: draft.name }),+ body: JSON.stringify({ content: draft.content, max_tokens: draft.maxTokens, name: draft.name }),method: 'POST',}));@@ -69,7 +75,9 @@ export const createSystemPrompt = async (draft: SystemPromptDraft): Promise<Systexport const updateSystemPrompt = async (id: string, draft: SystemPromptDraft): Promise<SystemPromptRecord> =>mapSystemPrompt(await apiFetchJson<SystemPromptDTO>(`${SYSTEM_PROMPTS_BASE}/i/${encodeURIComponent(id)}`, {- body: JSON.stringify({ content: draft.content, name: draft.name }),+ // `max_tokens` is sent on every update, including as an explicit null: the backend reads a+ // present-but-null as "clear the cap", and an omitted key as "leave it alone".+ body: JSON.stringify({ content: draft.content, max_tokens: draft.maxTokens, name: draft.name }),method: 'PATCH',}));diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex 42b691d4ba..c5a1c0f3b5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -442,6 +442,9 @@ const ExpandPromptButton = ({try {const result = await expandPrompt({+ // A structured prompt needs more room than the endpoint's default allows, so the+ // selected prompt's own cap travels with it. Omitted when it has none.+ max_tokens: selectedSystemPrompt?.maxTokens ?? undefined,model_key: selectedModel.key,prompt: positivePrompt,system_prompt: selectedSystemPrompt?.content ?? null,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsxindex 6135214337..bd8cf7579e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/SystemPromptsField.tsx@@ -3,6 +3,12 @@ import type { SystemPromptCatalog } from '@features/generation/ui/promptFields/uimport type { ChangeEvent } from 'react';import { createListCollection, HStack, Input, Stack, Text, Textarea } from '@chakra-ui/react';+import {+ parseMaxTokensInput,+ SYSTEM_PROMPT_MAX_TOKENS_DEFAULT,+ SYSTEM_PROMPT_MAX_TOKENS_MAX,+ SYSTEM_PROMPT_MAX_TOKENS_MIN,+} from '@features/generation/core/systemPrompts';import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';// Imported by subpath rather than from the `@platform/ui` barrel, which is at its// direct-importer budget (a dev-invalidation limit) — depending on the components@@ -31,9 +37,11 @@ type EditorTarget = { record: SystemPromptRecord | null };interface Draft {name: string;content: string;+ /** Raw input text — see `parseMaxTokensInput`. Empty means "use the backend default". */+ maxTokens: string;}-const EMPTY_DRAFT: Draft = { content: '', name: '' };+const EMPTY_DRAFT: Draft = { content: '', maxTokens: '', name: '' };const SystemPromptRow = ({canEdit,@@ -86,6 +94,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromconst { t } = useTranslation();const selectId = useId();const nameFieldId = useId();+ const maxTokensFieldId = useId();const [isManaging, setIsManaging] = useState(false);const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);const [draft, setDraft] = useState<Draft>(EMPTY_DRAFT);@@ -110,7 +119,11 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemProm}, []);const startEdit = useCallback((record: SystemPromptRecord) => {- setDraft({ content: record.content, name: record.name });+ setDraft({+ content: record.content,+ maxTokens: record.maxTokens === null ? '' : String(record.maxTokens),+ name: record.name,+ });setEditorTarget({ record });}, []);@@ -121,13 +134,29 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromreturn;}+ const maxTokens = parseMaxTokensInput(draft.maxTokens);++ // Save is disabled while the field is invalid, so this only catches a submit that raced the+ // keystroke that broke it.+ if (maxTokens === 'invalid') {+ setError(+ t('widgets.generate.systemPrompts.maxTokensInvalid', {+ max: SYSTEM_PROMPT_MAX_TOKENS_MAX,+ min: SYSTEM_PROMPT_MAX_TOKENS_MIN,+ })+ );+ return;+ }++ const payload = { content: draft.content, maxTokens, name: draft.name };+setIsSaving(true);setError(null);let saved: SystemPromptRecord;try {- saved = editorTarget.record ? await catalog.update(editorTarget.record, draft) : await catalog.create(draft);+ saved = editorTarget.record ? await catalog.update(editorTarget.record, payload) : await catalog.create(payload);} catch (caught) {// `ApiError.message` is the raw response body, so the backend's own explanation only// reads properly once unwrapped. Reported in place — the popover has no toast surface.@@ -179,8 +208,22 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemProm(event: ChangeEvent<HTMLTextAreaElement>) => setDraft((current) => ({ ...current, content: event.target.value })),[]);+ const handleMaxTokensChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => setDraft((current) => ({ ...current, maxTokens: event.target.value })),+ []+ );const handleSelectChange = useCallback(({ value }: { value: string[] }) => onSelect(value[0] ?? null), [onSelect]);+ const isMaxTokensInvalid = parseMaxTokensInput(draft.maxTokens) === 'invalid';+ // Reported under the field as it is typed rather than only on save, since an out-of-range+ // cap is the one thing here the backend would reject with a bare 422.+ const maxTokensError = isMaxTokensInvalid+ ? t('widgets.generate.systemPrompts.maxTokensInvalid', {+ max: SYSTEM_PROMPT_MAX_TOKENS_MAX,+ min: SYSTEM_PROMPT_MAX_TOKENS_MIN,+ })+ : null;+const selectValue = useMemo(() => (selectedId ? [selectedId] : []), [selectedId]);// The Select primitive renders `valueText` verbatim in the closed trigger, so// it must carry the selected prompt's name — a static string would mask the@@ -215,6 +258,23 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemPromvalue={draft.content}onChange={handleContentChange}/>+ <Field+ error={maxTokensError}+ helpText={t('widgets.generate.systemPrompts.maxTokensHelp', { tokens: SYSTEM_PROMPT_MAX_TOKENS_DEFAULT })}+ id={maxTokensFieldId}+ label={t('widgets.generate.systemPrompts.maxTokens')}+ >+ <Input+ id={maxTokensFieldId}+ // `inputMode` rather than `type="number"`: the spinner and the browser's own+ // out-of-range handling would fight the empty-means-default reading of this field.+ inputMode="numeric"+ placeholder={String(SYSTEM_PROMPT_MAX_TOKENS_DEFAULT)}+ size="xs"+ value={draft.maxTokens}+ onChange={handleMaxTokensChange}+ />+ </Field>{error ? (<Text color="fg.error" fontSize="xs">{error}@@ -225,7 +285,7 @@ export const SystemPromptsField = ({ catalog, onSelect, selectedId }: SystemProm{t('common.cancel')}</Button><Button- disabled={!draft.name.trim() || !draft.content.trim()}+ disabled={!draft.name.trim() || !draft.content.trim() || isMaxTokensInvalid}loading={isSaving}size="xs"onClick={handleSave}diff --git a/tests/app/invocations/test_text_llm_with_preset.py b/tests/app/invocations/test_text_llm_with_preset.pyindex c0f3b64528..fd3f692504 100644--- a/tests/app/invocations/test_text_llm_with_preset.py+++ b/tests/app/invocations/test_text_llm_with_preset.py@@ -15,17 +15,18 @@ from invokeai.app.invocations.fields import SystemPromptFieldfrom invokeai.app.invocations.model import ModelIdentifierFieldfrom invokeai.app.invocations.text_llm import TextLLMInvocation, TextLLMWithPresetInvocationfrom invokeai.app.services.system_prompt_records.system_prompt_records_common import (+ EXPAND_PROMPT_MAX_TOKENS_DEFAULT,SystemPromptNotFoundError,)-def _make_invocation(prompt_id: str = "test-id") -> TextLLMWithPresetInvocation:+def _make_invocation(prompt_id: str = "test-id", max_tokens: int | None = 50) -> TextLLMWithPresetInvocation:return TextLLMWithPresetInvocation(id="test-node",prompt="a cat",system_prompt=SystemPromptField(system_prompt_id=prompt_id),text_llm_model=ModelIdentifierField(key="dummy", hash="x", name="dummy", base="any", type="text_llm"),- max_tokens=50,+ max_tokens=max_tokens,seed=123,)@@ -53,6 +54,7 @@ def test_plain_text_llm_node_passes_seed_to_llm() -> None:def _make_context(prompt_record_content: str | None,*,+ record_max_tokens: int | None = None,multiuser: bool = False,record_user_id: str = "system",record_is_public: bool = True,@@ -70,6 +72,7 @@ def _make_context(else:record = MagicMock()record.content = prompt_record_content+ record.max_tokens = record_max_tokensrecord.user_id = record_user_idrecord.is_public = record_is_publiccontext._services.system_prompt_records.get.return_value = record@@ -191,3 +194,36 @@ def test_preset_node_skips_the_ownership_check_in_single_user_mode() -> None:context._services.users.get.assert_not_called()assert mock_run.call_count == 1+++def test_preset_node_uses_the_presets_own_cap_when_the_field_is_unset() -> None:+ # The whole point of a per-prompt cap: a structured preset that needs 500 tokens must not be+ # truncated at the shared default just because the workflow left the field alone.+ inv = _make_invocation(max_tokens=None)+ context = _make_context(prompt_record_content="structured instruction", record_max_tokens=500)++ with patch("invokeai.app.invocations.text_llm._run_text_llm", return_value="expanded") as mock_run:+ inv.invoke(context)++ assert mock_run.call_args.kwargs["max_tokens"] == 500+++def test_preset_node_falls_back_to_the_default_when_neither_names_a_cap() -> None:+ inv = _make_invocation(max_tokens=None)+ context = _make_context(prompt_record_content="instruction", record_max_tokens=None)++ with patch("invokeai.app.invocations.text_llm._run_text_llm", return_value="expanded") as mock_run:+ inv.invoke(context)++ assert mock_run.call_args.kwargs["max_tokens"] == EXPAND_PROMPT_MAX_TOKENS_DEFAULT+++def test_an_explicit_field_value_overrides_the_presets_cap() -> None:+ # An author who typed a number meant it, even when the preset carries one of its own.+ inv = _make_invocation(max_tokens=50)+ context = _make_context(prompt_record_content="instruction", record_max_tokens=500)++ with patch("invokeai.app.invocations.text_llm._run_text_llm", return_value="expanded") as mock_run:+ inv.invoke(context)++ assert mock_run.call_args.kwargs["max_tokens"] == 50diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_09_add_system_prompt_max_tokens.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_09_add_system_prompt_max_tokens.pynew file mode 100644index 0000000000..12e56a3f20--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_09_add_system_prompt_max_tokens.py@@ -0,0 +1,87 @@+import sqlite3++import pytest++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_07_10_create_system_prompts import (+ DEFAULT_SYSTEM_PROMPTS,+ CreateSystemPromptsCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_07_add_minimax_h3_ref2va_system_prompt import (+ MINIMAX_H3_REF2VA_PROMPT_ID,+ AddMiniMaxH3Ref2VASystemPromptCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_09_add_system_prompt_max_tokens import (+ MINIMAX_H3_REF2VA_MAX_TOKENS,+ AddSystemPromptMaxTokensCallback,+ build_migration,+)+from invokeai.app.services.system_prompt_records.system_prompt_records_common import (+ EXPAND_PROMPT_MAX_TOKENS_MAX,+ EXPAND_PROMPT_MAX_TOKENS_MIN,+)+++def db() -> sqlite3.Connection:+ connection = sqlite3.connect(":memory:")+ cursor = connection.cursor()+ CreateSystemPromptsCallback()(cursor)+ AddMiniMaxH3Ref2VASystemPromptCallback()(cursor)+ yield connection+ connection.close()+++def _max_tokens(cursor: sqlite3.Cursor, prompt_id: str) -> int | None:+ cursor.execute("SELECT max_tokens FROM system_prompts WHERE id = ?;", (prompt_id,))+ return cursor.fetchone()[0]+++def test_adds_a_nullable_column_that_leaves_existing_prompts_on_the_default(db: sqlite3.Connection) -> None:+ cursor = db.cursor()++ AddSystemPromptMaxTokensCallback()(cursor)++ # Every prompt but Ref2VA keeps NULL, which the API reads as "use the endpoint default".+ for default_id, _, _ in DEFAULT_SYSTEM_PROMPTS:+ assert _max_tokens(cursor, default_id) is None+++def test_raises_the_ref2va_cap(db: sqlite3.Connection) -> None:+ cursor = db.cursor()++ AddSystemPromptMaxTokensCallback()(cursor)++ assert _max_tokens(cursor, MINIMAX_H3_REF2VA_PROMPT_ID) == MINIMAX_H3_REF2VA_MAX_TOKENS+++def test_seeded_cap_is_within_the_range_the_api_accepts() -> None:+ assert EXPAND_PROMPT_MAX_TOKENS_MIN <= MINIMAX_H3_REF2VA_MAX_TOKENS <= EXPAND_PROMPT_MAX_TOKENS_MAX+++def test_is_idempotent_and_preserves_a_user_chosen_cap(db: sqlite3.Connection) -> None:+ cursor = db.cursor()++ AddSystemPromptMaxTokensCallback()(cursor)+ cursor.execute("UPDATE system_prompts SET max_tokens = 800 WHERE id = ?;", (MINIMAX_H3_REF2VA_PROMPT_ID,))++ # A re-run must neither fail on the already-present column nor undo the user's choice.+ AddSystemPromptMaxTokensCallback()(cursor)++ assert _max_tokens(cursor, MINIMAX_H3_REF2VA_PROMPT_ID) == 800+++def test_tolerates_a_deleted_ref2va_prompt(db: sqlite3.Connection) -> None:+ cursor = db.cursor()+ cursor.execute("DELETE FROM system_prompts WHERE id = ?;", (MINIMAX_H3_REF2VA_PROMPT_ID,))++ AddSystemPromptMaxTokensCallback()(cursor)++ cursor.execute("SELECT COUNT(*) FROM system_prompts WHERE id = ?;", (MINIMAX_H3_REF2VA_PROMPT_ID,))+ assert cursor.fetchone()[0] == 0+++def test_migration_id_matches_its_module_name() -> None:+ migration = build_migration()+ assert migration.id == "2026_09_09_add_system_prompt_max_tokens"+ # The Ref2VA row must exist before its cap can be raised.+ assert migration.depends_on == "2026_09_07_add_minimax_h3_ref2va_system_prompt"diff --git a/tests/app/services/test_system_prompt_records.py b/tests/app/services/test_system_prompt_records.pyindex fbce15822e..3bc54eaa59 100644--- a/tests/app/services/test_system_prompt_records.py+++ b/tests/app/services/test_system_prompt_records.py@@ -4,10 +4,15 @@ Covers the per-user scoping semantics added on top of the original CRUD:- get_many returns own + public for a user_id, all rows for None (admin)- update/delete with a non-owner user_id raises NotFound and leaves the row untouched- the migration-seeded defaults (user_id='system', is_public=TRUE) are visible to every user+- the per-prompt `max_tokens` cap, whose explicit null clears rather than meaning "no change""""+import pytest+from pydantic import ValidationError+from invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.system_prompt_records.system_prompt_records_common import (+ EXPAND_PROMPT_MAX_TOKENS_MAX,SystemPromptChanges,SystemPromptNotFoundError,SystemPromptWithoutId,@@ -154,3 +159,59 @@ def test_owner_can_flip_is_public() -> None:# Now visible to everyonebob_view = svc.get_many(user_id="bob")assert alice.id in {p.id for p in bob_view}+++def test_created_prompt_defaults_to_no_cap() -> None:+ # NULL is what tells the client to fall back to the endpoint default.+ svc = _storage()+ created = svc.create(SystemPromptWithoutId(name="alice", content="x"), user_id="alice")+ assert created.max_tokens is None+++def test_create_and_update_round_trip_a_cap() -> None:+ svc = _storage()+ created = svc.create(SystemPromptWithoutId(name="alice", content="x", max_tokens=500), user_id="alice")+ assert created.max_tokens == 500++ raised = svc.update(created.id, SystemPromptChanges(max_tokens=900), user_id="alice")+ assert raised.max_tokens == 900+++def test_update_that_omits_max_tokens_leaves_the_cap_alone() -> None:+ svc = _storage()+ created = svc.create(SystemPromptWithoutId(name="alice", content="x", max_tokens=500), user_id="alice")++ renamed = svc.update(created.id, SystemPromptChanges(name="renamed"), user_id="alice")++ assert renamed.max_tokens == 500+++def test_explicit_null_clears_the_cap_back_to_the_default() -> None:+ # The one field where null is a value rather than "no change" -- without this a cap could be+ # set but never removed.+ svc = _storage()+ created = svc.create(SystemPromptWithoutId(name="alice", content="x", max_tokens=500), user_id="alice")++ cleared = svc.update(created.id, SystemPromptChanges(max_tokens=None), user_id="alice")++ assert cleared.max_tokens is None+++def test_non_owner_cannot_change_the_cap() -> None:+ svc = _storage()+ alice = svc.create(SystemPromptWithoutId(name="alice", content="x", max_tokens=500), user_id="alice")++ try:+ svc.update(alice.id, SystemPromptChanges(max_tokens=2048), user_id="bob")+ raise AssertionError("expected SystemPromptNotFoundError")+ except SystemPromptNotFoundError:+ pass+ assert svc.get(alice.id).max_tokens == 500+++def test_out_of_range_caps_are_rejected_by_the_model() -> None:+ for out_of_range in (0, EXPAND_PROMPT_MAX_TOKENS_MAX + 1):+ with pytest.raises(ValidationError):+ SystemPromptWithoutId(name="alice", content="x", max_tokens=out_of_range)+ with pytest.raises(ValidationError):+ SystemPromptChanges(max_tokens=out_of_range)