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.

fix(images): display resolved inputs and preserve source graphs (#10035)

Nianze Wu4e15c9ef6e9a
diff --git a/docs/src/content/docs/development/Architecture/media-metadata.mdx b/docs/src/content/docs/development/Architecture/media-metadata.mdx
index 5cb7577909..9e62ab3b94 100644
--- a/docs/src/content/docs/development/Architecture/media-metadata.mdx
+++ b/docs/src/content/docs/development/Architecture/media-metadata.mdx
@@ -1,7 +1,7 @@
---
title: Media Metadata
description: How generation metadata travels inside PNG and MP4 files, the versioned record schema, and what a recall can restore on another install.
-lastUpdated: 2026-10-18
+lastUpdated: 2026-10-30
---
Every image and video InvokeAI produces carries its generation record **inside the file**, so a
@@ -9,15 +9,17 @@ download dropped into any Invoke instance is recallable and remixable without ac
database that produced it. This page is the reference for that contract: where the record lives
in each container, the record's fields, and how the format evolves.
-## Envelope: three keys, two containers
+## Envelope: shared keys and image inputs
-The same three strings are written to every media file. Each value is compact UTF-8 JSON.
+Three keys are shared by images and videos. Images generated from a graph also carry a
+separate resolved-input record. Values are JSON strings; saved workflow JSON retains its original bytes.
| Key | Content | Required |
|---|---|---|
| `invokeai_metadata` | The generation record (schema below) | when the graph produced one |
| `invokeai_workflow` | The `WorkflowWithoutID` the session ran, verbatim | only when a workflow was run |
-| `invokeai_graph` | The executed `Graph`, verbatim | when available |
+| `invokeai_graph` | For generated images, the complete session source `Graph`; videos retain their existing graph record | when available |
+| `invokeai_resolved_inputs` | PNG only: compact Graph JSON containing the active invocation's resolved inputs and ordinary ancestors | images generated from a graph |
| Container | Where the keys live | Writer | Reader |
|---|---|---|---|
@@ -27,8 +29,33 @@ The same three strings are written to every media file. Each value is compact UT
Both readers feed `extract_metadata` in `invokeai/app/api/extract_metadata.py`, which owns the
validation rules: the metadata must parse to a JSON object, the workflow must validate as a
`WorkflowWithoutID`, and the graph must be an object with a `nodes` object and an `edges` list.
-Anything else degrades to "absent". On upload, a client-supplied `metadata` form field wins over
-the embedded copy; workflow and graph are never client-overridable.
+Anything else degrades to "absent". The image reader additionally extracts optional
+`invokeai_resolved_inputs` using the same graph envelope checks, preserving the JSON string verbatim.
+These checks accept unknown community node types and unset connected fields without loading node schemas.
+A missing or malformed resolved-input record is ignored independently of the other channels.
+On image upload, the file is fully decoded in a worker thread before reading records, including
+PNG text chunks after IDAT. Records are extracted before cropping or resizing can discard `Image.info`
+and passed explicitly to the image service for persistence. A client-supplied `metadata` form field wins
+over the embedded copy; workflow, graph, and resolved inputs are never client-overridable.
+
+When workflow JSON is absent, the image editor converts `invokeai_graph` into an editable
+workflow. Keeping the source graph preserves original `Iterate`, `If`, and `Collect` nodes
+and their edges. `invokeai_resolved_inputs` is a separate PNG text chunk, exposed as optional
+`resolved_inputs` stringified Graph JSON in `GET /api/v1/images/i/{image_name}/workflow`. Inspection
+can prefer this record to display actual inputs, while `workflow` and `graph` retain their original
+contents for editor restoration. The route applies the same image read-access and storage-maintenance
+checks to all three fields. Older PNGs return `resolved_inputs: null`; responses that omit the field
+remain valid. Videos use the shared response model's `null` default and retain their existing metadata
+behavior. Shared metadata extraction and the MP4 reader retain their three-key contract; only the
+image reader fills the optional resolved-input field. The new response field does not
+reserve or replace any key inside user `invokeai_metadata`. No migration is needed.
+
+The resolved-input record includes ordinary ancestors, such as math nodes and a Noise node's
+actual seed, and stops at loop/control and collection boundaries. Values crossing those
+boundaries are already resolved on the retained downstream invocation. Each image stores one
+source graph plus this record, avoiding copies of the expanded runtime graph in nested batches.
+Literal collections in the source graph and collection inputs on retained invocations still
+contribute their full size; neither graph field is guaranteed to contain a single node.
The MP4 layout is the one `ffprobe`, `exiftool` and `mediainfo` display. Like PNG chunks it
survives a container-aware copy — for ffmpeg that is a remux with `-movflags use_metadata_tags`;
diff --git a/invokeai/app/api/extract_metadata.py b/invokeai/app/api/extract_metadata.py
index 04cc7579ea..1cde6a8486 100644
--- a/invokeai/app/api/extract_metadata.py
+++ b/invokeai/app/api/extract_metadata.py
@@ -1,9 +1,10 @@
"""Recovers the ``invokeai_metadata`` / ``invokeai_workflow`` / ``invokeai_graph`` strings a media
file carries, so an uploaded PNG or MP4 is recallable without the database that produced it.
-PNGs hold the three keys as text chunks; MP4s hold them as QuickTime keyed metadata (see
-``invokeai.app.util.mp4_metadata``). Both are stringified JSON written by this application,
-so the validation is the same for either source and lives in ``extract_metadata``.
+PNGs hold the shared keys and optional ``invokeai_resolved_inputs`` as text chunks; MP4s hold
+the three shared keys as QuickTime keyed metadata (see ``invokeai.app.util.mp4_metadata``).
+Both sources use the shared validation in ``extract_metadata``. The image entry point also
+reads resolved inputs using the same Graph JSON envelope validation as the source graph.
"""
import json
@@ -29,6 +30,24 @@ class ExtractedMetadata:
invokeai_metadata: str | None
invokeai_workflow: str | None
invokeai_graph: str | None
+ invokeai_resolved_inputs: str | None = None
+
+
+def _extract_graph(raw: object, logger: logging.Logger) -> str | None:
+ # Validate only the envelope: connected fields may be unset and community node types may be unavailable.
+ if isinstance(raw, str):
+ try:
+ parsed = json.loads(raw)
+ if not isinstance(parsed, dict):
+ raise ValueError("Not a dict")
+ if not isinstance(parsed.get("nodes"), dict):
+ raise ValueError("'nodes' is not a dict")
+ if not isinstance(parsed.get("edges"), list):
+ raise ValueError("'edges' is not a list")
+ return raw
+ except Exception as e:
+ logger.debug(f"Failed to parse graph for uploaded media, {e}")
+ return None
def extract_metadata(
@@ -88,35 +107,7 @@ def extract_metadata(
# We expect the graph, if embedded, to be a JSON-stringified Graph. We will store it as a string.
graph_raw = invokeai_graph_override if invokeai_graph_override is not None else embedded.get(GRAPH_KEY)
- # The fallback value for graph is None.
- stringified_graph: str | None = None
-
- if isinstance(graph_raw, str):
- try:
- # TODO(psyche): Due to pydantic's handling of None values, it is possible for the graph to fail validation,
- # even if it is a direct dump of a valid graph. Node fields in the graph are allowed to have be unset if
- # they have incoming connections, but something about the ser/de process cannot adequately handle this.
- #
- # In lieu of fixing the graph validation, we will just do a simple check here to see if the graph is dict
- # with the correct keys. This is not a perfect solution, but it should be good enough for now.
-
- # FIX ME: Validate the graph JSON before storing it
- # Graph.model_validate_json(graph_raw)
-
- # Crappy workaround to validate JSON
- graph_parsed = json.loads(graph_raw)
- if not isinstance(graph_parsed, dict):
- raise ValueError("Not a dict")
- if not isinstance(graph_parsed.get("nodes", None), dict):
- raise ValueError("'nodes' is not a dict")
- if not isinstance(graph_parsed.get("edges", None), list):
- raise ValueError("'edges' is not a list")
-
- # Looks good, overwrite the fallback value
- stringified_graph = graph_raw
- except Exception as e:
- logger.debug(f"Failed to parse graph for uploaded media, {e}")
- pass
+ stringified_graph = _extract_graph(graph_raw, logger)
return ExtractedMetadata(
invokeai_metadata=stringified_metadata, invokeai_workflow=stringified_workflow, invokeai_graph=stringified_graph
@@ -130,14 +121,16 @@ def extract_metadata_from_image(
invokeai_graph_override: str | None,
logger: logging.Logger,
) -> ExtractedMetadata:
- """Extracts and validates the metadata, workflow and graph embedded in a PIL Image's text chunks."""
- return extract_metadata(
+ """Extracts the three shared channels and optional resolved-input Graph JSON from an image's text chunks."""
+ extracted = extract_metadata(
pil_image.info,
invokeai_metadata_override,
invokeai_workflow_override,
invokeai_graph_override,
logger,
)
+ extracted.invokeai_resolved_inputs = _extract_graph(pil_image.info.get("invokeai_resolved_inputs"), logger)
+ return extracted
def extract_metadata_from_video(
diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py
index aa66a2f525..5c974bed3e 100644
--- a/invokeai/app/api/routers/images.py
+++ b/invokeai/app/api/routers/images.py
@@ -143,11 +143,28 @@ async def upload_image(
contents = await file.read()
try:
- pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))
+
+ def _read_image() -> Image.Image:
+ image = Image.open(io.BytesIO(contents))
+ # Pillow discovers PNG text chunks after IDAT only when the pixels are fully loaded.
+ image.load()
+ return image
+
+ pil_image = await asyncio.to_thread(_read_image)
except Exception:
ApiDependencies.invoker.services.logger.error(traceback.format_exc())
raise HTTPException(status_code=415, detail="Failed to read image")
+ # Read file records before pixel transforms: resizing through NumPy discards Image.info.
+ extracted_metadata = await asyncio.to_thread(
+ extract_metadata_from_image,
+ pil_image=pil_image,
+ invokeai_metadata_override=metadata,
+ invokeai_workflow_override=None,
+ invokeai_graph_override=None,
+ logger=ApiDependencies.invoker.services.logger,
+ )
+
if crop_visible:
try:
@@ -177,15 +194,6 @@ async def upload_image(
except Exception:
raise HTTPException(status_code=500, detail="Failed to resize image")
- extracted_metadata = await asyncio.to_thread(
- extract_metadata_from_image,
- pil_image=pil_image,
- invokeai_metadata_override=metadata,
- invokeai_workflow_override=None,
- invokeai_graph_override=None,
- logger=ApiDependencies.invoker.services.logger,
- )
-
try:
image_dto = await asyncio.to_thread(
ApiDependencies.invoker.services.images.create,
@@ -197,6 +205,7 @@ async def upload_image(
metadata=extracted_metadata.invokeai_metadata,
workflow=extracted_metadata.invokeai_workflow,
graph=extracted_metadata.invokeai_graph,
+ resolved_inputs=extracted_metadata.invokeai_resolved_inputs,
is_intermediate=is_intermediate,
user_id=current_user.user_id,
project_id=project_id,
@@ -380,6 +389,10 @@ def get_image_metadata(
class WorkflowAndGraphResponse(BaseModel):
workflow: Optional[str] = Field(description="The workflow used to generate the image, as stringified JSON")
graph: Optional[str] = Field(description="The graph used to generate the image, as stringified JSON")
+ resolved_inputs: Optional[str] = Field(
+ default=None,
+ description="The image's per-invocation resolved inputs, as stringified Graph JSON, when available",
+ )
@images_router.get(
@@ -395,7 +408,8 @@ def get_image_workflow(
try:
workflow = ApiDependencies.invoker.services.images.get_workflow(image_name)
graph = ApiDependencies.invoker.services.images.get_graph(image_name)
- return WorkflowAndGraphResponse(workflow=workflow, graph=graph)
+ resolved_inputs = ApiDependencies.invoker.services.images.get_resolved_inputs(image_name)
+ return WorkflowAndGraphResponse(workflow=workflow, graph=graph, resolved_inputs=resolved_inputs)
except Exception:
raise HTTPException(status_code=404)
diff --git a/invokeai/app/services/image_files/image_files_base.py b/invokeai/app/services/image_files/image_files_base.py
index 40bab0e532..d5e35f4923 100644
--- a/invokeai/app/services/image_files/image_files_base.py
+++ b/invokeai/app/services/image_files/image_files_base.py
@@ -63,6 +63,7 @@ class ImageFileStorageBase(ABC):
graph: Optional[str] = None,
thumbnail_size: int = 256,
image_subfolder: str = "",
+ resolved_inputs: Optional[str] = None,
) -> None:
"""Saves an image and a 256x256 WEBP thumbnail. Returns a tuple of the image name, thumbnail name, and created timestamp."""
pass
@@ -143,3 +144,8 @@ class ImageFileStorageBase(ABC):
def get_graph(self, image_name: str, image_subfolder: str = "") -> Optional[str]:
"""Gets the graph of an image."""
pass
+
+ @abstractmethod
+ def get_resolved_inputs(self, image_name: str, image_subfolder: str = "") -> Optional[str]:
+ """Gets the per-image resolved-input Graph JSON, when present."""
+ pass
diff --git a/invokeai/app/services/image_files/image_files_disk.py b/invokeai/app/services/image_files/image_files_disk.py
index 1624ee47f1..82764a6cbe 100644
--- a/invokeai/app/services/image_files/image_files_disk.py
+++ b/invokeai/app/services/image_files/image_files_disk.py
@@ -245,6 +245,7 @@ class DiskImageFileStorage(ImageFileStorageBase):
graph: Optional[str] = None,
thumbnail_size: int = 256,
image_subfolder: str = "",
+ resolved_inputs: Optional[str] = None,
) -> None:
image_path: Optional[Path] = None
thumbnail_path: Optional[Path] = None
@@ -270,6 +271,9 @@ class DiskImageFileStorage(ImageFileStorageBase):
if graph is not None:
info_dict["invokeai_graph"] = graph
pnginfo.add_text("invokeai_graph", graph)
+ if resolved_inputs is not None:
+ info_dict["invokeai_resolved_inputs"] = resolved_inputs
+ pnginfo.add_text("invokeai_resolved_inputs", resolved_inputs)
thumbnail_path = self.get_path(image_name, thumbnail=True, image_subfolder=image_subfolder)
thumbnail_existed = thumbnail_path.exists()
@@ -688,6 +692,13 @@ class DiskImageFileStorage(ImageFileStorageBase):
return graph
return None
+ def get_resolved_inputs(self, image_name: str, image_subfolder: str = "") -> str | None:
+ image = self.get(image_name, image_subfolder=image_subfolder)
+ resolved_inputs = image.info.get("invokeai_resolved_inputs", None)
+ if isinstance(resolved_inputs, str):
+ return resolved_inputs
+ return None
+
def __validate_storage_folders(self) -> None:
"""Checks if the required output folders exist and create them if they don't"""
folders: list[Path] = [self.__output_folder, self.__thumbnails_folder]
diff --git a/invokeai/app/services/images/images_base.py b/invokeai/app/services/images/images_base.py
index b83eac55b5..728e5e96d6 100644
--- a/invokeai/app/services/images/images_base.py
+++ b/invokeai/app/services/images/images_base.py
@@ -58,8 +58,9 @@ class ImageServiceABC(ABC):
graph: Optional[str] = None,
user_id: Optional[str] = None,
project_id: Optional[str] = None,
+ resolved_inputs: Optional[str] = None,
) -> ImageDTO:
- """Creates an image, storing the file and its metadata."""
+ """Creates an image, storing its metadata and optional per-image resolved-input Graph JSON."""
pass
@abstractmethod
@@ -116,6 +117,11 @@ class ImageServiceABC(ABC):
"""Gets an image's workflow."""
pass
+ @abstractmethod
+ def get_resolved_inputs(self, image_name: str) -> Optional[str]:
+ """Gets an image's resolved-input Graph JSON, when present."""
+ pass
+
@abstractmethod
def get_path(self, image_name: str, thumbnail: bool = False) -> str:
"""Gets an image's path."""
diff --git a/invokeai/app/services/images/images_default.py b/invokeai/app/services/images/images_default.py
index d4339f567b..6c5a344518 100644
--- a/invokeai/app/services/images/images_default.py
+++ b/invokeai/app/services/images/images_default.py
@@ -76,6 +76,7 @@ class ImageService(ImageServiceABC):
graph: Optional[str] = None,
user_id: Optional[str] = None,
project_id: Optional[str] = None,
+ resolved_inputs: Optional[str] = None,
) -> ImageDTO:
if image_origin not in ResourceOrigin:
raise InvalidOriginException
@@ -133,6 +134,7 @@ class ImageService(ImageServiceABC):
metadata=metadata,
workflow=workflow,
graph=graph,
+ resolved_inputs=resolved_inputs,
image_subfolder=image_subfolder,
)
self._record_file_size(image_name, image_subfolder)
@@ -424,6 +426,22 @@ class ImageService(ImageServiceABC):
self.__invoker.services.logger.error("Problem getting image graph")
raise
+ def get_resolved_inputs(self, image_name: str) -> Optional[str]:
+ try:
+ record = self.__invoker.services.image_records.get(image_name)
+ return self.__invoker.services.image_files.get_resolved_inputs(
+ image_name, image_subfolder=record.image_subfolder
+ )
+ except ImageRecordNotFoundException:
+ self.__invoker.services.logger.debug(f"Image record not found: {image_name}")
+ raise
+ except ImageFileNotFoundException:
+ self.__invoker.services.logger.error("Image file not found")
+ raise
+ except Exception:
+ self.__invoker.services.logger.error("Problem getting image resolved inputs")
+ raise
+
def get_path(self, image_name: str, thumbnail: bool = False) -> str:
try:
record = self.__invoker.services.image_records.get(image_name)
diff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.md
index 49d19429b7..ec7518fe6b 100644
--- a/invokeai/app/services/shared/README.md
+++ b/invokeai/app/services/shared/README.md
@@ -898,6 +898,35 @@ the invocation cache is empty.
In normal execution, all runtime expansion occurs in `execution_graph` with traceability back to source nodes.
+### Image input records
+
+`ImagesInterface.save()` preserves the complete session source graph in `invokeai_graph`, including all original
+nodes, input literals and edges. The editor uses it to restore the authoring structure when `invokeai_workflow` is
+absent. The workflow JSON, when present, is saved unchanged and takes precedence in the editor.
+
+A separate `invokeai_resolved_inputs` PNG text field contains a compact Graph JSON input record. It contains the
+active invocation with its runtime ID and resolved inputs, plus ordinary upstream invocations and the edges connecting
+them. This preserves inputs such as a Noise invocation's actual seed and intermediate math values. Traversal uses the
+execution graph's indexed input edges and stops before `Iterate`, `Collect`, `If`, `For`, `ForReturn`, saved-workflow
+calls, collection-valued output edges, and edges whose resolved destination input is a list. Inputs received across
+those boundaries are already resolved on the retained downstream invocation. Future nodes, unrelated branches, sibling
+iterations, and upstream collections beyond those boundaries are excluded. Before runtime materialization, only the
+active invocation's inputs are recorded.
+
+The resolved-input record describes the image's invocation; it is not used for editor restoration. Optional internal
+`resolved_inputs` parameters carry it through `ImageService.create()` and `DiskImageFileStorage.save()`. The existing
+`GET /api/v1/images/i/{image_name}/workflow` response exposes this PNG record as optional `resolved_inputs` stringified
+Graph JSON, with `null` for older images. `ImageService.get_resolved_inputs()` reads the file from the record's
+subfolder, behind the route's existing read-access and storage-maintenance guards. Inspection can prefer this record,
+while the response's unchanged `workflow` and source `graph` remain the editor restoration inputs. It is not merged
+into user-owned `invokeai_metadata`. Legacy calls omit the field, and old PNGs remain readable without rewriting.
+Video responses use the shared response model's `null` default. Image file copies preserve all chunks.
+
+No expanded runtime graph is serialized for either field. Each image stores one source graph plus one compact input
+record. Nested-loop tests count their combined UTF-8 bytes. A source with a literal collection includes that collection
+in every image, so its authoring payload grows with the collection size. Resolved collection inputs retained on the
+active invocation can also grow; the compact record is not universally a single node or constant-size.
+
## 6) Invariants
- Source **Graph** remains a DAG and type-consistent.
diff --git a/invokeai/app/services/shared/graph_validation.py b/invokeai/app/services/shared/graph_validation.py
index 4e3a3e956e..61116a6b42 100644
--- a/invokeai/app/services/shared/graph_validation.py
+++ b/invokeai/app/services/shared/graph_validation.py
@@ -1254,6 +1254,37 @@ class Graph(BaseModel):
self.edges[:] = original_edges
raise
+ def _get_invocation_input_graph(self, invocation: BaseInvocation) -> "Graph":
+ """Record resolved invocation inputs and ordinary ancestors, stopping at batch/control boundaries."""
+ nodes = {invocation.id: invocation}
+ edges: list[Edge] = []
+ pending = [invocation.id]
+ boundaries = (
+ IterateInvocation,
+ CollectInvocation,
+ IfInvocation,
+ ForInvocation,
+ ForReturnInvocation,
+ CallSavedWorkflowInvocation,
+ )
+ while pending:
+ node_id = pending.pop()
+ if isinstance(nodes[node_id], boundaries):
+ continue
+ for edge in self._get_input_edges(node_id):
+ ancestor = self.nodes[edge.source.node_id]
+ if (
+ isinstance(ancestor, boundaries)
+ or isinstance(getattr(nodes[node_id], edge.destination.field), list)
+ or is_list_or_contains_list(get_output_field_type(ancestor, edge.source.field))
+ ):
+ continue
+ edges.append(edge)
+ if ancestor.id not in nodes:
+ nodes[ancestor.id] = ancestor
+ pending.append(ancestor.id)
+ return Graph(id=self.id, nodes=nodes, edges=edges)
+
def _get_input_edges(
self, node_id: str, field: Optional[str] = None, *, include_loop_linkage: bool = False
) -> list[Edge]:
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index d4ce960227..a421a4420c 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -328,8 +328,14 @@ class ImagesInterface(InvocationContextInterface):
workflow_ = self._get_workflow_json()
graph_ = None
+ resolved_inputs = None
if self._data.queue_item.session.graph:
+ # The editor's graph-only fallback needs the complete authoring graph.
graph_ = self._data.queue_item.session.graph.model_dump_json()
+ # Record resolved inputs for this image, without expanding metadata with sibling iterations.
+ resolved_inputs = self._data.queue_item.session.execution_graph._get_invocation_input_graph(
+ self._data.invocation
+ ).model_dump_json()
return self._services.images.create(
image=image,
@@ -340,6 +346,7 @@ class ImagesInterface(InvocationContextInterface):
image_origin=ResourceOrigin.INTERNAL,
workflow=workflow_,
graph=graph_,
+ resolved_inputs=resolved_inputs,
session_id=self._data.queue_item.session_id,
node_id=self._data.invocation.id,
user_id=self._data.queue_item.user_id,
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 703be1500c..eea3e1f726 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -120817,6 +120817,18 @@
],
"title": "Graph",
"description": "The graph used to generate the image, as stringified JSON"
+ },
+ "resolved_inputs": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Resolved Inputs",
+ "description": "The image's per-invocation resolved inputs, as stringified Graph JSON, when available"
}
},
"type": "object",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index c62b9fd220..741f6b0e96 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -54494,6 +54494,11 @@ export type components = {
* @description The graph used to generate the image, as stringified JSON
*/
graph: string | null;
+ /**
+ * Resolved Inputs
+ * @description The image's per-invocation resolved inputs, as stringified Graph JSON, when available
+ */
+ resolved_inputs?: string | null;
};
/** WorkflowCallCompatibility */
WorkflowCallCompatibility: {
diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
index 171a3d8ab7..2a639f91d1 100644
--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts
@@ -482,6 +482,8 @@ export const getGalleryVideoMetadata = async (
/** The workflow and graph a piece of media embeds, each as stringified JSON, when it has them. */
export interface GalleryMediaWorkflow {
graph: string | null;
+ /** Image inputs resolved for this output; the full source graph remains available for workflow loading. */
+ resolved_inputs?: string | null;
workflow: string | null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index 814b8424de..896d526466 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -53,8 +53,11 @@ const mocks = vi.hoisted(() => ({
imageResolveMany: vi.fn((..._args: unknown[]) => Promise.resolve([])),
importGalleryImagesToCanvas: vi.fn(),
isActiveProject: vi.fn(),
- imageWorkflow: vi.fn((..._args: unknown[]): Promise<{ graph: string | null; workflow: string | null }> =>
- Promise.resolve({ graph: null, workflow: null })
+ imageWorkflow: vi.fn(
+ (
+ ..._args: unknown[]
+ ): Promise<{ graph: string | null; resolved_inputs?: string | null; workflow: string | null }> =>
+ Promise.resolve({ graph: null, workflow: null })
),
requestWorkflowDocumentLoad: vi.fn(),
submitUtilityGraph: vi.fn((..._args: unknown[]): Promise<unknown> => Promise.reject(new Error('not submitted'))),
@@ -353,6 +356,33 @@ beforeEach(() => {
IntegerOutput: {
properties: { type: { default: 'integer_output' }, value: { type: 'integer', field_kind: 'output' } },
},
+ IterateInvocation: {
+ class: 'invocation',
+ properties: {
+ type: { default: 'iterate' },
+ collection: { type: 'array', items: { type: 'integer' }, input: 'any', field_kind: 'input' },
+ },
+ output: { $ref: '#/components/schemas/IterateOutput' },
+ version: '1.0.0',
+ },
+ IterateOutput: {
+ properties: { type: { default: 'iterate_output' }, item: { type: 'integer', field_kind: 'output' } },
+ },
+ CollectInvocation: {
+ class: 'invocation',
+ properties: {
+ type: { default: 'collect' },
+ item: { type: 'integer', input: 'connection', field_kind: 'input' },
+ },
+ output: { $ref: '#/components/schemas/CollectOutput' },
+ version: '1.0.0',
+ },
+ CollectOutput: {
+ properties: {
+ type: { default: 'collect_output' },
+ collection: { type: 'array', items: { type: 'integer' }, field_kind: 'output' },
+ },
+ },
},
},
}),
@@ -680,6 +710,7 @@ describe('load workflow from image', () => {
it('hands the embedded workflow to the editor and opens it', async () => {
mocks.imageWorkflow.mockResolvedValueOnce({
graph: 'invalid graph ignored when an authored workflow exists',
+ resolved_inputs: '{"nodes":{"seed":{"id":"seed","type":"integer","value":18}},"edges":[]}',
workflow: JSON.stringify({ name: 'Embedded', nodes: [] }),
});
@@ -698,12 +729,23 @@ describe('load workflow from image', () => {
expect(mocks.getInvocationTemplatesSnapshot).not.toHaveBeenCalled();
});
- it('loads the stored generation graph when the image has no authored workflow', async () => {
+ it('loads the full source generation graph even when resolved inputs are available', async () => {
mocks.getInvocationTemplatesSnapshot.mockReturnValueOnce({ error: null, status: 'idle', templates: {} });
mocks.imageWorkflow.mockResolvedValueOnce({
graph: JSON.stringify({
id: 'generated',
- nodes: { seed: { id: 'seed', type: 'integer', value: 42 } },
+ nodes: {
+ seed: { id: 'seed', type: 'integer', value: 42 },
+ iterator: { id: 'iterator', type: 'iterate', collection: [17, 18] },
+ collector: { id: 'collector', type: 'collect' },
+ },
+ edges: [
+ { source: { node_id: 'iterator', field: 'item' }, destination: { node_id: 'collector', field: 'item' } },
+ ],
+ }),
+ resolved_inputs: JSON.stringify({
+ id: 'resolved',
+ nodes: { seed: { id: 'seed', type: 'integer', value: 18 } },
edges: [],
}),
workflow: null,
@@ -724,6 +766,22 @@ describe('load workflow from image', () => {
inputs: { value: expect.objectContaining({ value: 42 }) },
}),
}),
+ expect.objectContaining({
+ id: 'iterator',
+ data: expect.objectContaining({
+ type: 'iterate',
+ inputs: { collection: expect.objectContaining({ value: [17, 18] }) },
+ }),
+ }),
+ expect.objectContaining({ id: 'collector', data: expect.objectContaining({ type: 'collect' }) }),
+ ],
+ edges: [
+ expect.objectContaining({
+ source: 'iterator',
+ sourceHandle: 'item',
+ target: 'collector',
+ targetHandle: 'item',
+ }),
],
}),
expect.any(String)
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
index e608a4db5a..af8e11409f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetails.browser.test.tsx
@@ -1,6 +1,7 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import type { GalleryImage, GalleryImageItem, GalleryVideoItem } from '@features/gallery';
import type * as GalleryModule from '@features/gallery';
+import type * as GalleryQueriesModule from '@features/gallery/queries';
import type * as IdentityModule from '@features/identity';
import type { ImageActions, ImageRecallCapabilities } from '@workbench/image-actions';
@@ -55,6 +56,13 @@ vi.mock('@features/identity', async (importOriginal) => {
}),
};
});
+vi.mock('@features/gallery/queries', async (importOriginal) => ({
+ ...(await importOriginal<typeof GalleryQueriesModule>()),
+ imageIndexAvailabilityOptions: () => ({
+ queryFn: () => ({ state: 'disabled' }),
+ queryKey: ['test-image-index-availability'],
+ }),
+}));
const imageItem: GalleryImageItem = {
boardId: 'none',
@@ -220,6 +228,67 @@ afterEach(async () => {
});
describe('Preview query-driven Details', () => {
+ const sourceGraph = {
+ id: 'source',
+ nodes: {
+ iterator: { id: 'iterator', type: 'iterate', collection: [17, 18] },
+ math: { id: 'math', type: 'add', a: 0, b: 1 },
+ noise: { id: 'noise', type: 'noise', seed: 0 },
+ collector: { id: 'collector', type: 'collect' },
+ },
+ edges: [
+ { source: { node_id: 'iterator', field: 'item' }, destination: { node_id: 'math', field: 'a' } },
+ { source: { node_id: 'math', field: 'value' }, destination: { node_id: 'noise', field: 'seed' } },
+ { source: { node_id: 'noise', field: 'noise' }, destination: { node_id: 'collector', field: 'item' } },
+ ],
+ };
+
+ it("shows this image's resolved Noise and math inputs in the Graph tab", async () => {
+ galleryMocks.imageWorkflow.mockResolvedValueOnce({
+ graph: JSON.stringify(sourceGraph),
+ resolved_inputs: JSON.stringify({
+ id: 'resolved',
+ nodes: {
+ math: { id: 'math', type: 'add', a: 17, b: 1 },
+ noise: { id: 'noise', type: 'noise', seed: 18 },
+ },
+ edges: [],
+ }),
+ workflow: null,
+ });
+
+ await renderDetails({ isOpen: true, item: imageItem });
+ await act(async () => {
+ await vi.waitFor(() => expect(getButton('Graph').disabled).toBe(false));
+ });
+ await interact(() => getButton('Graph').click());
+
+ const graphRegion = document.querySelector('[role="region"][aria-label="Video graph JSON"]');
+ expect(graphRegion).not.toBeNull();
+ expect(JSON.parse(graphRegion!.textContent!)).toEqual({
+ id: 'resolved',
+ nodes: {
+ math: { id: 'math', type: 'add', a: 17, b: 1 },
+ noise: { id: 'noise', type: 'noise', seed: 18 },
+ },
+ edges: [],
+ });
+ });
+
+ it.each([{}, { resolved_inputs: null }])('shows the source graph for legacy image payloads: %j', async (legacy) => {
+ galleryMocks.imageWorkflow.mockResolvedValueOnce({ graph: JSON.stringify(sourceGraph), workflow: null, ...legacy });
+
+ await renderDetails({ isOpen: true, item: imageItem });
+ await act(async () => {
+ await vi.waitFor(() => expect(getButton('Graph').disabled).toBe(false));
+ });
+ await interact(() => getButton('Graph').click());
+
+ const graphRegion = document.querySelector('[role="region"][aria-label="Video graph JSON"]');
+ expect(graphRegion).not.toBeNull();
+ expect(JSON.parse(graphRegion!.textContent!)).toEqual(sourceGraph);
+ });
+
it('shows the video Details disclosure but starts no request while it is closed', async () => {
await renderDetails({ isOpen: false, item: videoItem });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
index d8cd8e19d3..11855ad980 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
@@ -119,7 +119,12 @@ const PreviewDetailsQuery = ({
galleryImages.workflow(item.name, signal),
]);
- return { graph: workflow.graph, kind: 'image', metadata, workflow: workflow.workflow };
+ return {
+ graph: workflow.resolved_inputs ?? workflow.graph,
+ kind: 'image',
+ metadata,
+ workflow: workflow.workflow,
+ };
}
const [metadata, workflow] = await Promise.all([
diff --git a/tests/app/routers/test_image_resolved_inputs.py b/tests/app/routers/test_image_resolved_inputs.py
new file mode 100644
index 0000000000..069fca48cc
--- /dev/null
+++ b/tests/app/routers/test_image_resolved_inputs.py
@@ -0,0 +1,391 @@
+"""Persisted PNG input records reach image inspection without changing editor restoration."""
+
+import io
+import json
+import zlib
+from collections.abc import Iterator
+from pathlib import Path
+
+import pytest
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from invokeai.app.api.routers.images import WorkflowAndGraphResponse
+from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.noise import NoiseInvocation
+from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.image_moves.image_moves_default import ImageMoveService
+from invokeai.app.services.image_records.image_records_common import (
+ ImageCategory,
+ ImageRecordNotFoundException,
+ ResourceOrigin,
+)
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.names.names_default import SimpleNameService
+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph
+from invokeai.app.services.urls.urls_default import LocalUrlService
+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowWithoutIDValidator
+from tests.app.routers.conftest import MockApiDependencies, _auth
+
+
+def persisted_inputs(
+ enable_multiuser: None, mock_invoker: Invoker, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> Iterator[DiskImageFileStorage]:
+ services = mock_invoker.services
+ storage = DiskImageFileStorage(tmp_path / "images")
+ services.image_files = storage
+ storage.start(mock_invoker)
+ services.images.start(mock_invoker)
+ moves = ImageMoveService(services.database, storage, services.configuration, services.logger)
+ services.image_moves = moves
+ monkeypatch.setattr(
+ "invokeai.app.api.routers.image_move_maintenance.ApiDependencies", MockApiDependencies(mock_invoker)
+ )
+ try:
+ yield storage
+ finally:
+ moves.stop()
+
+
+def _graph_strings(resolved: bool) -> tuple[str, str | None]:
+ graph = Graph(
+ nodes={"math": AddInvocation(id="math", a=0, b=1), "noise": NoiseInvocation(id="noise", seed=0)},
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id="math", field="value"),
+ destination=EdgeConnection(node_id="noise", field="seed"),
+ )
+ ],
+ )
+ source_json = graph.model_dump_json()
+ runtime = graph.model_copy(deep=True)
+ runtime.nodes["math"].a = 17
+ runtime.nodes["noise"].seed = 18
+ resolved_json = runtime.model_dump_json() if resolved else None
+ return source_json, resolved_json
+
+
+def _save_png(
+ invoker: Invoker, storage: DiskImageFileStorage, *, workflow: str | None, resolved: bool
+) -> tuple[str, str | None]:
+ source_json, resolved_json = _graph_strings(resolved)
+ services = invoker.services
+ user_id = services.users.get_by_email("[email protected]").user_id
+ services.image_records.save(
+ image_name="image.png",
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ width=2,
+ height=2,
+ has_workflow=True,
+ user_id=user_id,
+ image_subfolder="nested/record-path",
+ )
+ with Image.new("RGB", (2, 2), (12, 34, 56)) as image:
+ storage.save(
+ image,
+ "image.png",
+ workflow=workflow,
+ graph=source_json,
+ resolved_inputs=resolved_json,
+ image_subfolder="nested/record-path",
+ )
+ # A fresh reader must recover from disk, using the record's non-flat location.
+ services.image_files = DiskImageFileStorage(storage.image_root)
+ return source_json, resolved_json
+
+
[email protected]("crop,resize", [(False, False), (True, False), (False, True), (True, True)])
[email protected]("override_metadata", [False, True], ids=["embedded-metadata", "form-metadata"])
[email protected]("diagnostic", ["resolved", "legacy", "malformed", "wrong-envelope"])
+def test_uploaded_png_preserves_generation_records(
+ client: TestClient,
+ mock_invoker: Invoker,
+ user1_token: str,
+ persisted_inputs: DiskImageFileStorage,
+ crop: bool,
+ resize: bool,
+ override_metadata: bool,
+ diagnostic: str,
+) -> None:
+ services = mock_invoker.services
+ services.names = SimpleNameService()
+ services.urls = LocalUrlService()
+ source_json, resolved_json = _graph_strings(True)
+ workflow_json = (
+ json.dumps(
+ {
+ "name": "Original authoring workflow",
+ "author": "",
+ "description": "",
+ "version": "1.0.0",
+ "contact": "",
+ "tags": "",
+ "notes": "Preserve whitespace as well as content",
+ "exposedFields": [],
+ "meta": {"version": "3.0.0", "category": "user"},
+ "nodes": [],
+ "edges": [],
+ "form": {"elements": {}, "rootElementId": "root"},
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ WorkflowWithoutIDValidator.validate_json(workflow_json)
+ embedded_metadata = {"seed": 18, "resolved_inputs": "user-owned", "invokeai_resolved_inputs": {"note": "keep"}}
+ form_metadata = {"seed": 99, "resolved_inputs": {"custom": True}, "invokeai_resolved_inputs": "also user-owned"}
+ incoming_inputs = {
+ "resolved": resolved_json,
+ "legacy": None,
+ "malformed": "not JSON",
+ "wrong-envelope": '{"nodes": [], "edges": []}',
+ }[diagnostic]
+ # Produce the input PNG through the real image service and writer, then upload its actual bytes.
+ user_id = services.users.get_by_email("[email protected]").user_id
+ with Image.new("RGBA", (4, 4)) as image:
+ image.paste((12, 34, 56, 255), (1, 1, 3, 3))
+ original = services.images.create(
+ image=image,
+ image_origin=ResourceOrigin.INTERNAL,
+ image_category=ImageCategory.GENERAL,
+ user_id=user_id,
+ metadata=json.dumps(embedded_metadata),
+ workflow=workflow_json,
+ graph=source_json,
+ resolved_inputs=incoming_inputs,
+ )
+ original_record = services.image_records.get(original.image_name)
+ original_path = persisted_inputs.get_path(original.image_name, image_subfolder=original_record.image_subfolder)
+ original_png = original_path.read_bytes()
+ form = {"metadata": json.dumps(form_metadata)} if override_metadata else {}
+ if resize:
+ form["resize_to"] = '{"width": 8, "height": 6}'
+ uploaded = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "general", "is_intermediate": "false", "crop_visible": str(crop).lower()},
+ headers=_auth(user1_token),
+ files={"file": (original.image_name, original_png, "image/png")},
+ data=form,
+ )
+ assert uploaded.status_code == 201, uploaded.text
+ image_name = uploaded.json()["image_name"]
+ assert image_name != original.image_name
+ record = services.image_records.get(image_name)
+ assert services.image_records.get_user_id(image_name) == user_id
+ assert record.has_workflow
+ expected_metadata = form_metadata if override_metadata else embedded_metadata
+ expected_inputs = resolved_json if diagnostic == "resolved" else None
+ # A new storage instance cannot serve the writer's populated Image.info cache.
+ reader = DiskImageFileStorage(persisted_inputs.image_root)
+ services.image_files = reader
+ with reader.get(image_name, image_subfolder=record.image_subfolder) as reopened:
+ assert reopened.format == "PNG"
+ assert reopened.size == ((8, 6) if resize else (2, 2) if crop else (4, 4))
+ assert json.loads(reopened.info["invokeai_metadata"]) == expected_metadata
+ assert reopened.info["invokeai_graph"] == source_json
+ assert reopened.info["invokeai_workflow"] == workflow_json
+ disk_inputs = reopened.info.get("invokeai_resolved_inputs")
+ response = client.get(f"/api/v1/images/i/{image_name}/workflow", headers=_auth(user1_token))
+ assert response.status_code == 200, response.text
+ assert response.json() == {"workflow": workflow_json, "graph": source_json, "resolved_inputs": expected_inputs}
+ assert disk_inputs == expected_inputs
+ if expected_inputs is not None:
+ inputs = json.loads(disk_inputs)
+ assert inputs["nodes"]["noise"]["seed"] == 18
+ assert inputs["nodes"]["math"]["a"] == 17
+ assert original_path.read_bytes() == original_png
+
+
+def _png_chunks(png: bytes) -> list[bytes]:
+ assert png[:8] == b"\x89PNG\r\n\x1a\n"
+ chunks = []
+ offset = 8
+ while offset < len(png):
+ end = offset + 12 + int.from_bytes(png[offset : offset + 4], "big")
+ chunks.append(png[offset:end])
+ offset = end
+ assert offset == len(png)
+ assert chunks[-1][4:8] == b"IEND"
+ return chunks
+
+
[email protected]("crop", [False, True], ids=["plain", "crop"])
+def test_upload_preserves_post_idat_png_records(
+ client: TestClient,
+ mock_invoker: Invoker,
+ user1_token: str,
+ persisted_inputs: DiskImageFileStorage,
+ crop: bool,
+) -> None:
+ services = mock_invoker.services
+ services.names = SimpleNameService()
+ services.urls = LocalUrlService()
+ source, resolved = _graph_strings(True)
+ workflow = (
+ '{ "name": "Trailing text workflow", "author": "", "description": "", "version": "1.0.0", '
+ '"contact": "", "tags": "", "notes": "", "exposedFields": [], '
+ '"meta": {"version": "3.0.0", "category": "user"}, "nodes": [], "edges": [] }\n'
+ )
+ WorkflowWithoutIDValidator.validate_json(workflow)
+ metadata = '{ "seed": 18, "resolved_inputs": "user-owned" }'
+ records = {
+ "invokeai_metadata": metadata,
+ "invokeai_workflow": workflow,
+ "invokeai_graph": source,
+ "invokeai_resolved_inputs": resolved,
+ }
+ with Image.new("RGBA", (4, 4)) as image:
+ image.paste((12, 34, 56, 255), (1, 1, 3, 3))
+ persisted_inputs.save(
+ image, "post-idat.png", metadata=metadata, workflow=workflow, graph=source, resolved_inputs=resolved
+ )
+ original_path = persisted_inputs.get_path("post-idat.png")
+ chunks = _png_chunks(original_path.read_bytes())
+ text_chunks = [chunk for chunk in chunks if chunk[4:8] == b"tEXt"]
+ assert len(text_chunks) == 4
+ # Move whole tEXt chunks, retaining their payloads, lengths and CRCs after all IDATs and before IEND.
+ body = [chunk for chunk in chunks[:-1] if chunk[4:8] != b"tEXt"]
+ assert body[-1][4:8] == b"IDAT"
+ original_png = b"\x89PNG\r\n\x1a\n" + b"".join(body + text_chunks + chunks[-1:])
+ original_path.write_bytes(original_png)
+ with Image.open(io.BytesIO(original_png)) as image:
+ assert not records.keys() & image.info.keys()
+ image.verify()
+ with Image.open(io.BytesIO(original_png)) as image:
+ image.load()
+ assert image.info == records
+ assert image.getpixel((1, 1)) == (12, 34, 56, 255)
+ uploaded = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "general", "is_intermediate": "false", "crop_visible": str(crop).lower()},
+ headers=_auth(user1_token),
+ files={"file": (original_path.name, original_png, "image/png")},
+ )
+ assert uploaded.status_code == 201, uploaded.text
+ name = uploaded.json()["image_name"]
+ assert name != original_path.name
+ record = services.image_records.get(name)
+ reader = DiskImageFileStorage(persisted_inputs.image_root)
+ services.image_files = reader
+ with reader.get(name, image_subfolder=record.image_subfolder) as image:
+ assert image.size == ((2, 2) if crop else (4, 4))
+ assert image.getpixel((0, 0) if crop else (1, 1)) == (12, 34, 56, 255)
+ disk_records = dict(image.info)
+ response = client.get(f"/api/v1/images/i/{name}/workflow", headers=_auth(user1_token))
+ assert response.status_code == 200, response.text
+ assert response.json() == {"workflow": workflow, "graph": source, "resolved_inputs": resolved}
+ assert disk_records == records
+ assert json.loads(disk_records["invokeai_resolved_inputs"])["nodes"]["noise"]["seed"] == 18
+ assert original_path.read_bytes() == original_png
+
+
+def test_upload_rejects_undecodable_idat_as_failed_image_read(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, persisted_inputs: DiskImageFileStorage
+) -> None:
+ mock_invoker.services.names = SimpleNameService()
+ mock_invoker.services.urls = LocalUrlService()
+ png = io.BytesIO()
+ with Image.new("RGB", (2, 2), (12, 34, 56)) as image:
+ image.save(png, "PNG")
+ chunks = _png_chunks(png.getvalue())
+ for index, chunk in enumerate(chunks):
+ if chunk[4:8] == b"IDAT":
+ payload = b"\x00" * (len(chunk) - 12)
+ data = b"IDAT" + payload
+ chunks[index] = len(payload).to_bytes(4, "big") + data + zlib.crc32(data).to_bytes(4, "big")
+ broken = b"\x89PNG\r\n\x1a\n" + b"".join(chunks)
+ # Valid container/CRCs and header, but invalid compressed pixels: Image.open alone cannot catch this.
+ with Image.open(io.BytesIO(broken)) as image:
+ image.verify()
+ with Image.open(io.BytesIO(broken)) as image, pytest.raises(OSError):
+ image.load()
+ response = client.post(
+ "/api/v1/images/upload",
+ params={"image_category": "general", "is_intermediate": "false"},
+ headers=_auth(user1_token),
+ files={"file": ("broken.png", broken, "image/png")},
+ )
+ assert response.status_code == 415, response.text
+ assert response.json() == {"detail": "Failed to read image"}
+ assert list(persisted_inputs.image_root.rglob("*.png")) == []
+
+
[email protected]("workflow", [None, '{ "name": "original workflow", "nodes": [], "edges": [] }'])
[email protected]("resolved", [True, False], ids=["resolved", "legacy"])
+def test_workflow_http_preserves_source_and_exposes_persisted_inputs(
+ client: TestClient,
+ mock_invoker: Invoker,
+ user1_token: str,
+ persisted_inputs: DiskImageFileStorage,
+ workflow: str | None,
+ resolved: bool,
+) -> None:
+ source_json, resolved_json = _save_png(mock_invoker, persisted_inputs, workflow=workflow, resolved=resolved)
+ path = persisted_inputs.get_path("image.png", image_subfolder="nested/record-path")
+ before = path.read_bytes()
+ response = client.get("/api/v1/images/i/image.png/workflow", headers=_auth(user1_token))
+ assert response.status_code == 200, response.text
+ assert response.json() == {"workflow": workflow, "graph": source_json, "resolved_inputs": resolved_json}
+ source = Graph.model_validate_json(response.json()["graph"])
+ assert source.nodes["noise"].seed == 0
+ assert source.nodes["math"].a == 0
+ assert len(source.edges) == 1
+ if resolved:
+ inputs = Graph.model_validate_json(response.json()["resolved_inputs"])
+ assert inputs.nodes["noise"].seed == 18
+ assert inputs.nodes["math"].a == 17
+ else:
+ # Responses predating the optional channel (including video callers) still deserialize.
+ old_response = WorkflowAndGraphResponse.model_validate({"workflow": workflow, "graph": source_json})
+ assert old_response.model_dump() == response.json()
+ assert path.read_bytes() == before
+
+
[email protected]("resolved", [True, False], ids=["resolved", "legacy"])
+def test_image_service_reads_inputs_from_record_subfolder(
+ mock_invoker: Invoker, user1_token: str, persisted_inputs: DiskImageFileStorage, resolved: bool
+) -> None:
+ source_json, resolved_json = _save_png(mock_invoker, persisted_inputs, workflow=None, resolved=resolved)
+ images = mock_invoker.services.images
+ assert images.get_resolved_inputs("image.png") == resolved_json
+ assert images.get_graph("image.png") == source_json
+ assert images.get_workflow("image.png") is None
+
+
+def test_input_inspection_preserves_read_access_and_maintenance_guards(
+ client: TestClient,
+ mock_invoker: Invoker,
+ user1_token: str,
+ user2_token: str,
+ persisted_inputs: DiskImageFileStorage,
+) -> None:
+ _save_png(mock_invoker, persisted_inputs, workflow=None, resolved=True)
+ endpoint = "/api/v1/images/i/image.png/workflow"
+ assert client.get(endpoint).status_code == 401
+ assert client.get(endpoint, headers=_auth(user2_token)).status_code == 403
+ with mock_invoker.services.image_moves.reserve_gallery_maintenance():
+ # Read denial must still precede the maintenance check.
+ assert client.get(endpoint, headers=_auth(user2_token)).status_code == 403
+ response = client.get(endpoint, headers=_auth(user1_token))
+ assert response.status_code == 409
+ assert response.json()["detail"] == "Image storage maintenance is active"
+ response = client.get(endpoint, headers=_auth(user1_token))
+ assert response.status_code == 200
+ assert Graph.model_validate_json(response.json()["resolved_inputs"]).nodes["noise"].seed == 18
+
+
+def test_missing_record_or_file_keeps_service_errors_and_http_404(
+ client: TestClient, mock_invoker: Invoker, user1_token: str, persisted_inputs: DiskImageFileStorage
+) -> None:
+ images = mock_invoker.services.images
+ with pytest.raises(ImageRecordNotFoundException):
+ images.get_resolved_inputs("missing.png")
+ assert client.get("/api/v1/images/i/missing.png/workflow", headers=_auth(user1_token)).status_code == 404
+ _save_png(mock_invoker, persisted_inputs, workflow=None, resolved=True)
+ persisted_inputs.get_path("image.png", image_subfolder="nested/record-path").unlink()
+ with pytest.raises(ImageFileNotFoundException):
+ images.get_resolved_inputs("image.png")
+ assert client.get("/api/v1/images/i/image.png/workflow", headers=_auth(user1_token)).status_code == 404
diff --git a/tests/app/routers/test_videos_multiuser.py b/tests/app/routers/test_videos_multiuser.py
index 80bad22a76..f0941b8cf0 100644
--- a/tests/app/routers/test_videos_multiuser.py
+++ b/tests/app/routers/test_videos_multiuser.py
@@ -1141,7 +1141,7 @@ def test_get_video_workflow_returns_workflow_and_graph_for_owner(
)
assert response.status_code == status.HTTP_200_OK
- assert response.json() == {"workflow": '{"nodes": []}', "graph": '{"edges": []}'}
+ assert response.json() == {"workflow": '{"nodes": []}', "graph": '{"edges": []}', "resolved_inputs": None}
def test_get_video_workflow_returns_nulls_when_video_has_none(
@@ -1159,7 +1159,7 @@ def test_get_video_workflow_returns_nulls_when_video_has_none(
)
assert response.status_code == status.HTTP_200_OK
- assert response.json() == {"workflow": None, "graph": None}
+ assert response.json() == {"workflow": None, "graph": None, "resolved_inputs": None}
def test_get_video_workflow_missing_video_returns_404(client: TestClient, mock_invoker: Invoker, user1_token: str):
diff --git a/tests/app/services/images/test_images_default.py b/tests/app/services/images/test_images_default.py
index 1a4424d9fd..872c1debac 100644
--- a/tests/app/services/images/test_images_default.py
+++ b/tests/app/services/images/test_images_default.py
@@ -10,11 +10,18 @@ import os
import stat
import threading
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from PIL import Image
+from invokeai.app.api.extract_metadata import extract_metadata_from_image
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.collections import CollectionConcatInvocation
+from invokeai.app.invocations.fields import MetadataField
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.math import AddInvocation
from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.services.image_files.image_files_common import (
ImageFileDeleteException,
@@ -33,9 +40,19 @@ from invokeai.app.services.image_records.image_records_default import ImageRecor
from invokeai.app.services.images.images_default import ImageService
from invokeai.app.services.shared.database.errors import LockTimeoutError
from invokeai.app.services.shared.database.startup import init_database
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ Edge,
+ EdgeConnection,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+)
+from invokeai.app.services.shared.invocation_context import ImagesInterface
from invokeai.app.util.misc import get_iso_timestamp
from invokeai.backend.util.logging import InvokeAILogger
from tests.fixtures.sqlite_database import create_mock_sqlite_database
+from tests.test_nodes import AnyTypeTestInvocation
@pytest.fixture
@@ -102,6 +119,147 @@ def real_image_service(tmp_path: Path) -> tuple[ImageService, ImageRecordStorage
return service, records, storage
+ ("boundary", "output", "expected_values"),
+ [
+ pytest.param(IterateInvocation(id="boundary", collection=[17, 18]), "item", [17, 18], id="iterate"),
+ pytest.param(
+ IfInvocation(id="boundary", condition=True, true_input=17, false_input=90), "value", [17], id="if-true"
+ ),
+ pytest.param(
+ IfInvocation(id="boundary", condition=False, true_input=17, false_input=90), "value", [90], id="if-false"
+ ),
+ pytest.param(CollectInvocation(id="boundary", collection=[17, 18]), "collection", [[17, 18]], id="collect"),
+ ],
+)
+def test_image_save_graph_only_restores_source_and_persists_separate_resolved_inputs(
+ real_image_service: tuple[ImageService, ImageRecordStorage, DiskImageFileStorage],
+ boundary: BaseInvocation,
+ output: str,
+ expected_values: list[object],
+) -> None:
+ graph = Graph(
+ nodes={
+ "boundary": boundary,
+ "active": AnyTypeTestInvocation(id="active"),
+ "future": AnyTypeTestInvocation(id="future"),
+ },
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id="boundary", field=output),
+ destination=EdgeConnection(node_id="active", field="value"),
+ ),
+ Edge(
+ source=EdgeConnection(node_id="active", field="value"),
+ destination=EdgeConnection(node_id="future", field="value"),
+ ),
+ ],
+ )
+ if isinstance(boundary, (IterateInvocation, CollectInvocation)):
+ graph.add_node(CollectionConcatInvocation(id="source", first=[17, 18]))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="source", field="collection"),
+ destination=EdgeConnection(node_id="boundary", field="collection"),
+ )
+ )
+ else:
+ graph.add_node(AddInvocation(id="true", a=16, b=1))
+ graph.add_node(AddInvocation(id="false", a=89, b=1))
+ for name in ("true", "false"):
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id=name, field="value"),
+ destination=EdgeConnection(node_id="boundary", field=f"{name}_input"),
+ )
+ )
+ source_json = graph.model_dump_json()
+ session = GraphExecutionState(graph=graph)
+ service, records, storage = real_image_service
+ services = service._ImageService__invoker.services
+ services.configuration.multiuser = False
+ services.images = service
+ data = SimpleNamespace(
+ queue_item=SimpleNamespace(
+ user_id=None,
+ project_id=None,
+ session_id=None,
+ session=session,
+ workflow=None,
+ root_item_id=None,
+ _workflow_json_loaded=False,
+ _workflow_json_snapshot=None,
+ ),
+ invocation=None,
+ )
+ images = ImagesInterface(services, data, MagicMock())
+ metadata = MetadataField.model_validate({"invokeai_resolved_inputs": {"user": "保留"}, "seed": 123})
+ metadata_json = metadata.model_dump_json()
+ saved: list[tuple[str, str, object]] = []
+ for _ in range(12):
+ node = session.next()
+ if node is None:
+ break
+ data.invocation = node
+ if session.prepared_source_mapping[node.id] == "active":
+ name = f"{len(saved)}.png"
+ services.names.create_image_name.return_value = name
+ execution_json = session.execution_graph.model_dump_json()
+ with Image.new("RGB", (2, 2), (12, 34, 56)) as image:
+ images.save(image, metadata=metadata)
+ assert session.execution_graph.model_dump_json() == execution_json
+ saved.append((name, node.id, node.value))
+ session.complete(node.id, node.invoke(MagicMock()))
+ else:
+ pytest.fail("Boundary graph did not finish")
+ assert session.is_complete()
+ assert [value for _, _, value in saved] == expected_values
+ assert graph.model_dump_json() == session.graph.model_dump_json() == source_json
+ assert metadata.model_dump_json() == metadata_json
+
+ reader = DiskImageFileStorage(storage.image_root)
+ for name, node_id, value in saved:
+ with reader.get(name) as reopened:
+ assert (reopened.format, reopened.size, reopened.getpixel((0, 0))) == ("PNG", (2, 2), (12, 34, 56))
+ extracted = extract_metadata_from_image(reopened, None, None, None, services.logger)
+ assert extracted.invokeai_workflow is None
+ # This is exactly the graph returned to executeLoadMediaWorkflow's graph-only fallback.
+ assert reader.get_graph(name) == extracted.invokeai_graph == source_json
+ restored = Graph.model_validate_json(extracted.invokeai_graph)
+ assert restored.model_dump() == graph.model_dump() # Includes boundary nodes and all original edges.
+ assert extracted.invokeai_metadata == metadata_json
+ assert records.get(name).has_workflow
+ assert records.get_metadata(name).model_dump_json() == metadata_json
+ resolved = Graph.model_validate_json(reopened.info["invokeai_resolved_inputs"])
+ assert set(resolved.nodes) == {node_id}
+ assert resolved.edges == []
+ assert resolved.nodes[node_id].value == value
+
+
+def test_create_without_resolved_inputs_preserves_legacy_png_channels(
+ real_image_service: tuple[ImageService, ImageRecordStorage, DiskImageFileStorage],
+) -> None:
+ service, records, storage = real_image_service
+ metadata = '{ "seed": 123, "invokeai_resolved_inputs": "user-owned" }'
+ graph = '{ "nodes": {}, "edges": [] }'
+ with Image.new("RGB", (2, 2)) as image:
+ dto = service.create(
+ image,
+ ResourceOrigin.EXTERNAL,
+ ImageCategory.GENERAL,
+ metadata=metadata,
+ graph=graph,
+ )
+ reader = DiskImageFileStorage(storage.image_root)
+ with reader.get(dto.image_name) as reopened:
+ assert "invokeai_resolved_inputs" not in reopened.info
+ assert reopened.info["invokeai_metadata"] == metadata
+ assert reopened.info["invokeai_graph"] == graph
+ assert "invokeai_workflow" not in reopened.info
+ assert records.get(dto.image_name).has_workflow
+ assert records.get_metadata(dto.image_name).root["invokeai_resolved_inputs"] == "user-owned"
+
+
def test_create_rolls_back_record_and_files_when_thumbnail_save_fails(
real_image_service: tuple[ImageService, ImageRecordStorage, DiskImageFileStorage],
) -> None:
diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
index e05fa607ab..0cf7476aa5 100644
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
@@ -10,6 +10,7 @@ import pytest
from PIL import Image
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.image import BlankImageInvocation
from invokeai.app.services.events.events_common import (
InvocationStartedEvent,
QueueItemsRetriedEvent,
@@ -391,7 +392,7 @@ def test_enqueue_workflow_call_child_inherits_workflow_for_image_metadata(
mock_invoker.services,
InvocationContextData(
queue_item=child_queue_item,
- invocation=MagicMock(is_intermediate=False, id=f"image-node-{index}"),
+ invocation=BlankImageInvocation(is_intermediate=False, id=f"image-node-{index}", width=4, height=4),
source_invocation_id=f"image-node-{index}",
),
MagicMock(),
diff --git a/tests/app/services/shared/test_invocation_context_images.py b/tests/app/services/shared/test_invocation_context_images.py
index 6a6a64c672..6bd0189eb4 100644
--- a/tests/app/services/shared/test_invocation_context_images.py
+++ b/tests/app/services/shared/test_invocation_context_images.py
@@ -1,14 +1,39 @@
+import json
+from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
-
+from PIL import Image
+
+from invokeai.app.api.extract_metadata import extract_metadata_from_image
+from invokeai.app.invocations.baseinvocation import BaseInvocation
+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.collections import CollectionConcatInvocation
+from invokeai.app.invocations.fields import LatentsField
+from invokeai.app.invocations.image import BlankImageInvocation
+from invokeai.app.invocations.logic import IfInvocation
+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation
+from invokeai.app.invocations.math import AddInvocation, RandomIntInvocation
+from invokeai.app.invocations.noise import NoiseInvocation, NoiseOutput
from invokeai.app.services.board_access.board_access_common import (
BoardAccessDeniedError,
BoardAction,
ItemAccessDeniedError,
ItemAction,
)
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.shared.graph import (
+ CollectInvocation,
+ Edge,
+ EdgeConnection,
+ Graph,
+ GraphExecutionState,
+ IterateInvocation,
+)
from invokeai.app.services.shared.invocation_context import ImagesInterface
+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowWithoutID
+from tests.test_nodes import AnyTypeTestInvocation
def _make_interface(allowed: bool) -> tuple[ImagesInterface, MagicMock]:
@@ -151,3 +176,484 @@ def test_images_save_attributes_the_output_to_the_queue_items_project() -> None:
images.save(MagicMock())
assert services.images.create.call_args.kwargs["project_id"] == "project-1"
+
+
+def test_image_save_graph_records_resolved_runtime_inputs() -> None:
+ graph = Graph()
+ graph.add_node(RandomIntInvocation(id="random", low=17, high=18))
+ graph.add_node(AddInvocation(id="add", b=1))
+ graph.add_node(AddInvocation(id="downstream", b=2))
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="random", field="value"),
+ destination=EdgeConnection(node_id="add", field="a"),
+ )
+ )
+ graph.add_edge(
+ Edge(
+ source=EdgeConnection(node_id="add", field="value"),
+ destination=EdgeConnection(node_id="downstream", field="a"),
+ )
+ )
+ source_graph_json = graph.model_dump_json()
+ session = GraphExecutionState(graph=graph)
+
+ random_node = session.next()
+ assert isinstance(random_node, RandomIntInvocation)
+ session.complete(random_node.id, random_node.invoke(MagicMock()))
+ runtime_add_node = session.next()
+ assert isinstance(runtime_add_node, AddInvocation)
+ assert runtime_add_node.a == 17
+
+ services = MagicMock()
+ services.configuration.multiuser = False
+ data = MagicMock()
+ data.queue_item.user_id = "queue-user"
+ data.queue_item.workflow = None
+ data.queue_item.root_item_id = None
+ data.queue_item._workflow_json_loaded = False
+ data.queue_item._workflow_json_snapshot = None
+ data.queue_item.session = session
+ data.queue_item.session_id = "session"
+ data.queue_item.project_id = "project-1"
+ data.invocation = runtime_add_node
+ images = ImagesInterface(services, data, MagicMock())
+ execution_graph_json = session.execution_graph.model_dump_json()
+
+ images.save(MagicMock())
+
+ saved_kwargs = services.images.create.call_args.kwargs
+ assert saved_kwargs["graph"] == source_graph_json
+ saved_graph = Graph.model_validate_json(saved_kwargs["resolved_inputs"])
+ saved_add_node = saved_graph.nodes[next(iter(session.source_prepared_mapping["add"]))]
+ assert isinstance(saved_add_node, AddInvocation)
+ assert saved_add_node.a == 17
+ assert saved_kwargs["node_id"] == saved_add_node.id
+ assert set(saved_graph.nodes) == {random_node.id, runtime_add_node.id}
+ assert sorted(
+ (edge.source.node_id, edge.source.field, edge.destination.node_id, edge.destination.field)
+ for edge in saved_graph.edges
+ ) == sorted(
+ [
+ (random_node.id, "value", runtime_add_node.id, "a"),
+ ]
+ )
+ assert graph.nodes["add"].a == 0
+ assert session.graph.model_dump_json() == source_graph_json
+ assert graph.model_dump_json() == source_graph_json
+ assert session.execution_graph.model_dump_json() == execution_graph_json
+ assert saved_kwargs["workflow"] is None
+ assert data.queue_item.workflow is None
+
+
+def test_image_save_graph_uses_active_inputs_before_materialization() -> None:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=2, b=3))
+ session = GraphExecutionState(graph=graph)
+ assert not session.execution_graph.nodes
+
+ services = MagicMock()
+ services.configuration.multiuser = False
+ data = MagicMock()
+ data.queue_item.user_id = "queue-user"
+ data.queue_item.workflow = None
+ data.queue_item.root_item_id = None
+ data.queue_item._workflow_json_loaded = False
+ data.queue_item._workflow_json_snapshot = None
+ data.queue_item.session = session
+ data.queue_item.session_id = "session"
+ data.queue_item.project_id = "project-1"
+ data.invocation = AddInvocation(id="resolved-add", a=17, b=1)
+ images = ImagesInterface(services, data, MagicMock())
+ source_json = graph.model_dump_json()
+
+ images.save(MagicMock())
+
+ saved_kwargs = services.images.create.call_args.kwargs
+ assert saved_kwargs["graph"] == source_json
+ saved_graph_json = saved_kwargs["resolved_inputs"]
+ saved_graph = Graph.model_validate_json(saved_graph_json)
+ saved_add_node = saved_graph.nodes["resolved-add"]
+ assert isinstance(saved_add_node, AddInvocation)
+ assert (saved_add_node.a, saved_add_node.b) == (17, 1)
+ assert set(saved_graph.nodes) == {"resolved-add"}
+ assert saved_graph.edges == []
+ assert graph.model_dump_json() == source_json
+ assert not session.execution_graph.nodes
+
+
[email protected]("cached_workflow", [False, True])
+def test_image_save_graph_png_round_trip(tmp_path: Path, cached_workflow: bool) -> None:
+ session = GraphExecutionState(
+ graph=Graph(
+ nodes={
+ "random": RandomIntInvocation(id="random", low=17, high=18),
+ "add": AddInvocation(id="add", b=1),
+ "downstream": AddInvocation(id="downstream", b=2),
+ },
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id="random", field="value"),
+ destination=EdgeConnection(node_id="add", field="a"),
+ ),
+ Edge(
+ source=EdgeConnection(node_id="add", field="value"),
+ destination=EdgeConnection(node_id="downstream", field="a"),
+ ),
+ ],
+ )
+ )
+ random_node = session.next()
+ assert isinstance(random_node, RandomIntInvocation)
+ session.complete(random_node.id, random_node.invoke(MagicMock()))
+ runtime_add_node = session.next()
+ assert isinstance(runtime_add_node, AddInvocation)
+ assert runtime_add_node.a == 17
+ assert runtime_add_node.id != "add"
+
+ workflow = WorkflowWithoutID.model_validate(
+ {
+ "name": "Reusable image workflow",
+ "author": "",
+ "description": "",
+ "version": "1.0.0",
+ "contact": "",
+ "tags": "",
+ "notes": "Keep the authoring workflow separate from the resolved input record.",
+ "exposedFields": [],
+ "meta": {"category": "user", "version": "3.0.0"},
+ "nodes": [
+ {
+ "id": "random",
+ "type": "invocation",
+ "position": {"x": 0, "y": 0},
+ "data": {"id": "random", "type": "rand_int", "inputs": {"low": {"value": 17}}},
+ },
+ {
+ "id": "add",
+ "type": "invocation",
+ "position": {"x": 100, "y": 0},
+ "data": {"id": "add", "type": "add", "inputs": {"a": {"value": 0}, "b": {"value": 1}}},
+ },
+ ],
+ "edges": [
+ {
+ "id": "random-to-add",
+ "source": "random",
+ "sourceHandle": "value",
+ "target": "add",
+ "targetHandle": "a",
+ "type": "default",
+ }
+ ],
+ }
+ )
+ source_json = session.graph.model_dump_json()
+ workflow_model_json = workflow.model_dump_json()
+ # A recovered queue item's original workflow JSON can have different whitespace from model_dump_json().
+ workflow_json = (
+ json.dumps(json.loads(workflow_model_json), indent=2) + "\n" if cached_workflow else workflow_model_json
+ )
+ services = MagicMock()
+ services.configuration.multiuser = False
+ services.configuration.pil_compress_level = 6
+ storage = DiskImageFileStorage(tmp_path / "outputs")
+ invoker = MagicMock()
+ invoker.services = services
+ storage.start(invoker)
+
+ # PNG persistence and extraction are real; the owning image-service path is covered in its SQLite suite.
+ def create_image(
+ image: Image.Image,
+ metadata: str | None,
+ workflow: str | None,
+ graph: str | None,
+ resolved_inputs: str | None,
+ **kwargs: object,
+ ) -> None:
+ storage.save(
+ image=image,
+ image_name="runtime.png",
+ metadata=metadata,
+ workflow=workflow,
+ graph=graph,
+ resolved_inputs=resolved_inputs,
+ )
+
+ services.images.create.side_effect = create_image
+ data = MagicMock()
+ data.queue_item.user_id = "queue-user"
+ data.queue_item.workflow = workflow
+ data.queue_item.root_item_id = None
+ data.queue_item._workflow_json_loaded = cached_workflow
+ data.queue_item._workflow_json_snapshot = workflow_json if cached_workflow else None
+ data.queue_item.session = session
+ data.queue_item.session_id = "session"
+ data.queue_item.project_id = "project-1"
+ data.invocation = runtime_add_node
+ images = ImagesInterface(services, data, MagicMock())
+
+ with Image.new("RGB", (2, 2), color=(12, 34, 56)) as image:
+ images.save(image)
+
+ # A fresh reader cannot return the writer's cached image with its populated image.info.
+ reader = DiskImageFileStorage(storage.image_root)
+ with reader.get("runtime.png") as reopened:
+ assert (reopened.format, reopened.size, reopened.getpixel((0, 0))) == ("PNG", (2, 2), (12, 34, 56))
+ extracted = extract_metadata_from_image(
+ pil_image=reopened,
+ invokeai_metadata_override=None,
+ invokeai_workflow_override=None,
+ invokeai_graph_override=None,
+ logger=services.logger,
+ )
+ saved_graph = Graph.model_validate_json(reopened.info["invokeai_resolved_inputs"])
+
+ assert extracted.invokeai_graph == source_json
+ saved_node_id = services.images.create.call_args.kwargs["node_id"]
+ assert saved_node_id == runtime_add_node.id
+ saved_add_node = saved_graph.nodes[saved_node_id]
+ assert isinstance(saved_add_node, AddInvocation)
+ assert (saved_add_node.id, saved_add_node.a, saved_add_node.b) == (runtime_add_node.id, 17, 1)
+ assert set(saved_graph.nodes) == {random_node.id, runtime_add_node.id}
+ assert sorted(
+ (edge.source.node_id, edge.source.field, edge.destination.node_id, edge.destination.field)
+ for edge in saved_graph.edges
+ ) == sorted(
+ [
+ (random_node.id, "value", runtime_add_node.id, "a"),
+ ]
+ )
+ assert extracted.invokeai_workflow == workflow_json
+ assert data.queue_item.workflow.model_dump_json() == workflow_model_json
+ assert session.graph.model_dump_json() == source_json
+
+
+def test_image_save_graph_retains_resolved_noise_seed_and_math_ancestors() -> None:
+ graph = Graph(
+ nodes={
+ "random": RandomIntInvocation(id="random", low=17, high=18),
+ "add": AddInvocation(id="add", b=1),
+ "noise": NoiseInvocation(id="noise", width=8, height=8),
+ "image": BlankImageInvocation(id="image", width=1, height=2),
+ "future": AddInvocation(id="future", b=2),
+ },
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id=source, field=output),
+ destination=EdgeConnection(node_id=destination, field=input_),
+ )
+ for source, output, destination, input_ in [
+ ("random", "value", "add", "a"),
+ ("add", "value", "noise", "seed"),
+ ("noise", "width", "image", "width"),
+ ("image", "width", "future", "a"),
+ ]
+ ],
+ )
+ source_json = graph.model_dump_json()
+ session = GraphExecutionState(graph=graph)
+ images, services = _make_interface(allowed=True)
+ services.configuration.multiuser = False
+ data = images._data
+ data.queue_item.session = session
+ data.queue_item.root_item_id = None
+ data.queue_item._workflow_json_loaded = False
+ data.queue_item._workflow_json_snapshot = None
+ services.images.create.return_value = SimpleNamespace(image_name="resolved.png", width=8, height=2)
+ for _ in range(5):
+ node = session.next()
+ assert node is not None
+ data.invocation = node
+ if isinstance(node, BlankImageInvocation):
+ execution_json = session.execution_graph.model_dump_json()
+ node.invoke(MagicMock(images=images))
+ assert session.execution_graph.model_dump_json() == execution_json
+ break
+ if isinstance(node, NoiseInvocation):
+ assert node.seed == 18
+ # Substitute only the tensor-generation boundary. The downstream leaf has no seed input.
+ result = NoiseOutput(noise=LatentsField(latents_name="opaque-noise"), width=8, height=8)
+ else:
+ result = node.invoke(MagicMock())
+ session.complete(node.id, result)
+ else:
+ pytest.fail("Image invocation was not scheduled")
+
+ saved_kwargs = services.images.create.call_args.kwargs
+ assert saved_kwargs["graph"] == source_json
+ saved_graph = Graph.model_validate_json(saved_kwargs["resolved_inputs"])
+ ids = {name: next(iter(session.source_prepared_mapping[name])) for name in ("random", "add", "noise", "image")}
+ assert set(saved_graph.nodes) == set(ids.values())
+ assert saved_kwargs["node_id"] == ids["image"]
+ assert saved_graph.nodes[ids["add"]].a == 17
+ assert saved_graph.nodes[ids["noise"]].seed == 18
+ assert saved_graph.nodes[ids["image"]].width == 8
+ assert {
+ (e.source.node_id, e.source.field, e.destination.node_id, e.destination.field) for e in saved_graph.edges
+ } == {
+ (ids["random"], "value", ids["add"], "a"),
+ (ids["add"], "value", ids["noise"], "seed"),
+ (ids["noise"], "width", ids["image"], "width"),
+ }
+ assert graph.nodes["add"].a == graph.nodes["noise"].seed == 0
+ assert graph.model_dump_json() == source_json
+
+
+ ("boundary", "output", "resolved_value"),
+ [
+ (IterateInvocation(id="boundary", collection=[17, 18]), "item", 17),
+ (CollectInvocation(id="boundary", collection=[17, 18]), "collection", [17, 18]),
+ (IfInvocation(id="boundary", condition=True, true_input=17, false_input=90), "value", 17),
+ (ForInvocation(id="boundary", collection=[17, 18], index=0), "item", 17),
+ (ForReturnInvocation(id="boundary", output=17), "output", 17),
+ (CallSavedWorkflowInvocation(id="boundary", workflow_id="saved"), "values", {"seed": 17}),
+ (CollectionConcatInvocation(id="boundary", first=[17, 18]), "collection", [17, 18]),
+ (AnyTypeTestInvocation(id="boundary", value=[17, 18]), "value", [17, 18]),
+ ],
+)
+def test_image_graph_projection_keeps_resolved_inputs_across_boundaries(
+ boundary: BaseInvocation, output: str, resolved_value: object
+) -> None:
+ graph = Graph(
+ nodes={"boundary": boundary, "active": AnyTypeTestInvocation(id="active")},
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id="boundary", field=output),
+ destination=EdgeConnection(node_id="active", field="value"),
+ )
+ ],
+ )
+ before = graph.model_dump_json()
+ active = AnyTypeTestInvocation(id="active", value=resolved_value)
+
+ record = graph._get_invocation_input_graph(active)
+
+ assert set(record.nodes) == {active.id}
+ assert record.nodes[active.id].value == resolved_value
+ assert record.edges == []
+ assert graph.model_dump_json() == before
+
+
+def test_image_save_graph_nested_iterate_keeps_one_resolved_record_per_image(tmp_path: Path) -> None:
+ measurements = []
+ saved_runs = []
+ for outer_size, inner_size in [(2, 3), (4, 6)]:
+ values = [[10 + i * inner_size + j for j in range(inner_size)] for i in range(outer_size)]
+ graph = Graph(
+ nodes={
+ "source": CollectionConcatInvocation(id="source", first=values),
+ "outer": IterateInvocation(id="outer"),
+ "prepare": CollectionConcatInvocation(id="prepare"),
+ "inner": IterateInvocation(id="inner"),
+ "image": BlankImageInvocation(id="image", width=1, height=2),
+ },
+ edges=[
+ Edge(
+ source=EdgeConnection(node_id=source, field=output),
+ destination=EdgeConnection(node_id=destination, field=input_),
+ )
+ for source, output, destination, input_ in [
+ ("source", "collection", "outer", "collection"),
+ ("outer", "item", "prepare", "first"),
+ ("prepare", "collection", "inner", "collection"),
+ ("inner", "item", "image", "width"),
+ ]
+ ],
+ )
+ source_json = graph.model_dump_json()
+ session = GraphExecutionState(graph=graph)
+ images, services = _make_interface(allowed=True)
+ services.configuration.multiuser = False
+ services.configuration.pil_compress_level = 6
+ data = images._data
+ data.queue_item.session = session
+ data.queue_item.root_item_id = None
+ data.queue_item._workflow_json_loaded = False
+ data.queue_item._workflow_json_snapshot = None
+ storage = DiskImageFileStorage(tmp_path / f"{outer_size}x{inner_size}")
+ storage.start(SimpleNamespace(services=services))
+ saved: list[tuple[str, str, str, str, int]] = []
+
+ def create_image(
+ image: Image.Image,
+ graph: str,
+ resolved_inputs: str,
+ *,
+ _storage: DiskImageFileStorage = storage,
+ _saved: list[tuple[str, str, str, str, int]] = saved,
+ **kwargs: object,
+ ) -> SimpleNamespace:
+ image_name = f"{len(_saved)}.png"
+ _storage.save(image=image, image_name=image_name, graph=graph, resolved_inputs=resolved_inputs)
+ node_id = kwargs["node_id"]
+ assert isinstance(node_id, str)
+ _saved.append((image_name, graph, resolved_inputs, node_id, image.width))
+ return SimpleNamespace(image_name=image_name, width=image.width, height=image.height)
+
+ services.images.create.side_effect = create_image
+ context = MagicMock(images=images)
+ # Bound scheduler calls to catch a stalled loop without asserting execution time.
+ for _ in range(2 + 2 * outer_size + 2 * outer_size * inner_size):
+ node = session.next()
+ if node is None:
+ break
+ data.invocation = node
+ execution_json = session.execution_graph.model_dump_json()
+ result = node.invoke(context)
+ assert session.execution_graph.model_dump_json() == execution_json
+ session.complete(node.id, result)
+ else:
+ pytest.fail("Nested Iterate graph did not finish")
+
+ assert session.is_complete()
+ assert [width for _, _, _, _, width in saved] == [value for group in values for value in group]
+ assert graph.model_dump_json() == source_json
+ reader = DiskImageFileStorage(storage.image_root)
+ for image_name, graph_json, resolved_json, _, _ in saved:
+ assert reader.get_graph(image_name) == graph_json
+ with reader.get(image_name) as reopened:
+ assert reopened.info["invokeai_resolved_inputs"] == resolved_json
+ assert graph_json == source_json
+ payloads = [json.loads(resolved_json) for _, _, resolved_json, _, _ in saved]
+ source_byte_counts = [len(graph_json.encode("utf-8")) for _, graph_json, _, _, _ in saved]
+ resolved_byte_counts = [len(resolved_json.encode("utf-8")) for _, _, resolved_json, _, _ in saved]
+ byte_counts = [
+ source_bytes + resolved_bytes
+ for source_bytes, resolved_bytes in zip(source_byte_counts, resolved_byte_counts, strict=True)
+ ]
+ measurements.append(
+ {
+ "shape": [outer_size, inner_size],
+ "images": len(saved),
+ "per_image_bytes": byte_counts,
+ "total_bytes": sum(byte_counts),
+ "source_bytes": len(source_json.encode("utf-8")),
+ "per_image_resolved_bytes": resolved_byte_counts,
+ "total_resolved_bytes": sum(resolved_byte_counts),
+ "resolved_node_counts": [len(payload["nodes"]) for payload in payloads],
+ "source_node_counts": [len(json.loads(graph_json)["nodes"]) for _, graph_json, _, _, _ in saved],
+ }
+ )
+ saved_runs.append(saved)
+
+ # Count both persisted channels: the complete source graph and the compact input record.
+ print("NESTED_IMAGE_GRAPH_MEASUREMENTS=" + json.dumps(measurements))
+ for saved in saved_runs:
+ for _, _, resolved_json, node_id, width in saved:
+ saved_graph = Graph.model_validate_json(resolved_json)
+ assert set(saved_graph.nodes) == {node_id}
+ assert saved_graph.edges == []
+ saved_node = saved_graph.nodes[node_id]
+ assert isinstance(saved_node, BlankImageInvocation)
+ assert (saved_node.id, saved_node.width, saved_node.height) == (node_id, width, 2)
+ assert node_id != "image"
+ assert len(node_id) == len(saved_graph.id) == 36
+ # Fixed-width resolved inputs cost no extra bytes as runtime copies grow. The authoring collection grows.
+ assert len(set(measurements[0]["per_image_resolved_bytes"] + measurements[1]["per_image_resolved_bytes"])) == 1
+ assert measurements[1]["total_resolved_bytes"] == 4 * measurements[0]["total_resolved_bytes"]
+ for measurement in measurements:
+ assert measurement["total_bytes"] == (
+ measurement["images"] * measurement["source_bytes"] + measurement["total_resolved_bytes"]
+ )
diff --git a/tests/app/test_extract_metadata.py b/tests/app/test_extract_metadata.py
index 682cc22b1a..2ca7dead33 100644
--- a/tests/app/test_extract_metadata.py
+++ b/tests/app/test_extract_metadata.py
@@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patch
import pytest
from PIL import Image
-from invokeai.app.api.extract_metadata import ExtractedMetadata, extract_metadata_from_image
+from invokeai.app.api.extract_metadata import ExtractedMetadata, extract_metadata, extract_metadata_from_image
@pytest.fixture
@@ -223,6 +223,55 @@ def test_empty_string_overrides_do_not_fall_back_to_image_metadata(
assert result.invokeai_graph is None
+def test_image_extraction_preserves_community_resolved_inputs_verbatim(mock_logger):
+ resolved = '{ "nodes": {"custom": {"type": "community_node", "input": null}}, "edges": [], "extra": true }\n'
+ source = '{ "nodes": {}, "edges": [] }'
+ override = '{"resolved_inputs": "user metadata", "invokeai_resolved_inputs": {"custom": true}}'
+ with Image.new("RGB", (2, 2)) as image:
+ image.info = {
+ "invokeai_graph": source,
+ "invokeai_metadata": '{"seed": 0}',
+ "invokeai_resolved_inputs": resolved,
+ }
+ result = extract_metadata_from_image(image, override, None, None, mock_logger)
+ shared = extract_metadata(image.info, override, None, None, mock_logger)
+ assert result == ExtractedMetadata(override, None, source, resolved)
+ # The shared entry point still handles only the three common channels, including old positional callers.
+ assert shared == ExtractedMetadata(override, None, source)
+
+
+ "raw",
+ [
+ None,
+ 42,
+ {"nodes": {}, "edges": []},
+ "",
+ "not JSON",
+ "null",
+ "[]",
+ "{}",
+ '{"nodes": [], "edges": []}',
+ '{"nodes": {}, "edges": {}}',
+ '{"nodes": {}}',
+ '{"edges": []}',
+ ],
+)
+def test_bad_optional_image_inputs_leave_common_channels_intact(mock_logger, raw):
+ metadata = '{"seed": 18, "resolved_inputs": "user-owned"}'
+ workflow = json.dumps(MINIMAL_WORKFLOW)
+ graph = '{"nodes": {}, "edges": []}'
+ with Image.new("RGB", (2, 2)) as image:
+ image.info = {
+ "invokeai_metadata": metadata,
+ "invokeai_workflow": workflow,
+ "invokeai_graph": graph,
+ "invokeai_resolved_inputs": raw,
+ }
+ result = extract_metadata_from_image(image, None, None, None, mock_logger)
+ assert result == ExtractedMetadata(metadata, workflow, graph)
+
+
# --- MP4 sources -----------------------------------------------------------------------------
@@ -247,6 +296,8 @@ def tagged_mp4(tmp_path_factory: pytest.TempPathFactory):
"invokeai_metadata": json.dumps({"seed": 42, "generation_mode": "wan_t2v"}),
"invokeai_workflow": json.dumps(MINIMAL_WORKFLOW),
"invokeai_graph": json.dumps({"nodes": {}, "edges": []}),
+ # PNG's optional diagnostic channel is not part of the MP4 extraction contract.
+ "invokeai_resolved_inputs": json.dumps({"nodes": {}, "edges": []}),
}
write_mp4_tags(plain, tagged, tags)
return tagged, plain, tags