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.

Restore Canvas metadata and recall parity (#10127)

Josh Corbettcbe7fd823903
diff --git a/.github/actions/install-frontend-deps/action.yml b/.github/actions/install-frontend-deps/action.yml
index 49ccb9b3d0..b2cd0cb962 100644
--- a/.github/actions/install-frontend-deps/action.yml
+++ b/.github/actions/install-frontend-deps/action.yml
@@ -5,13 +5,17 @@ inputs:
description: Directory to install dependencies in
required: false
default: invokeai/frontend/webv2
+ node-version-file:
+ description: Node version file relative to the workspace
+ required: false
+ default: .nvmrc
runs:
using: 'composite'
steps:
- name: setup node 22
uses: actions/setup-node@v6
with:
- node-version-file: '.nvmrc'
+ node-version-file: ${{ inputs.node-version-file }}
- name: setup pnpm
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.yml
index d19d96cf91..b4e6b25fbd 100644
--- a/.github/workflows/frontend-tests.yml
+++ b/.github/workflows/frontend-tests.yml
@@ -77,11 +77,9 @@ jobs:
shell: bash
# A pull request into main, or a merge group, is compared with the base branch's
- # own measurements, restored from the cache every push to main fills below: the exact base
- # commit when it has an entry, otherwise the most recent main entry (a main job that failed or
- # is still running leaves no hole). Anything else compares against the committed baseline. The
- # gate also honors deliberately re-recorded byte baselines. It logs which reference it used,
- # and the restored key is passed through so reports can name it.
+ # own measurements at the exact base commit. A skipped or failed main run may leave no cache
+ # entry; measure that base in isolation rather than compare with an older main's smaller payload.
+ # Other events compare against the committed baseline. Candidate gates remain strict in every case.
- name: restore performance reference
id: perf-ref
if: ${{ (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) && ((github.event_name == 'pull_request' && github.base_ref == 'main') || (github.event_name == 'merge_group' && github.event.merge_group.base_ref == 'refs/heads/main')) }}
@@ -89,29 +87,88 @@ jobs:
with:
path: invokeai/frontend/webv2/artifacts/perf-reference
key: webv2-perf-reference-${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
- restore-keys: webv2-perf-reference-
- - name: note a missing performance reference
- if: ${{ steps.perf-ref.outcome == 'success' && steps.perf-ref.outputs.cache-matched-key == '' }}
- run: 'echo "::warning::No performance reference was restored; byte budgets are compared against the committed baseline."'
+ - name: check out missing performance base
+ id: perf-base
+ if: ${{ steps.perf-ref.outcome == 'success' && steps.perf-ref.outputs.cache-hit != 'true' }}
+ uses: useblacksmith/checkout@25227e61ff9dafe400e22fa487b673eac4e4409a # v1.8.1
+ with:
+ ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
+ path: .perf-base
+ persist-credentials: false
+
+ - name: install performance base dependencies
+ if: ${{ steps.perf-base.outcome == 'success' }}
+ uses: ./.github/actions/install-frontend-deps
+ with:
+ working-directory: .perf-base/invokeai/frontend/webv2
+ node-version-file: .perf-base/.nvmrc
+
+ - name: measure missing performance base
+ if: ${{ steps.perf-base.outcome == 'success' }}
+ working-directory: .perf-base/invokeai/frontend/webv2
+ env:
+ WEBV2_PERF_REFERENCE_DIR: ''
+ WEBV2_PERF_REFERENCE_LABEL: ''
+ run: |
+ pnpm exec playwright install --with-deps chromium
+ pnpm exec vite build
+ rm -f artifacts/architecture-performance/build-reference.json artifacts/architecture-performance/browser-reference.json
+ # Measurements are written before budget checks. Both must exist even if the base has outgrown its budgets.
+ node --experimental-strip-types scripts/check-architecture-performance.mjs || echo "::notice::Base build check failed; validating its measurements below."
+ node scripts/measure-architecture-performance.mjs || echo "::notice::Base browser check failed; validating its measurements below."
+ node --input-type=module <<'NODE'
+ import { copyFile, mkdir, readFile } from 'node:fs/promises';
+ import { resolve } from 'node:path';
+ import { pathToFileURL } from 'node:url';
+ const candidate = resolve(process.env.GITHUB_WORKSPACE, 'invokeai/frontend/webv2');
+ const { applyBuildReference, applyBrowserReference, loadPerformanceReference, BUILD_METRIC_KEYS, BROWSER_RESOURCE_METRIC_KEYS } =
+ await import(pathToFileURL(resolve(candidate, 'scripts/performance-budgets.mjs')));
+ for (const [kind, metricKeys, baselineFile] of [
+ ['build', BUILD_METRIC_KEYS, 'architecture-baseline.json'],
+ ['browser', BROWSER_RESOURCE_METRIC_KEYS, 'browser-baseline.json'],
+ ]) {
+ const fileName = `${kind}-reference.json`;
+ const { reference, reason } = await loadPerformanceReference({
+ directory: 'artifacts/architecture-performance', fileName, kind, metricKeys, root: process.cwd(),
+ });
+ if (reason) throw new Error(`Invalid exact-base ${kind} reference: ${reason}`);
+ const baseline = JSON.parse(await readFile(`performance/${baselineFile}`, 'utf8'));
+ const applied = kind === 'build' ? applyBuildReference(baseline.build, reference) : applyBrowserReference(baseline.routes, reference);
+ if (applied.uncovered.length) throw new Error(`Incomplete exact-base ${kind} reference: ${applied.uncovered.join(', ')}`);
+ }
+ const destination = resolve(candidate, 'artifacts/perf-reference');
+ await mkdir(destination, { recursive: true });
+ for (const kind of ['build', 'browser']) {
+ await copyFile(`artifacts/architecture-performance/${kind}-reference.json`, resolve(destination, `${kind}-reference.json`));
+ }
+ NODE
shell: bash
+ - name: restore candidate Node version
+ if: ${{ steps.perf-base.outcome == 'success' }}
+ uses: actions/setup-node@v6
+ with:
+ node-version-file: .nvmrc
+
- name: release completion gates
if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
run: 'pnpm check:release:tests'
shell: bash
env:
- WEBV2_PERF_REFERENCE_DIR: ${{ steps.perf-ref.outputs.cache-matched-key != '' && 'artifacts/perf-reference' || '' }}
- WEBV2_PERF_REFERENCE_LABEL: ${{ steps.perf-ref.outputs.cache-matched-key }}
+ WEBV2_PERF_REFERENCE_DIR: ${{ steps.perf-ref.outcome == 'success' && 'artifacts/perf-reference' || '' }}
+ WEBV2_PERF_REFERENCE_LABEL: ${{ steps.perf-ref.outcome == 'success' && format('webv2-perf-reference-{0}', github.event.pull_request.base.sha || github.event.merge_group.base_sha) || '' }}
# Recorded even when the gate failed: a main that has outgrown the committed baseline is
# still the right thing for a pull request to be compared with. A main job that ran the gate
# but produced no reference (a failure before the browser stage) records nothing and says so;
- # one that left webv2 untouched has nothing to record. Pull requests based on either restore
- # the most recent main entry instead.
+ # one that left webv2 untouched has nothing to record. Pull requests based on either measure
+ # that exact base instead.
- name: stage performance reference
id: perf-ref-stage
if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && (steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true) }}
+ env:
+ REFERENCE_SHA: ${{ github.sha }}
run: |
if [ -f artifacts/architecture-performance/build-reference.json ] && [ -f artifacts/architecture-performance/browser-reference.json ]; then
mkdir -p artifacts/perf-reference
@@ -119,7 +176,7 @@ jobs:
echo "ready=true" >> "$GITHUB_OUTPUT"
else
echo "ready=false" >> "$GITHUB_OUTPUT"
- echo "::warning::No performance reference recorded for ${{ github.sha }}; pull requests based on it fall back to the most recent main reference."
+ echo "::warning::No performance reference recorded for $REFERENCE_SHA; pull requests based on it measure their exact base."
fi
shell: bash
diff --git a/invokeai/frontend/webv2/performance/README.md b/invokeai/frontend/webv2/performance/README.md
index 62cd8d9c31..720ff9128f 100644
--- a/invokeai/frontend/webv2/performance/README.md
+++ b/invokeai/frontend/webv2/performance/README.md
@@ -23,7 +23,7 @@ Baseline byte budgets record measurements only. Each byte ceiling is the lower o
Reference modes:
-- PRs into `main` and merge groups targeting `main`: CI restores `main`'s own measurements from the Actions cache (`WEBV2_PERF_REFERENCE_DIR`). Logs and reports name the restored reference.
+- PRs into `main` and merge groups targeting `main`: CI restores the exact base commit's measurements from the Actions cache (`WEBV2_PERF_REFERENCE_DIR`). On a cache miss it checks out that pinned base separately, installs its dependencies and Node version, builds once, and records both build and browser resources. Base budget failures still permit recording, but missing, malformed, incompatible, or incomplete measurements stop the job. Both reference files must come from that base; older cached or candidate measurements cannot substitute. Logs and reports name the exact base SHA. Candidate completion gates retain their normal strict checks.
- Local runs, pushes to `main`, stacked PRs without a reference: compare against committed measurements directly.
- Every mode pins source-owner sets exactly: a module entering a route's initial graph fails at zero bytes.
- Request counts have no allowance; cap is the lower of reference and committed counts.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index e93fefbc26..324f64955c 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -181,6 +181,7 @@
"archived": "Archived",
"asc": "Asc",
"assets": "Uploads",
+ "auto": "Auto",
"cancel": "Cancel",
"cancelFailed": "Cancel failed",
"canceled": "Canceled",
@@ -3858,7 +3859,109 @@
"use": "Use",
"useInGenerate": "Use this image in Generate",
"useThisVideo": "Use this video",
- "showGallery": "Show Gallery"
+ "showGallery": "Show Gallery",
+ "metadataWeight": "Weight {{weight}}",
+ "metadataMore": "{{count}} more (see raw JSON)",
+ "metadataLayerCount_one": "{{count}} layer",
+ "metadataLayerCount_other": "{{count}} layers",
+ "metadataLabels": {
+ "app_version": "Created by",
+ "generation_mode": "Generation mode",
+ "rand_device": "Random device",
+ "cfg_rescale_multiplier": "CFG rescale multiplier",
+ "strength": "Denoising strength",
+ "seamless_x": "Seamless x",
+ "seamless_y": "Seamless y",
+ "dype_preset": "Dype preset",
+ "dype_scale": "Dype scale",
+ "dype_exponent": "Dype exponent",
+ "hidiffusion": "Hidiffusion",
+ "hidiffusion_raunet": "Hidiffusion raunet",
+ "hidiffusion_window_attn": "Hidiffusion window attn",
+ "hidiffusion_t1_ratio": "Hidiffusion t1 ratio",
+ "hidiffusion_t2_ratio": "Hidiffusion t2 ratio",
+ "refiner_steps": "Refiner steps",
+ "refiner_cfg_scale": "Refiner cfg scale",
+ "refiner_scheduler": "Refiner scheduler",
+ "refiner_positive_aesthetic_score": "Refiner positive aesthetic score",
+ "refiner_negative_aesthetic_score": "Refiner negative aesthetic score",
+ "refiner_start": "Refiner start",
+ "refiner_denoising_start": "Refiner denoising start",
+ "z_image_seed_variance_enabled": "Z image seed variance enabled",
+ "z_image_seed_variance_strength": "Z image seed variance strength",
+ "z_image_seed_variance_randomize_percent": "Z image seed variance randomize percent",
+ "z_image_shift": "Z image shift",
+ "qwen_image_quantization": "Qwen image quantization",
+ "qwen_image_shift": "Qwen image shift",
+ "wan_guidance_scale_low_noise": "Wan guidance scale low noise",
+ "krea2_seed_variance_enabled": "Krea2 seed variance enabled",
+ "krea2_seed_variance_strength": "Krea2 seed variance strength",
+ "krea2_seed_variance_randomize_percent": "Krea2 seed variance randomize percent",
+ "krea2_rebalance_enabled": "Krea2 rebalance enabled",
+ "krea2_rebalance_multiplier": "Krea2 rebalance multiplier",
+ "krea2_rebalance_weights": "Krea2 rebalance weights",
+ "krea2_reference_kv_cache": "Krea2 reference kv cache",
+ "anima_inpaint_adapter_weight": "Anima inpaint adapter weight",
+ "ideogram4_sampler_preset": "Ideogram4 sampler preset",
+ "ideogram4_steps": "Ideogram4 steps",
+ "ideogram4_guidance_scale": "Ideogram4 guidance scale",
+ "ideogram4_mu": "Ideogram4 mu",
+ "ideogram4_caption": "Ideogram4 caption",
+ "image_size": "Image size",
+ "gemini_temperature": "Gemini temperature",
+ "gemini_thinking_level": "Gemini thinking level",
+ "openai_quality": "Openai quality",
+ "openai_background": "Openai background",
+ "openai_input_fidelity": "Openai input fidelity",
+ "seedream_watermark": "Seedream watermark",
+ "seedream_optimize_prompt": "Seedream optimize prompt",
+ "minimax_h3_duration_seconds": "Minimax h3 duration seconds",
+ "minimax_h3_output_mode": "Minimax h3 output mode",
+ "duration": "Duration",
+ "duration_seconds": "Duration seconds",
+ "resolution": "Resolution",
+ "aspect_ratio": "Aspect ratio",
+ "cfg_scale_low_noise": "Cfg scale low noise",
+ "motion_bucket_id": "Motion bucket id",
+ "noise_aug_strength": "Noise aug strength",
+ "num_inference_steps": "Num inference steps",
+ "ltx2_scheduler": "Ltx2 scheduler",
+ "ltx2_distilled": "Ltx2 distilled",
+ "ltx2_audio_enabled": "Ltx2 audio enabled",
+ "vae": "VAE",
+ "refiner_model": "Refiner model",
+ "t5_encoder": "T5 encoder",
+ "clip_embed_model": "Clip embed model",
+ "gemma2_encoder": "Gemma2 encoder",
+ "qwen3_encoder": "Qwen3 encoder",
+ "qwen3_source": "Qwen3 source",
+ "anima_inpaint_adapter": "Anima inpaint adapter",
+ "qwen3_vl_encoder": "Qwen3 vl encoder",
+ "qwen3_5_encoder": "Qwen3 5 encoder",
+ "mistral_encoder": "Mistral encoder",
+ "qwen_image_component_source": "Qwen image component source",
+ "qwen_image_vae": "Qwen image vae",
+ "qwen_image_qwen_vl_encoder": "Qwen image qwen vl encoder",
+ "wan_component_source": "Wan component source",
+ "wan_transformer_low_noise": "Wan transformer low noise",
+ "wan_vae_model": "Wan vae model",
+ "wan_t5_encoder_model": "Wan t5 encoder model",
+ "minimax_h3_transformer_model": "Minimax h3 transformer model",
+ "minimax_h3_text_encoder_model": "Minimax h3 text encoder model",
+ "ideogram4_unconditional_model": "Ideogram4 unconditional model",
+ "ideogram4_color_palette": "Ideogram4 color palette",
+ "loras": "LoRAs",
+ "ref_images": "Reference images",
+ "control_layers": "Executed controls",
+ "controlnets": "ControlNets",
+ "t2iAdapters": "T2i adapters",
+ "ipAdapters": "IP-Adapters",
+ "regions": "Regions",
+ "canvas_layers": "Canvas layers",
+ "metadata_source": "Metadata source"
+ },
+ "canvasSaveSource": "Saved canvas (authored settings)",
+ "metadataSchedule": "Steps {{begin}}–{{end}}"
},
"queue": {
"actionConfirmationTitle": "{{action}}?",
@@ -5921,6 +6024,27 @@
"prompts": "Recalled prompts",
"remix": "Remixed video",
"seed": "Recalled seed"
+ },
+ "beforeCanvasRecall": "Before metadata recall",
+ "canvasImagesTemporary": "Canvas was recalled, but some restored paint images are still temporary. Keep the project open or save it before closing to protect them from intermediate cleanup.",
+ "canvasRecalled": "Canvas layers and available settings recalled. Replaced canvases remain available in History restore points.",
+ "canvasPartial": "Some canvas metadata could not be restored: {{items}}. Existing work was preserved.",
+ "referenceImagesPartial": "Some recorded reference images are unavailable or unsupported. Existing references were kept when none could be restored.",
+ "canvasReasons": {
+ "record-too-large": "the canvas record exceeds the metadata size limit",
+ "invalid-record": "the canvas metadata version is damaged or unsupported",
+ "invalid-document": "the canvas document is damaged or unsupported",
+ "canvas-changed": "the canvas changed while metadata was loading",
+ "canvas-busy": "finish the current canvas edit first",
+ "model-changed": "the model changed while metadata was loading",
+ "canvas-pending-results": "recalled layers were added to keep staged and running results",
+ "canvas-limit": "the recalled layers could not fit in the current canvas",
+ "unsupported-control": "a recorded control weight schedule or resize mode cannot be represented in Canvas",
+ "unsupported-legacy-layers": "legacy vector layers cannot be restored",
+ "invalid-control": "a control entry is damaged",
+ "invalid-control-image": "a control image is unavailable",
+ "image-lookup-failed": "canvas images could not be checked; try recalling again",
+ "invalid-strength": "the recorded denoising strength is outside the Canvas range"
}
},
"star": {
@@ -6379,8 +6503,8 @@
"conditioningClipBlocked": "Clear the Initial Video and References to use a conditioning clip.",
"twoStageConditioningBlocked": "A conditioning clip cannot run a two-stage resolution. Pick a single-stage one.",
"conditioningRole": "Use from this clip",
- "conditioningRoleAudio": "Its soundtrack \u2014 generate the picture",
- "conditioningRoleVideo": "Its picture \u2014 generate the soundtrack",
+ "conditioningRoleAudio": "Its soundtrack — generate the picture",
+ "conditioningRoleVideo": "Its picture — generate the soundtrack",
"conditioningRoleVideoBlocked": "Clear the First Frame and Last Frame to use this clip's picture.",
"conditioningRoleVideoHelp": "The clip is re-encoded at the generation's canvas, so the picture comes back cropped and recompressed.",
"conditioningDerivedAudio": "{{frames}} frames at {{fps}} FPS, from the soundtrack's length.",
@@ -6702,7 +6826,7 @@
"clusterStrength": "Clustering strength",
"clusterStrengthHint": "Higher values create larger clusters",
"clusterStrengthAuto": "auto",
- "clusterStrengthIncomplete": "Not a number yet \u2014 the clustering strength is unchanged.",
+ "clusterStrengthIncomplete": "Not a number yet — the clustering strength is unchanged.",
"clusterStrengthRange": "Clustering strength must be between {{min}} and {{max}}."
},
"defaultsNote": "Defaults for every project. A project can pin its own value.",
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
index 1b54809c20..9be2a5dea9 100644
--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.mjs
@@ -4,7 +4,15 @@ import { resolve } from 'node:path';
const splitLocale = (translations) => {
const { fonts, ...translation } = translations;
- return { translation, fonts: fonts ? { fonts } : {} };
+ const { metadataLabels, ...preview } = translation.widgets?.preview ?? {};
+ if (metadataLabels !== undefined) {
+ translation.widgets = { ...translation.widgets, preview };
+ }
+ return {
+ translation,
+ fonts: fonts ? { fonts } : {},
+ metadata: metadataLabels === undefined ? {} : { widgets: { preview: { metadataLabels } } },
+ };
};
/** The files a build emits for `public/locales`, sorted by name so the version does not depend on readdir order. */
@@ -27,13 +35,14 @@ const buildLocaleAssets = async (projectRoot) => {
return [
{ fileName: `locales/${name}`, source: JSON.stringify(parts.translation) },
{ fileName: `locales/${name.replace('.json', '.fonts.json')}`, source: JSON.stringify(parts.fonts) },
+ { fileName: `locales/${name.replace('.json', '.metadata.json')}`, source: JSON.stringify(parts.metadata) },
];
});
};
/**
- * Keep source locales readable; load font-library copy only when that UI opens. Locale URLs stay the same across
- * releases, so the injected content version tells the client and service worker which files a build carries.
+ * Keep source locales readable; load font-library and metadata labels only when their UI opens. Locale URLs stay
+ * the same across releases, so the injected content version tells the client and service worker which files a build carries.
*/
export const localeAssetsPlugin = ({ projectRoot }) => {
let assets;
@@ -52,7 +61,7 @@ export const localeAssetsPlugin = ({ projectRoot }) => {
// Read per request so edits show without a restart. The version stays at its startup value, which only the
// production service worker relies on.
server.middlewares.use(async (request, response, next) => {
- const match = request.url?.match(/\/locales\/([a-zA-Z0-9_-]+)(\.fonts)?\.json(?:\?.*)?$/);
+ const match = request.url?.match(/\/locales\/([a-zA-Z0-9_-]+)(?:\.(fonts|metadata))?\.json(?:\?.*)?$/);
if (!match) {
next();
return;
@@ -61,7 +70,7 @@ export const localeAssetsPlugin = ({ projectRoot }) => {
const source = await readFile(resolve(projectRoot, `public/locales/${match[1]}.json`), 'utf8');
const parts = splitLocale(JSON.parse(source));
response.setHeader('Content-Type', 'application/json');
- response.end(JSON.stringify(match[2] ? parts.fonts : parts.translation));
+ response.end(JSON.stringify(parts[match[2] ?? 'translation']));
} catch (error) {
if (error.code === 'ENOENT') {
next();
diff --git a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
index c8e99be589..7dbd241dd9 100644
--- a/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
+++ b/invokeai/frontend/webv2/scripts/locale-assets-plugin.test.mjs
@@ -104,19 +104,35 @@ test('invalid locale JSON fails the production build with the failing filename',
await assert.rejects(buildFixture(projectRoot), /Invalid locale JSON: broken\.json/);
});
-test('font namespace loads separately in production and development, preserving fallback locales', async (context) => {
+test('cold namespaces load separately in production and development, preserving fallback locales', async (context) => {
const projectRoot = await createFixture(context);
- const translations = { common: { retry: 'Retry' }, fonts: { title: 'Fonts 🎨' } };
+ const translations = {
+ common: { retry: 'Retry' },
+ fonts: { title: 'Fonts 🎨' },
+ widgets: { preview: { details: 'Details', metadataLabels: { control_layers: 'Control layers 🎨' } } },
+ };
await writeFile(resolve(projectRoot, 'public/locales/en.json'), JSON.stringify(translations));
await writeFile(resolve(projectRoot, 'public/locales/fr.json'), JSON.stringify({ common: { retry: 'Réessayer' } }));
await buildFixture(projectRoot);
assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/en.json'), 'utf8')), {
common: translations.common,
+ widgets: { preview: { details: 'Details' } },
});
assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/en.fonts.json'), 'utf8')), {
fonts: translations.fonts,
});
assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/fr.fonts.json'), 'utf8')), {});
+ assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/en.metadata.json'), 'utf8')), {
+ widgets: { preview: { metadataLabels: translations.widgets.preview.metadataLabels } },
+ });
+ assert.deepEqual(JSON.parse(await readFile(resolve(projectRoot, 'dist/locales/fr.metadata.json'), 'utf8')), {});
+ const originalVersion = await readBuiltLocaleVersion(projectRoot);
+ const originalRoot = await readFile(resolve(projectRoot, 'dist/locales/en.json'), 'utf8');
+ translations.widgets.preview.metadataLabels.control_layers = 'Control adapters';
+ await writeFile(resolve(projectRoot, 'public/locales/en.json'), JSON.stringify(translations));
+ await buildFixture(projectRoot);
+ assert.equal(await readFile(resolve(projectRoot, 'dist/locales/en.json'), 'utf8'), originalRoot);
+ assert.notEqual(await readBuiltLocaleVersion(projectRoot), originalVersion);
const server = await createServer({
root: projectRoot,
configFile: false,
@@ -129,7 +145,7 @@ test('font namespace loads separately in production and development, preserving
try {
await server.listen();
const origin = server.resolvedUrls.local[0];
- for (const filename of ['en.json', 'en.fonts.json', 'fr.fonts.json']) {
+ for (const filename of ['en.json', 'en.fonts.json', 'fr.fonts.json', 'en.metadata.json', 'fr.metadata.json']) {
// Versioned like the client's requests.
const response = await fetch(new URL(`locales/${filename}?v=0123456789ab`, origin));
assert.equal(response.status, 200);
@@ -138,6 +154,12 @@ test('font namespace loads separately in production and development, preserving
JSON.parse(await readFile(resolve(projectRoot, `dist/locales/${filename}`), 'utf8'))
);
}
+ translations.widgets.preview.metadataLabels.control_layers = 'Updated controls';
+ await writeFile(resolve(projectRoot, 'public/locales/en.json'), JSON.stringify(translations));
+ const updated = await fetch(new URL('locales/en.metadata.json?v=0123456789ab', origin));
+ assert.deepEqual(await updated.json(), {
+ widgets: { preview: { metadataLabels: { control_layers: 'Updated controls' } } },
+ });
} finally {
await server.close();
}
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index d5b9e8174b..5044d4c76e 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -2405,6 +2405,41 @@ test('wildcards are stateful: create, rename, delete one, and delete a batch of
}
});
+test('image PATCH adopts an intermediate as hidden durable Canvas pixels on every read', async () => {
+ await withRepresentativeBackend(async (backend) => {
+ const form = new FormData();
+ form.append('file', new Blob(['paint'], { type: 'image/png' }), 'paint.png');
+ const response = await fetch(`${backend.origin}/api/v1/images/upload?image_category=general&is_intermediate=true`, {
+ method: 'POST',
+ body: form,
+ });
+ const temporary = await response.json();
+ assert.equal(temporary.is_intermediate, true);
+ const path = `/api/v1/images/i/${encodeURIComponent(temporary.image_name)}`;
+ const adopted = await getJson(backend, path, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ is_intermediate: false, image_category: 'other' }),
+ });
+ assert.deepEqual(adopted, { ...temporary, is_intermediate: false, image_category: 'other' });
+ assert.deepEqual(await getJson(backend, path), adopted);
+ assert.deepEqual(
+ await getJson(backend, '/api/v1/images/images_by_names', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ image_names: [temporary.image_name] }),
+ }),
+ [adopted]
+ );
+ const missing = await fetch(`${backend.origin}/api/v1/images/i/missing.png`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ is_intermediate: false }),
+ });
+ assert.equal(missing.status, 404);
+ });
+});
+
test('opt-in large library has pageable metadata, representative documents, retry and revision scenarios', async () => {
const backend = await startMockBackend(0, { profile: 'representative' });
try {
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index d10f5d4322..05f2819137 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -2977,11 +2977,29 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt
}
const imageMatch = /^\/api\/v1\/images\/i\/([^/]+)$/.exec(path);
- if (imageMatch) {
+ if ((method === 'GET' || method === 'PATCH') && imageMatch) {
const imageName = decodeURIComponent(imageMatch[1]);
const image = state.images.get(imageName);
-
- return image ? json(200, image) : json(404, { detail: 'Image not found' });
+ if (!image) {
+ return json(404, { detail: 'Image not found' });
+ }
+ if (method === 'PATCH') {
+ const changes = await readJsonBody(request);
+ if (
+ ('is_intermediate' in changes && typeof changes.is_intermediate !== 'boolean') ||
+ ('image_category' in changes &&
+ !['general', 'control', 'mask', 'user', 'other'].includes(changes.image_category))
+ ) {
+ return json(422, { detail: 'Invalid image changes' });
+ }
+ if ('is_intermediate' in changes) {
+ image.is_intermediate = changes.is_intermediate;
+ }
+ if ('image_category' in changes) {
+ image.image_category = changes.image_category;
+ }
+ }
+ return json(200, image);
}
if (method === 'POST' && path === '/api/v1/videos/upload') {
diff --git a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs
index 5b4bfd6bde..d7edf33a15 100644
--- a/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs
+++ b/invokeai/frontend/webv2/scripts/performance-budgets.test.mjs
@@ -1,8 +1,13 @@
import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { join, resolve } from 'node:path';
+import process from 'node:process';
import { describe, it } from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { parse } from 'yaml';
import { createChunkSourceManifest, getModuleSourceOwner } from './chunk-source-manifest.mjs';
import {
@@ -1014,3 +1019,118 @@ describe('the remedy is offered only for budget failures', () => {
assert.ok(!isBudgetFailure('ui has 3 direct importers (budget 1).'));
});
});
+
+describe('exact-base workflow measurements', () => {
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url));
+ const workflow = parse(readFileSync(resolve(packageRoot, '../../../.github/workflows/frontend-tests.yml'), 'utf8'));
+ const measure = workflow.jobs['frontend-webv2-tests'].steps.find(
+ (step) => step.name === 'measure missing performance base'
+ );
+
+ for (const scenario of [
+ 'complete',
+ 'missing-browser',
+ 'malformed-browser',
+ 'incompatible-browser',
+ 'incomplete-build',
+ ]) {
+ it(`accepts failed base checks only with their newly generated valid reference pair (${scenario})`, () => {
+ const root = mkdtempSync(join(tmpdir(), 'invokeai-reference-workflow-'));
+ try {
+ const candidate = resolve(root, 'invokeai/frontend/webv2');
+ const base = resolve(root, '.perf-base/invokeai/frontend/webv2');
+ const binary = resolve(root, 'bin');
+ for (const directory of [candidate, base, binary]) {
+ mkdirSync(directory, { recursive: true });
+ }
+ mkdirSync(resolve(candidate, 'scripts'));
+ copyFileSync(
+ resolve(packageRoot, 'scripts/performance-budgets.mjs'),
+ resolve(candidate, 'scripts/performance-budgets.mjs')
+ );
+ mkdirSync(resolve(base, 'performance'));
+ const buildMeasurement = createSyntheticBuild(1_000);
+ const build = createBuildReference([buildMeasurement]);
+ const browserBaseline = createBrowserBaseline();
+ const browser = createBrowserReference(
+ browserBaseline.routes.map((route) => ({
+ id: route.id,
+ stateProfile: route.stateProfile,
+ resources: route.resourceBaseline,
+ activatedResources: route.activatedResourceBaseline,
+ }))
+ );
+ writeFileSync(
+ resolve(root, 'build.json'),
+ JSON.stringify(scenario === 'incomplete-build' ? { ...build, routes: {} } : build)
+ );
+ writeFileSync(
+ resolve(root, 'browser.json'),
+ scenario === 'malformed-browser'
+ ? '{'
+ : JSON.stringify(scenario === 'incompatible-browser' ? { ...browser, schemaVersion: 999 } : browser)
+ );
+ writeFileSync(
+ resolve(base, 'performance/architecture-baseline.json'),
+ JSON.stringify(createArchitectureBaseline(buildMeasurement))
+ );
+ writeFileSync(resolve(base, 'performance/browser-baseline.json'), JSON.stringify(browserBaseline));
+ // Stale files, including candidate measurements, cannot rescue a failed base measurement.
+ for (const directory of [base, candidate]) {
+ const output = resolve(directory, 'artifacts/architecture-performance');
+ mkdirSync(output, { recursive: true });
+ writeFileSync(resolve(output, 'build-reference.json'), JSON.stringify(build));
+ writeFileSync(resolve(output, 'browser-reference.json'), JSON.stringify(browser));
+ }
+ writeFileSync(resolve(binary, 'pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeFileSync(
+ resolve(binary, 'node'),
+ `#!/bin/sh
+ if [ "$1" = --experimental-strip-types ]; then shift; fi
+ case "$1" in
+ scripts/check-architecture-performance.mjs)
+ echo build >> "$GITHUB_WORKSPACE/calls"
+ cp "$GITHUB_WORKSPACE/build.json" artifacts/architecture-performance/build-reference.json
+ exit 1 ;;
+ scripts/measure-architecture-performance.mjs)
+ echo browser >> "$GITHUB_WORKSPACE/calls"
+ if [ "$REFERENCE_CASE" != missing-browser ]; then
+ cp "$GITHUB_WORKSPACE/browser.json" artifacts/architecture-performance/browser-reference.json
+ fi
+ exit 1 ;;
+ esac
+ exec "${process.execPath}" "$@"
+ `,
+ { mode: 0o755 }
+ );
+ const result = spawnSync('bash', ['-e', '-o', 'pipefail', '-c', measure.run], {
+ cwd: base,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ GITHUB_WORKSPACE: root,
+ PATH: `${binary}:${process.env.PATH}`,
+ REFERENCE_CASE: scenario,
+ },
+ });
+ assert.equal(readFileSync(resolve(root, 'calls'), 'utf8'), 'build\nbrowser\n');
+ assert.equal(result.status, scenario === 'complete' ? 0 : 1, result.stderr);
+ if (scenario === 'complete') {
+ assert.deepEqual(
+ JSON.parse(readFileSync(resolve(candidate, 'artifacts/perf-reference/build-reference.json'), 'utf8')),
+ build
+ );
+ assert.deepEqual(
+ JSON.parse(readFileSync(resolve(candidate, 'artifacts/perf-reference/browser-reference.json'), 'utf8')),
+ browser
+ );
+ } else {
+ assert.equal(existsSync(resolve(candidate, 'artifacts/perf-reference/build-reference.json')), false);
+ assert.equal(existsSync(resolve(candidate, 'artifacts/perf-reference/browser-reference.json')), false);
+ }
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+ }
+});
diff --git a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
index dece4f4a4c..4e4f431a29 100644
--- a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
@@ -39,7 +39,53 @@ describe('architecture workflow', () => {
step.run?.startsWith('pnpm check:')
);
expect(completion.run).toBe('pnpm check:release:tests');
- expect(completion.env.WEBV2_PERF_REFERENCE_DIR).toContain('steps.perf-ref.outputs.cache-matched-key');
+ expect(completion.env.WEBV2_PERF_REFERENCE_DIR).toContain('steps.perf-ref.outcome');
+ expect(completion['continue-on-error']).toBeUndefined();
+ });
+
+ it('measures only a missing exact main base, with isolated credentials, dependencies and runtime', () => {
+ const sources = import.meta.glob('../../../../../.github/workflows/frontend-tests.yml', {
+ eager: true,
+ import: 'default',
+ query: '?raw',
+ }) as Record<string, string>;
+ const workflow = parse(Object.values(sources)[0] ?? '');
+ const steps = workflow.jobs['frontend-webv2-tests'].steps;
+ const restore = steps.find((step: { id?: string }) => step.id === 'perf-ref');
+ expect(restore.if).toContain("github.event_name == 'pull_request' && github.base_ref == 'main'");
+ expect(restore.if).toContain("github.event_name == 'merge_group'");
+ expect(restore.if).toContain("github.event.merge_group.base_ref == 'refs/heads/main'");
+ expect(restore.if).toContain(
+ "steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true"
+ );
+ expect(restore.with.key).toContain('github.event.pull_request.base.sha || github.event.merge_group.base_sha');
+ expect(restore.with['restore-keys']).toBeUndefined();
+ const checkout = steps.find((step: { id?: string }) => step.id === 'perf-base');
+ expect(checkout.if).toContain("steps.perf-ref.outcome == 'success'");
+ expect(checkout.if).toContain("steps.perf-ref.outputs.cache-hit != 'true'");
+ expect(checkout.uses).toBe(steps[0].uses);
+ expect(checkout.with.ref).toMatch(
+ /^\$\{\{ github.event.pull_request.base.sha \|\| github.event.merge_group.base_sha \}\}$/
+ );
+ expect(checkout.with['persist-credentials']).toBe(false);
+ const install = steps.find((step: { name?: string }) => step.name === 'install performance base dependencies');
+ expect(install.uses).toBe('./.github/actions/install-frontend-deps');
+ expect(install.with['working-directory']).toBe(`${checkout.with.path}/invokeai/frontend/webv2`);
+ expect(install.with['node-version-file']).toBe(`${checkout.with.path}/.nvmrc`);
+ const measure = steps.find((step: { name?: string }) => step.name === 'measure missing performance base');
+ expect(measure['working-directory']).toBe(install.with['working-directory']);
+ expect(measure.env.WEBV2_PERF_REFERENCE_DIR).toBe('');
+ expect(measure.run).toContain('node --experimental-strip-types scripts/check-architecture-performance.mjs');
+ const candidateNode = steps.find((step: { name?: string }) => step.name === 'restore candidate Node version');
+ expect(candidateNode.with['node-version-file']).toBe('.nvmrc');
+ expect(steps.indexOf(candidateNode)).toBeGreaterThan(steps.indexOf(measure));
+ expect(steps.indexOf(candidateNode)).toBeLessThan(
+ steps.findIndex((step: { run?: string }) => step.run === 'pnpm check:release:tests')
+ );
+ expect(workflow.permissions).toEqual({ contents: 'read' });
+ for (const event of ['push', 'pull_request', 'merge_group', 'workflow_dispatch', 'workflow_call']) {
+ expect(workflow.on).toHaveProperty(event);
+ }
});
it('runs each completion gate once locally and across the frontend CI jobs', () => {
@@ -139,9 +185,12 @@ describe('architecture workflow', () => {
{ eager: true, import: 'default', query: '?raw' }
) as Record<string, string>;
const action = parse(Object.entries(sources).find(([path]) => path.endsWith('/action.yml'))![1]);
- const nodeVersionFile = action.runs.steps.find((step: { uses?: string }) =>
+ const nodeVersionInput = action.runs.steps.find((step: { uses?: string }) =>
step.uses?.startsWith('actions/setup-node@')
).with['node-version-file'];
+ expect(nodeVersionInput).toMatch(/^\$\{\{ inputs.node-version-file \}\}$/);
+ const nodeVersionFile = action.inputs['node-version-file'].default;
+ expect(nodeVersionFile).toBe('.nvmrc');
const workflows = Object.entries(sources).filter(([path]) => path.includes('/workflows/'));
expect(workflows).toHaveLength(4);
for (const [path, source] of workflows) {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json
index d5a5deb9d7..abcc325e80 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json
@@ -395,7 +395,10 @@
"hash": "blake3:inpaint"
},
"anima_inpaint_adapter_weight": 0.75,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_i2l": {
"is_intermediate": true,
@@ -877,7 +880,83 @@
"hash": "blake3:qwen3"
},
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 0.9,
+ "control_mode": null,
+ "image": {
+ "image_name": "sketch-layer-composite.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "sketch-layer",
+ "model": {
+ "base": "anima",
+ "hash": "blake3:sketch",
+ "key": "sketch",
+ "name": "sketch",
+ "type": "controlnet"
+ },
+ "type": "anima_lllite",
+ "weight": 0.8
+ },
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 0.9,
+ "control_mode": null,
+ "image": {
+ "image_name": "depth-layer-composite.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "depth-layer",
+ "model": {
+ "base": "anima",
+ "hash": "blake3:depth",
+ "key": "depth",
+ "name": "depth",
+ "type": "controlnet"
+ },
+ "type": "anima_lllite",
+ "weight": -1
+ },
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 0.9,
+ "control_mode": null,
+ "image": {
+ "image_name": "pose-layer-composite.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "pose-layer",
+ "model": {
+ "base": "anima",
+ "hash": "blake3:pose",
+ "key": "pose",
+ "name": "pose",
+ "type": "controlnet"
+ },
+ "type": "anima_lllite",
+ "weight": 2
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_i2l": {
"is_intermediate": true,
@@ -1446,7 +1525,35 @@
"hash": "blake3:inpaint"
},
"anima_inpaint_adapter_weight": 0.75,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 0.9,
+ "control_mode": null,
+ "image": {
+ "image_name": "sketch-layer-composite.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "sketch-layer",
+ "model": {
+ "base": "anima",
+ "hash": "blake3:sketch",
+ "key": "sketch",
+ "name": "sketch",
+ "type": "controlnet"
+ },
+ "type": "anima_lllite",
+ "weight": 0.8
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"infill": {
"is_intermediate": true,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/externalCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/externalCanvasGraphs.json
index cae6c5dd4d..8f229623f7 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/externalCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/externalCanvasGraphs.json
@@ -184,7 +184,10 @@
"width": 640,
"openai_quality": "auto",
"openai_background": "auto",
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_processing_output": {
"is_intermediate": true,
@@ -451,7 +454,10 @@
"width": 640,
"openai_quality": "auto",
"openai_background": "auto",
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_resize_image_to_request": {
"is_intermediate": true,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux2ControlCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux2ControlCanvasGraphs.json
index 5398238022..b94ff395cb 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux2ControlCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux2ControlCanvasGraphs.json
@@ -319,7 +319,35 @@
"type": "core_metadata",
"width": 768,
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "f-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "f-control",
+ "model": {
+ "base": "flux2",
+ "key": "flux2-union",
+ "name": "FLUX.2 [dev] ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "flux2_control",
+ "weight": 0.75
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_i2l": {
"is_intermediate": true,
@@ -772,7 +800,35 @@
"type": "core_metadata",
"width": 768,
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "f-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "f-control",
+ "model": {
+ "base": "flux2",
+ "key": "flux2-union",
+ "name": "FLUX.2 [dev] ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "flux2_control",
+ "weight": 0.75
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"infill": {
"is_intermediate": true,
@@ -1115,7 +1171,35 @@
"steps": 28,
"type": "core_metadata",
"width": 768,
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "f-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "f-control",
+ "model": {
+ "base": "flux2",
+ "key": "flux2-union",
+ "name": "FLUX.2 [dev] ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "flux2_control",
+ "weight": 0.75
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"flux2_control_f-control": {
"is_intermediate": true,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux3LayoutCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux3LayoutCanvasGraphs.json
index ba412f10ca..02e5f14497 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux3LayoutCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/flux3LayoutCanvasGraphs.json
@@ -306,6 +306,29 @@
"id": "beach",
"isEnabled": true
}
+ ],
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 63,
+ 250,
+ 313,
+ 750
+ ],
+ "desc": "a red kite reading \"Éole\""
+ },
+ {
+ "bbox": [
+ 625,
+ 667,
+ 1000,
+ 1000
+ ],
+ "desc": "a dog digging in the sand"
+ }
]
}
}
@@ -627,7 +650,30 @@
"type": "core_metadata",
"width": 768,
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 63,
+ 250,
+ 313,
+ 750
+ ],
+ "desc": "a red kite reading \"Éole\""
+ },
+ {
+ "bbox": [
+ 625,
+ 667,
+ 1000,
+ 1000
+ ],
+ "desc": "a dog digging in the sand"
+ }
+ ]
},
"canvas_i2l": {
"is_intermediate": true,
@@ -930,7 +976,30 @@
"steps": 16,
"type": "core_metadata",
"width": 768,
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 63,
+ 250,
+ 313,
+ 750
+ ],
+ "desc": "a red kite reading \"Éole\""
+ },
+ {
+ "bbox": [
+ 625,
+ 667,
+ 1000,
+ 1000
+ ],
+ "desc": "a dog digging in the sand"
+ }
+ ]
}
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
index d0dd15fceb..ecd5b0e5f6 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
@@ -675,6 +675,8 @@
"clip_skip": [
0
],
+ "control_layers": [],
+ "controlnets": [],
"dype_exponent": [
1
],
@@ -735,9 +737,18 @@
true
],
"ideogram4_color_palette": [],
+ "ideogram4_guidance_scale": [
+ null
+ ],
+ "ideogram4_mu": [
+ null
+ ],
"ideogram4_sampler_preset": [
"V4_QUALITY_48"
],
+ "ideogram4_steps": [
+ null
+ ],
"ideogram4_unconditional_model": [],
"is_intermediate": [
true
@@ -832,12 +843,16 @@
"strength": [
0.6
],
+ "t2iAdapters": [],
"t5_encoder": [],
"use_cache": [
true
],
"vae": [],
"wan_component_source": [],
+ "wan_guidance_scale_low_noise": [
+ null
+ ],
"wan_t5_encoder_model": [],
"width": [
1024,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json
index a47a8e528e..821448e957 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json
@@ -239,8 +239,34 @@
"type": "core_metadata",
"width": 768,
"ideogram4_color_palette": [],
+ "ideogram4_guidance_scale": null,
+ "ideogram4_mu": null,
"ideogram4_sampler_preset": "V4_QUALITY_48",
- "clip_skip": 0
+ "ideogram4_steps": null,
+ "clip_skip": 0,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 63,
+ 250,
+ 313,
+ 750
+ ],
+ "prompt": "a red kite"
+ },
+ {
+ "bbox": [
+ 625,
+ 667,
+ 1000,
+ 1000
+ ],
+ "prompt": "a dog digging in the sand"
+ }
+ ]
}
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
index 16a681e9dc..f08e488a7c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
@@ -372,7 +372,43 @@
22
],
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 0,
+ 0,
+ 512,
+ 256
+ ],
+ "caption": "a hand-lettered cafe sign",
+ "kind": "text",
+ "text": "一杯温暖\n一刻从容"
+ },
+ {
+ "bbox": [
+ 64,
+ 128,
+ 256,
+ 384
+ ],
+ "caption": "a barista pouring latte art",
+ "kind": "character"
+ },
+ {
+ "bbox": [
+ 512,
+ 640,
+ 768,
+ 1024
+ ],
+ "caption": "a steaming ceramic cup",
+ "kind": "object"
+ }
+ ]
},
"canvas_i2l": {
"is_intermediate": true,
@@ -730,7 +766,43 @@
"moss_image_uncond_skip_layers": [
22
],
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [],
+ "controlnets": [],
+ "t2iAdapters": [],
+ "regions": [
+ {
+ "bbox": [
+ 0,
+ 0,
+ 512,
+ 256
+ ],
+ "caption": "a hand-lettered cafe sign",
+ "kind": "text",
+ "text": "一杯温暖\n一刻从容"
+ },
+ {
+ "bbox": [
+ 64,
+ 128,
+ 256,
+ 384
+ ],
+ "caption": "a barista pouring latte art",
+ "kind": "character"
+ },
+ {
+ "bbox": [
+ 512,
+ 640,
+ 768,
+ 1024
+ ],
+ "caption": "a steaming ceramic cup",
+ "kind": "object"
+ }
+ ]
}
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/qwenImageControlCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/qwenImageControlCanvasGraphs.json
index 25de26524e..b06bfad271 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/qwenImageControlCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/qwenImageControlCanvasGraphs.json
@@ -326,7 +326,35 @@
"qwen_image_quantization": "none",
"qwen_image_shift": "auto",
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "q-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "q-control",
+ "model": {
+ "base": "qwen-image",
+ "key": "qwen-union",
+ "name": "Qwen Image ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "qwen_image_control",
+ "weight": 0.85
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_i2l": {
"is_intermediate": true,
@@ -726,7 +754,35 @@
"qwen_image_quantization": "none",
"qwen_image_shift": "auto",
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "q-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "q-control",
+ "model": {
+ "base": "qwen-image",
+ "key": "qwen-instantx",
+ "name": "Qwen Image InstantX ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:instantx"
+ },
+ "type": "qwen_image_control",
+ "weight": 0.85
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"canvas_i2l": {
"is_intermediate": true,
@@ -1172,7 +1228,35 @@
"qwen_image_quantization": "none",
"qwen_image_shift": "auto",
"clip_skip": 0,
- "strength": 0.6
+ "strength": 0.6,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "q-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "q-control",
+ "model": {
+ "base": "qwen-image",
+ "key": "qwen-union",
+ "name": "Qwen Image ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "qwen_image_control",
+ "weight": 0.85
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"infill": {
"is_intermediate": true,
@@ -1520,7 +1604,35 @@
"width": 768,
"qwen_image_quantization": "none",
"qwen_image_shift": "auto",
- "clip_skip": 0
+ "clip_skip": 0,
+ "control_layers": [
+ {
+ "begin_step_percent": 0,
+ "end_step_percent": 1,
+ "control_mode": null,
+ "image": {
+ "image_name": "q-control.png",
+ "width": 768,
+ "height": 1024
+ },
+ "position": {
+ "x": 128,
+ "y": 64
+ },
+ "layer_id": "q-control",
+ "model": {
+ "base": "qwen-image",
+ "key": "qwen-union",
+ "name": "Qwen Image ControlNet Union",
+ "type": "controlnet",
+ "hash": "blake3:union"
+ },
+ "type": "qwen_image_control",
+ "weight": 0.85
+ }
+ ],
+ "controlnets": [],
+ "t2iAdapters": []
},
"qwen_image_control_q-control": {
"is_intermediate": true,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
index f7a8056529..2782d12212 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
@@ -379,6 +379,61 @@ const setCanvasMetadataDimensions = (graph: BackendGraphContract, bbox: CompileC
}
};
+/** Record only the resolved inputs handed to the graph, beside the independently versioned authored document. */
+const recordCanvasInputs = (graph: BackendGraphContract, input: CompileCanvasGraphInput): void => {
+ const metadata = findMetadataNode(graph);
+ if (!metadata) {
+ return;
+ }
+ if (input.canvasMetadata) {
+ metadata.canvas_v3_metadata = input.canvasMetadata;
+ }
+ const controls = input.controlLayers ?? [];
+ const recordedControls = controls.map((control) => ({
+ begin_step_percent: control.beginEndStepPct[0],
+ end_step_percent: control.beginEndStepPct[1],
+ control_mode: control.controlMode,
+ image: { image_name: control.imageName, width: input.bbox.width, height: input.bbox.height },
+ position: { x: input.bbox.x, y: input.bbox.y },
+ layer_id: control.id,
+ model: control.model,
+ type: control.kind,
+ weight: control.weight,
+ ...(control.instantxControlMode === null || control.instantxControlMode === undefined
+ ? {}
+ : { instantx_control_mode: control.instantxControlMode }),
+ }));
+ metadata.control_layers = recordedControls;
+ metadata.controlnets = recordedControls
+ .filter((control) => control.type === 'controlnet')
+ .map((control) => ({
+ image: control.image,
+ control_model: control.model,
+ control_weight: control.weight,
+ begin_step_percent: control.begin_step_percent,
+ end_step_percent: control.end_step_percent,
+ control_mode: control.control_mode ?? 'balanced',
+ }));
+ metadata.t2iAdapters = recordedControls
+ .filter((control) => control.type === 't2i_adapter')
+ .map((control) => ({
+ image: control.image,
+ t2i_adapter_model: control.model,
+ weight: control.weight,
+ begin_step_percent: control.begin_step_percent,
+ end_step_percent: control.end_step_percent,
+ }));
+ const layoutRegions = graph.nodes.layout_prompt?.regions ?? graph.nodes.caption_builder?.regions;
+ if (Array.isArray(layoutRegions) && layoutRegions.length > 0) {
+ metadata.regions = layoutRegions;
+ } else if (!['moss-image', 'ideogram-4', 'flux3'].includes(input.model.base)) {
+ const regions = (input.regionalGuidance ?? []).filter((region) => graph.nodes[`rg_mask_to_tensor_${region.id}`]);
+ if (regions.length) {
+ metadata.regions = regions.map(({ layout: _layout, ...region }) => region);
+ }
+ }
+};
+
/** Sets the metadata `generation_mode` variant + strength (legacy parity). */
const setMetadataMode = (graph: BackendGraphContract, mode: string, strength: number): void => {
const metadata = findMetadataNode(graph);
@@ -1082,6 +1137,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
}
restoreExternalCanvasOutputToBbox(backendGraph, { bbox, destination, mode }, processingSize);
setCanvasMetadataDimensions(backendGraph, bbox);
+ recordCanvasInputs(backendGraph, input);
return {
backendGraph,
@@ -1169,6 +1225,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
// After every mode has settled its final image node, so the filters see the composited/resized result.
addOutputPostprocessors(backendGraph, runtimeProjectSettings, outputIsIntermediate);
setCanvasMetadataDimensions(backendGraph, bbox);
+ recordCanvasInputs(backendGraph, input);
return {
backendGraph,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts
index dff9009d49..6969624d8c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/types.ts
@@ -77,6 +77,8 @@ export interface CompileCanvasGraphInput {
compositing: CanvasCompositingSettings;
/** Processing-size policy; absent means the bbox snapped to the model grid. */
scaling?: CanvasScalingSettings;
+ /** Opaque Workbench-owned authored canvas record, captured with the composites. */
+ canvasMetadata?: Record<string, unknown>;
/** Prevalidated per-layer composites, each uploaded separately. */
controlLayers?: readonly ControlLayerGraphInput[];
/** Resolved inputs for each supported region. */
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index 1c2810612e..e4eef2d17a 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -1860,10 +1860,10 @@ const buildIdeogram4Graph = (
addEdge(graph, denoise, 'latents', output, 'latents');
const metadata = addMetadata(graph, output, settings, model, 'ideogram4_txt2img', projectSettings, {
ideogram4_color_palette: settings.ideogram4ColorPalette,
- ideogram4_guidance_scale: settings.ideogram4GuidanceScale ?? undefined,
- ideogram4_mu: settings.ideogram4Mu ?? undefined,
+ ideogram4_guidance_scale: settings.ideogram4GuidanceScale ?? null,
+ ideogram4_mu: settings.ideogram4Mu ?? null,
ideogram4_sampler_preset: settings.ideogram4SamplerPreset,
- ideogram4_steps: settings.ideogram4Steps ?? undefined,
+ ideogram4_steps: settings.ideogram4Steps ?? null,
// Record both transformer files in provenance.
ideogram4_unconditional_model: isDiffusers ? undefined : (unconditionalModel ?? undefined),
qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,
@@ -1937,7 +1937,7 @@ const buildWanGraph = (
addMetadata(graph, output, settings, model, 'wan_txt2img', projectSettings, {
vae: vaeModel ?? undefined,
wan_component_source: sourceModel,
- wan_guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? undefined,
+ wan_guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? null,
wan_t5_encoder_model: wanT5EncoderModel ?? undefined,
wan_transformer_low_noise: settings.wanLowNoiseModel ?? undefined,
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
index 5b8930a415..e2ae6fcda5 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts
@@ -352,7 +352,7 @@ export const isValidMossImageSkipLayers = (layers: readonly number[]): boolean =
export const normalizeMossImageSkipLayers = (value: unknown): number[] | null =>
Array.isArray(value) && value.every((entry) => Number.isInteger(entry)) ? toUniqueAscending(value) : null;
-const isIdeogram4SamplerPreset = (value: unknown): value is Ideogram4SamplerPreset =>
+export const isIdeogram4SamplerPreset = (value: unknown): value is Ideogram4SamplerPreset =>
IDEOGRAM4_SAMPLER_PRESETS.includes(value as Ideogram4SamplerPreset);
export const isFluxDypePreset = (value: unknown): value is FluxDypePreset =>
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 85d867d07c..4ba8163308 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -18,6 +18,7 @@ export {
hasModelDefaultVae,
isAspectRatioLocked,
isFluxDypePreset,
+ isIdeogram4SamplerPreset,
isGenerateModelConfig,
isLoraCompatibleWithModel,
isLoraModelConfig,
diff --git a/invokeai/frontend/webv2/src/platform/i18n/client.test.ts b/invokeai/frontend/webv2/src/platform/i18n/client.test.ts
new file mode 100644
index 0000000000..edbd37a66c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/i18n/client.test.ts
@@ -0,0 +1,59 @@
+import type * as I18nextModule from 'i18next';
+
+import { afterEach, expect, it, vi } from 'vitest';
+
+vi.mock('i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof I18nextModule>();
+ return { ...actual, default: actual.createInstance() };
+});
+vi.mock('@platform/transport/deploymentBase', () => ({
+ getDeploymentBaseUrl: () => 'https://invoke.example/studio',
+}));
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+it('loads cold namespaces only on demand under the deployment prefix with English and root fallbacks', async () => {
+ const resources: Record<string, unknown> = {
+ 'en.json': { common: { copy: 'Copy' } },
+ 'fr.json': { common: { copy: 'Copier' } },
+ 'en.metadata.json': { widgets: { preview: { metadataLabels: { control_layers: 'Control layers' } } } },
+ 'fr.metadata.json': {},
+ 'en.fonts.json': { fonts: { title: 'Fonts' } },
+ 'fr.fonts.json': {},
+ };
+ const request = vi.fn((input: RequestInfo | URL) => {
+ const url = new URL(String(input));
+ expect(url.origin).toBe('https://invoke.example');
+ expect(url.pathname).toMatch(/^\/studio\/locales\//u);
+ expect(url.searchParams.get('v')).toMatch(/^[a-f\d]{12}$/u);
+ const value = resources[url.pathname.split('/').at(-1)!];
+ return Promise.resolve(new Response(JSON.stringify(value), { status: value ? 200 : 404 }));
+ });
+ vi.stubGlobal('fetch', request);
+
+ const { default: i18n } = await import('./client');
+ await vi.waitFor(() => expect(i18n.isInitialized).toBe(true));
+ await i18n.changeLanguage('fr');
+ expect(request.mock.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([
+ '/studio/locales/en.json',
+ '/studio/locales/fr.json',
+ ]);
+
+ await i18n.loadNamespaces('metadata');
+ const t = i18n.getFixedT('fr', 'metadata');
+ expect(t('widgets.preview.metadataLabels.control_layers')).toBe('Control layers');
+ expect(t('common.copy')).toBe('Copier');
+ expect(request.mock.calls.slice(2).map(([url]) => new URL(String(url)).pathname)).toEqual([
+ '/studio/locales/fr.metadata.json',
+ '/studio/locales/en.metadata.json',
+ ]);
+
+ await i18n.loadNamespaces('fonts');
+ expect(i18n.getFixedT('fr', 'fonts')('fonts.title')).toBe('Fonts');
+ expect(request.mock.calls.slice(-2).map(([url]) => new URL(String(url)).pathname)).toEqual([
+ '/studio/locales/fr.fonts.json',
+ '/studio/locales/en.fonts.json',
+ ]);
+});
diff --git a/invokeai/frontend/webv2/src/platform/i18n/client.ts b/invokeai/frontend/webv2/src/platform/i18n/client.ts
index 105c0f0b0b..66646abc60 100644
--- a/invokeai/frontend/webv2/src/platform/i18n/client.ts
+++ b/invokeai/frontend/webv2/src/platform/i18n/client.ts
@@ -9,7 +9,9 @@ void i18n
.init({
backend: {
loadPath: (_languages: readonly string[], namespaces: readonly string[]) =>
- `${getDeploymentBaseUrl()}/locales/{{lng}}${namespaces[0] === 'fonts' ? '.fonts' : ''}.json`,
+ `${getDeploymentBaseUrl()}/locales/{{lng}}${
+ namespaces[0] === 'fonts' || namespaces[0] === 'metadata' ? `.${namespaces[0]}` : ''
+ }.json`,
// Changes with locale content, so a release never reads the previous one's cached translations; the service
// worker caches only these versioned URLs.
queryStringParams: { v: import.meta.env.LOCALE_VERSION },
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index bf49523af3..fd39ea8ddd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -218,6 +218,10 @@ Undo removes accepted layer and restores prior selection. Redo restores identica
`canvas.snapshots` are restore points, at most `MAX_CANVAS_SNAPSHOTS` (five) per kind and project, newest kept, so Discard all points never push a `clear-canvas` point out. Every document swap they drive (`widgets/canvas/canvasRestorePoints.ts`) crosses the paint barrier first and changes nothing when the flush fails: Clear canvas keeps a `clear-canvas` point of the document and its staged candidates (none for a blank canvas: no layer but empty masks, no candidates), then replaces the document and withdraws the point when `replaceDocument` refuses. Restoring a canvas point, from the History pane or a toast's Undo, waits while `documentEditingLocked` holds the document or the session has pending results (`hasPendingCanvasResults`: a staged candidate, or a generation queued or running for this revision; a swap would drop them) and says so. `document.restoreSnapshot` is the one restore path, a document swap like `replaceDocument`: `restoreCanvasSnapshot` bumps `documentRevision`, clears staging (restoring the point's candidates when it kept any) and so drops in-flight results of the replaced session, and engine history clears with the swap. `keepCurrentAs` saves the replaced canvas as a point in the restored one's place, so a restore is undoable without pushing an older point out; a blank replaced canvas is not kept and the restored point is deleted instead. The Undo of a Clear canvas or a restore runs only while the canvas is as that swap left it (`isCanvasEditedSince`: same `documentRevision`, size, background and layer stacks; selection and bbox do not count): it may run minutes later from the Notifications list. It looks before and again after the paint barrier, whose saved strokes land in the document only then, and after a later edit it says the canvas was not restored and leaves the point in History. Discard all keeps a `discard-results` point of the candidates only, its document an empty one of the canvas's size; restoring it neither waits nor flushes, re-stages the candidates on the current canvas through `restoreStagedImages`, leaves the document alone and is used up once one of them is back (when all already are, the point stays and nothing changes). A staging Undo re-stages through `restoreStagedImages` fenced by the discard's `documentRevision`; after a swap moved it, Discard all's Undo falls back to its point and the others say they could not bring the results back.
+### Metadata recall
+
+Image and queue recall enter through `canvas-operations/importGalleryImages.ts`, the same structural ingestion owner as Gallery imports. The image-action parser validates records and resolves assets before commit; the import owner checks the captured project/document, rejects an editing lock and preserves a replaced canvas as a restore point. A partial or appended recall uses a structural history transaction when an engine is live. A canvas with staged or running results merges recalled layers, preserving that session and its pinned placements. A paint-persistence barrier runs before the final identity check. Metadata records and legacy raster conversion are application workflows, outside the engine; their wire format and recovery semantics are documented in `src/workbench/projects/README.md`.
+
## Control derivation
A typed control layer can keep the pixels it was detected from (`original`, framed by `originalTransform`) beside the derived map in `source`. The invariants are documented on `CanvasControlLayerContract`; `document/controlDerivation.ts` owns them as pure rules, and every engine path that changes a control layer's pixels or frame applies one of them so no edit leaves a map paired with an original it no longer derives from:
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
index 6c636433c9..eb4a6c5bbe 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts
@@ -12,6 +12,8 @@ export type {
} from './contracts';
export {
importGalleryImagesToCanvas,
+ commitCanvasRecall,
+ prepareLegacyCanvasMetadata,
type GalleryCanvasImportDestination,
type ImportGalleryImagesResult,
} from './importGalleryImages';
@@ -60,7 +62,12 @@ export type {
export { getCanvasOperations } from './operationAccess';
export { IDLE_CONTROL_DETECTION_STATUS } from './controlDetectionStatusStore';
export { getCanvasEngine, isBlankCanvasDocument } from './engineRegistry';
-export { resolveCanvasSaveBoardId, saveCanvasToGallery, type CanvasGallerySaveRegion } from './saveCanvasToGallery';
+export {
+ recordCanvasMetadata,
+ resolveCanvasSaveBoardId,
+ saveCanvasToGallery,
+ type CanvasGallerySaveRegion,
+} from './saveCanvasToGallery';
export {
retryStagedResultBoard,
saveStagedResultToGallery,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts
index e126481018..6b8ee751dc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts
@@ -30,8 +30,9 @@ const BBOX = { height: 512, width: 768, x: 31, y: 47 };
const engineWith = (composite: unknown) => {
const intents: ControlLayerIntent[] = [];
+ const document = { ...documentFrom([]), bbox: BBOX };
const engine = {
- document: { getDocument: () => ({ bbox: BBOX }) },
+ document: { getDocument: () => document },
exports: { exportRasterComposite: () => composite },
lifecycle: { flushPendingUploads: () => Promise.resolve() },
projectId: 'project-1',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
index cc926ef42c..0ef82bdec3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
@@ -164,7 +164,13 @@ describe('createFromBbox', () => {
const result = await harness.run('raster');
- expect(harness.order).toEqual(['flush', 'document', 'export', 'upload', 'resolve', 'commit']);
+ expect(harness.order.filter((event) => event !== 'document')).toEqual([
+ 'flush',
+ 'export',
+ 'upload',
+ 'resolve',
+ 'commit',
+ ]);
expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'rect', rect: bbox });
expect(harness.uploadImage).toHaveBeenCalledWith(defaultBlob, {
fileName: 'bbox.png',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts
index 023d15bbae..03e2a4da26 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.test.ts
@@ -3,6 +3,7 @@ import type { CanvasEngine } from '@workbench/canvas-engine/engine';
import type { RasterCompositeExportResult } from '@workbench/canvas-engine/exportRasterComposite';
import type { Rect } from '@workbench/canvas-engine/types';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
import { describe, expect, it, vi } from 'vitest';
import { exportCanvasComposite } from './exportCanvasComposite';
@@ -10,7 +11,7 @@ import { exportCanvasComposite } from './exportCanvasComposite';
const defaultRect: Rect = { height: 456, width: 123, x: -4, y: 8 };
const defaultBlob = new Blob(['pixels'], { type: 'image/png' });
-const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ bbox }) as unknown as CanvasDocumentContractV3;
+const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ ...createEmptyCanvasDocument(), bbox });
const createHarness = (
options: {
@@ -56,12 +57,13 @@ describe('exportCanvasComposite', () => {
const harness = createHarness();
await expect(exportCanvasComposite(harness.engine, 'canvas')).resolves.toEqual({
+ document: createDocument(defaultRect),
blob: defaultBlob,
rect: defaultRect,
status: 'ok',
});
- expect(harness.order).toEqual(['flush', 'document', 'export']);
+ expect(harness.order).toEqual(['flush', 'document', 'export', 'document']);
expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'content' });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
index 1b3869b1c0..c30d7172d0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/exportCanvasComposite.ts
@@ -2,6 +2,7 @@ import type {
AdjustmentRefusal,
LayerUnreadable,
CanvasDocumentCapability,
+ CanvasDocumentContractV3,
CanvasExportCapability,
CanvasLifecycleCapability,
} from '@workbench/canvas-engine/api';
@@ -10,7 +11,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
export type CanvasCompositeRegion = 'canvas' | 'bbox';
export type ExportCanvasCompositeResult =
- | { status: 'ok'; blob: Blob; rect: Rect }
+ | { status: 'ok'; blob: Blob; rect: Rect; document: CanvasDocumentContractV3 }
| { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }
| LayerUnreadable
| AdjustmentRefusal;
@@ -35,7 +36,14 @@ export const exportCanvasComposite = async (
return { status: 'not-ready' };
}
- return engine.exports.exportRasterComposite(
+ const result = await engine.exports.exportRasterComposite(
region === 'canvas' ? { bounds: 'content' } : { bounds: 'rect', rect: document.bbox }
);
+ if (result.status !== 'ok') {
+ return result;
+ }
+ if (engine.document.getDocument() !== document) {
+ return { status: 'stale' };
+ }
+ return { ...result, document };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
index 2978d1a707..7ab8db3a9c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -1,7 +1,16 @@
import type { GalleryImage } from '@features/gallery';
-import type { CanvasDocumentCapability, CanvasLayerCapability, LayerStackKind } from '@workbench/canvas-engine/api';
+import type {
+ CanvasDocumentContractV3,
+ CanvasNodeContract,
+ CanvasNodeInsertion,
+ CanvasLayerStackKind,
+ CanvasDocumentCapability,
+ CanvasLayerCapability,
+ LayerStackKind,
+} from '@workbench/canvas-engine/api';
import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { CanvasRecallPlan, CanvasRecallTarget } from '@workbench/image-actions/canvasRecall';
import type { Project } from '@workbench/projectContracts';
import { galleryImageUrls } from '@features/gallery/utility';
@@ -12,11 +21,13 @@ import {
isArchitectureDescribed,
normalizeGenerateWidgetValues,
} from '@features/generation/settings';
+import { createItemId } from '@platform/browser/randomUuid';
import { mapWithConcurrency } from '@platform/core/concurrency';
import {
assertAccountScopeCurrent,
captureAccountScope,
registerAccountOwnedResource,
+ type AccountScope,
} from '@platform/state/accountLifecycle';
import {
captureInsertionAnchor,
@@ -24,6 +35,7 @@ import {
getDocumentLeaves,
nextControlLayerName,
} from '@workbench/canvas-engine/api';
+import { hasPendingCanvasResults } from '@workbench/canvasStagingView';
import {
createEmptyPaintLayer,
createInpaintMaskFromImage,
@@ -40,6 +52,14 @@ import { getProjectWidgetValues } from '@workbench/widgetState';
import { nextLayerName } from '@workbench/workbenchState';
import { uploadCanvasImage } from './backend/canvasImages';
+import { getCanvasEngine } from './engineRegistry';
+
+/** Keep the legacy raster renderer out of Canvas startup and current-record recall. */
+export const prepareLegacyCanvasMetadata = async (
+ metadata: Record<string, unknown>,
+ owner: AccountScope,
+ isCurrent?: () => boolean
+) => (await import('./legacyCanvasMetadata')).convertLegacyCanvasMetadata(metadata, owner, isCurrent);
export type GalleryCanvasImportDestination =
| 'raster'
@@ -344,3 +364,122 @@ export const importGalleryImagesToCanvas = async (options: {
activeImports.delete(importKey);
}
};
+
+/** Commit synchronously only to the captured project/document. Preserve replaced work in the existing restore-point UI. */
+export const commitCanvasRecall = ({
+ plan,
+ target,
+ expectedDocument,
+ append = false,
+ restorePointName,
+}: {
+ plan: CanvasRecallPlan;
+ target: CanvasRecallTarget;
+ expectedDocument: CanvasDocumentContractV3;
+ append?: boolean;
+ restorePointName: string;
+}): boolean => {
+ const project = target.getProject();
+ if (!project || project.id !== target.projectId || project.canvas.document !== expectedDocument) {
+ plan.problems.push('canvas-changed');
+ return false;
+ }
+ const engine = getCanvasEngine(target.projectId);
+ if (engine?.interaction.get('documentEditingLocked')) {
+ plan.problems.push('canvas-busy');
+ return false;
+ }
+ let applied = false;
+ if (plan.document) {
+ const document = structuredClone(plan.document);
+ if (plan.fitControlsToFrame) {
+ const frame = project.canvas.document.bbox;
+ for (const control of document.stacks.control) {
+ if (control.type === 'control' && control.source.type === 'image') {
+ control.transform = {
+ x: frame.x,
+ y: frame.y,
+ rotation: 0,
+ scaleX: frame.width / control.source.image.width,
+ scaleY: frame.height / control.source.image.height,
+ };
+ }
+ }
+ }
+ // Fresh ids avoid collisions in partial/append recalls and old engine caches on wholesale replacement.
+ const remappedIds = new Map<string, string>();
+ const remap = (nodes: CanvasNodeContract[]): void => {
+ for (const node of nodes) {
+ const newId = createItemId('recalled-layer');
+ remappedIds.set(node.id, newId);
+ node.id = newId;
+ if (node.type === 'group') {
+ remap(node.children);
+ }
+ }
+ };
+ Object.values(document.stacks).forEach(remap);
+ document.selectedLayerId = remappedIds.get(document.selectedLayerId ?? '') ?? null;
+ if (hasPendingCanvasResults(project.canvas, project.queue.items)) {
+ plan.partial = true;
+ plan.problems.push('canvas-pending-results');
+ }
+ if (plan.controlsOnly && !append && !plan.partial) {
+ document.stacks = { ...project.canvas.document.stacks, control: document.stacks.control };
+ document.width = project.canvas.document.width;
+ document.height = project.canvas.document.height;
+ document.bbox = project.canvas.document.bbox;
+ document.background = project.canvas.document.background;
+ document.selectedLayerId = project.canvas.document.selectedLayerId;
+ }
+ if (append || plan.partial) {
+ const add: CanvasNodeInsertion[] = Object.entries(document.stacks).map(([stack, nodes]) => ({
+ nodes,
+ anchor: {
+ projectId: target.projectId,
+ stack: stack as CanvasLayerStackKind,
+ parentPath: [],
+ beforeId: null,
+ afterId: null,
+ capturedEditRevision: engine?.document.getEditRevision() ?? 0,
+ },
+ }));
+ const forward: CanvasProjectMutation = { type: 'applyCanvasLayerStackMutation', add, enabledUpdates: [] };
+ const inverse: CanvasProjectMutation = {
+ type: 'applyCanvasLayerStackMutation',
+ removeIds: add.flatMap((insertion) => insertion.nodes.map((node) => node.id)),
+ enabledUpdates: [],
+ selectedLayerId: expectedDocument.selectedLayerId,
+ };
+ const hasAdditions = add.some((insertion) => insertion.nodes.length > 0);
+ applied =
+ hasAdditions &&
+ (engine
+ ? engine.layers.commitStructural(restorePointName, forward, inverse).status === 'committed'
+ : target.commands.canvas.apply(target.projectId, forward));
+ if (hasAdditions && !applied) {
+ plan.problems.push('canvas-limit');
+ }
+ } else {
+ const snapshotId = createItemId('canvas-recall');
+ target.commands.canvas.apply(target.projectId, {
+ type: 'saveCanvasSnapshot',
+ id: snapshotId,
+ name: restorePointName,
+ createdAt: new Date().toISOString(),
+ });
+ applied = engine
+ ? engine.document.replaceDocument(document)
+ : target.commands.canvas.apply(target.projectId, { type: 'replaceCanvasDocument', document });
+ if (!applied) {
+ target.commands.canvas.apply(target.projectId, { type: 'deleteCanvasSnapshot', snapshotId });
+ plan.problems.push('canvas-busy');
+ }
+ }
+ }
+ if (Object.keys(plan.settings).length > 0) {
+ target.commands.widgets.patchValues('canvas', plan.settings, target.projectId);
+ applied = true;
+ }
+ return applied;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasAdjustments.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasAdjustments.ts
new file mode 100644
index 0000000000..2fa7504b3f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasAdjustments.ts
@@ -0,0 +1,102 @@
+import { z } from 'zod';
+
+const unit = z.number().finite().min(-1).max(1);
+const simple = z.object({
+ brightness: unit,
+ contrast: unit,
+ saturation: unit,
+ temperature: unit,
+ tint: unit,
+ sharpness: unit,
+});
+const curve = z
+ .array(z.tuple([z.number().min(0).max(255), z.number().min(0).max(255)]))
+ .min(2)
+ .max(256);
+const curves = z.object({ master: curve, r: curve, g: curve, b: curve });
+const adjustments = z.object({
+ version: z.literal(1),
+ enabled: z.boolean(),
+ mode: z.enum(['simple', 'curves']),
+ simple,
+ curves,
+});
+const clamp = (value: number): number => Math.max(0, Math.min(255, value));
+
+const curveLut = (points: [number, number][]): number[] => {
+ const sorted = points.map(([x, y]): [number, number] => [Math.round(x), Math.round(y)]).sort((a, b) => a[0] - b[0]);
+ if (sorted[0]![0] !== 0) {
+ sorted.unshift([0, sorted[0]![1]]);
+ }
+ if (sorted.at(-1)![0] !== 255) {
+ sorted.push([255, sorted.at(-1)![1]]);
+ }
+ let segment = 0;
+ return Array.from({ length: 256 }, (_, x) => {
+ while (segment < sorted.length - 2 && x > sorted[segment + 1]![0]) {
+ segment++;
+ }
+ const [x0, y0] = sorted[segment]!,
+ [x1, y1] = sorted[segment + 1]!;
+ return clamp(Math.round(y0 + (y1 - y0) * (x1 === x0 ? 0 : (x - x0) / (x1 - x0))));
+ });
+};
+
+/** Match the legacy committed-layer filter, baking it once into its recalled paint bitmap. */
+export const applyLegacyCanvasAdjustments = (pixels: ImageData, raw: unknown): void => {
+ if (raw === undefined) {
+ return;
+ }
+ const config = adjustments.parse(raw);
+ if (!config.enabled) {
+ return;
+ }
+ const { data, width, height } = pixels;
+ if (config.mode === 'curves') {
+ const luts = {
+ master: curveLut(config.curves.master),
+ r: curveLut(config.curves.r),
+ g: curveLut(config.curves.g),
+ b: curveLut(config.curves.b),
+ };
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = luts.r[luts.master[data[i]!]!]!;
+ data[i + 1] = luts.g[luts.master[data[i + 1]!]!]!;
+ data[i + 2] = luts.b[luts.master[data[i + 2]!]!]!;
+ }
+ return;
+ }
+ const { brightness, contrast, saturation, temperature, tint, sharpness } = config.simple;
+ const tintScale = tint * 0.5,
+ sat = 1 + saturation;
+ for (let i = 0; i < data.length; i += 4) {
+ const r = ((data[i]! + brightness * 255 - 128) * (1 + contrast) + 128) * (1 + temperature * 0.5) * (1 + tintScale);
+ const g = ((data[i + 1]! + brightness * 255 - 128) * (1 + contrast) + 128) * (1 - tintScale);
+ const b =
+ ((data[i + 2]! + brightness * 255 - 128) * (1 + contrast) + 128) * (1 - temperature * 0.5) * (1 + tintScale);
+ const luma = r * 0.2126 + g * 0.7152 + b * 0.0722;
+ data[i] = clamp(luma * (1 - sat) + r * sat);
+ data[i + 1] = clamp(luma * (1 - sat) + g * sat);
+ data[i + 2] = clamp(luma * (1 - sat) + b * sat);
+ }
+ if (Math.abs(sharpness) <= 0.001 || width <= 2 || height <= 2) {
+ return;
+ }
+ const source = new Uint8ClampedArray(data),
+ amount = sharpness * 0.5;
+ for (let y = 1; y < height - 1; y++) {
+ for (let x = 1; x < width - 1; x++) {
+ const index = (y * width + x) * 4;
+ for (let channel = 0; channel < 3; channel++) {
+ data[index + channel] = clamp(
+ source[index + channel]! * (1 + 4 * amount) -
+ amount *
+ (source[index - 4 + channel]! +
+ source[index + 4 + channel]! +
+ source[index - width * 4 + channel]! +
+ source[index + width * 4 + channel]!)
+ );
+ }
+ }
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.browser.test.ts
new file mode 100644
index 0000000000..66ab2eb83b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.browser.test.ts
@@ -0,0 +1,480 @@
+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const uploads = vi.hoisted(() => ({
+ blobs: [] as Blob[],
+ options: [] as { isIntermediate?: boolean }[],
+ onUpload: null as (() => Promise<void>) | null,
+}));
+vi.mock('./backend/canvasImages', () => ({
+ uploadCanvasImage: async (blob: Blob, options: { isIntermediate?: boolean }) => {
+ uploads.blobs.push(blob);
+ uploads.options.push(options);
+ await uploads.onUpload?.();
+ const bitmap = await createImageBitmap(blob);
+ try {
+ return { imageName: `legacy-paint-${uploads.blobs.length}.png`, width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ },
+}));
+
+import { convertLegacyCanvasMetadata } from './legacyCanvasMetadata';
+import { prepareLegacyOpacityStroke } from './legacyCanvasPressure';
+
+const pixel = async (blob: Blob, x: number, y: number): Promise<number[]> => {
+ const bitmap = await createImageBitmap(blob);
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ try {
+ const ctx = canvas.getContext('2d')!;
+ ctx.drawImage(bitmap, 0, 0);
+ return [...ctx.getImageData(x, y, 1, 1).data];
+ } finally {
+ bitmap.close();
+ canvas.width = 1;
+ canvas.height = 1;
+ }
+};
+const convert = (objects: unknown[], extra = {}, isCurrent?: () => boolean) =>
+ convertLegacyCanvasMetadata(
+ {
+ canvas_v2_metadata: {
+ rasterLayers: [
+ {
+ id: 'legacy',
+ name: 'Painted',
+ isEnabled: true,
+ isLocked: false,
+ position: { x: -50, y: 80 },
+ opacity: 0.5,
+ objects,
+ ...extra,
+ },
+ ],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ },
+ },
+ captureAccountScope(),
+ isCurrent
+ );
+const rectangle = {
+ id: 'rect',
+ type: 'rect',
+ rect: { x: -8, y: 4, width: 16, height: 16 },
+ color: { r: 200, g: 100, b: 50, a: 1 },
+};
+
+const pressureDot = {
+ id: 'pressure',
+ type: 'brush_line_with_pressure',
+ points: [0, 0, 0.5],
+ strokeWidth: 512,
+ pressureAffectsOpacity: true,
+ pressureAffectsWidth: false,
+ color: { r: 255, g: 0, b: 0, a: 1 },
+ clip: null,
+};
+
+beforeEach(() => {
+ accountLifecycle.activate('legacy-canvas-browser');
+ uploads.blobs.length = 0;
+ uploads.options.length = 0;
+ uploads.onUpload = null;
+});
+
+describe('legacy canvas raster recall', () => {
+ it('bakes ordered objects and erasure with negative local bounds while preserving layer position and opacity', async () => {
+ const result = await convert([
+ rectangle,
+ { id: 'erase', type: 'eraser_line', strokeWidth: 4, points: [0, 8, 0, 16], clip: null },
+ ]);
+ expect(result.problems).toEqual([]);
+ const document = result.record!.document as {
+ stacks: {
+ raster: {
+ transform: { x: number; y: number };
+ opacity: number;
+ source: { offset: { x: number; y: number } };
+ }[];
+ };
+ };
+ expect(document.stacks.raster[0]).toMatchObject({
+ opacity: 0.5,
+ transform: { x: -50, y: 80 },
+ source: { offset: { x: -8, y: 4 } },
+ });
+ expect(await pixel(uploads.blobs[0]!, 2, 2)).toEqual([200, 100, 50, 255]);
+ expect((await pixel(uploads.blobs[0]!, 8, 8))[3]).toBe(0);
+ });
+
+ it('bakes legacy adjustments and leaves alpha unchanged', async () => {
+ const identity = [
+ [0, 0],
+ [255, 255],
+ ];
+ const result = await convert([rectangle], {
+ adjustments: {
+ version: 1,
+ enabled: true,
+ collapsed: false,
+ mode: 'simple',
+ simple: { brightness: 0.2, contrast: 0, saturation: 0, temperature: 0, tint: 0, sharpness: 0 },
+ curves: { master: identity, r: identity, g: identity, b: identity },
+ },
+ });
+ expect(result.problems).toEqual([]);
+ expect(await pixel(uploads.blobs[0]!, 5, 5)).toEqual([251, 151, 101, 255]);
+ });
+
+ it('uses legacy maximum opacity coverage so overlapping pressure stamps do not darken the stroke', async () => {
+ const result = await convert([
+ {
+ id: 'pressure',
+ type: 'brush_line_with_pressure',
+ points: [10, 10, 0.5, 20, 10, 0.5, 10, 10, 0.5],
+ strokeWidth: 10,
+ pressureAffectsOpacity: true,
+ pressureAffectsWidth: false,
+ color: { r: 255, g: 0, b: 0, a: 1 },
+ clip: null,
+ },
+ ]);
+ expect(result.problems).toEqual([]);
+ const alpha = (await pixel(uploads.blobs[0]!, 10, 10))[3]!;
+ expect(alpha).toBeGreaterThanOrEqual(126);
+ expect(alpha).toBeLessThanOrEqual(128);
+ });
+
+ it.each([
+ ['dot', [10, 10, 0.5]],
+ ['horizontal stroke', [10, 10, 0.5, 20, 10, 0.5]],
+ ] as const)('keeps a one-pixel pressure-opacity %s visible on its two-pixel-high output', async (_kind, points) => {
+ // Legacy opacity is the maximum stamp coverage scaled by pressure, not repeated source-over blending.
+ const reference = new OffscreenCanvas(5, 5);
+ const ctx = reference.getContext('2d')!;
+ ctx.beginPath();
+ ctx.arc(2, 2, 0.5, 0, Math.PI * 2);
+ ctx.fill();
+ const expectedAlphas = [...ctx.getImageData(1, 1, 2, 2).data]
+ .filter((_, index) => index % 4 === 3)
+ .map((alpha) => Math.round((alpha * 128) / 255));
+ reference.width = 1;
+ reference.height = 1;
+ expect(Math.min(...expectedAlphas)).toBeGreaterThan(0);
+ const result = await convert([{ ...pressureDot, strokeWidth: 1, points: [...points] }]);
+ expect(result.problems).toEqual([]);
+ const bitmap = await createImageBitmap(uploads.blobs[0]!);
+ expect(bitmap.height).toBe(2);
+ bitmap.close();
+ const last = points.length === 3 ? 1 : 11;
+ for (let x = 0; x <= last; x++) {
+ for (let y = 0; y < 2; y++) {
+ const left = expectedAlphas[y * 2]!;
+ const right = expectedAlphas[y * 2 + 1]!;
+ const expected = x === 0 ? left : x === last ? right : Math.max(left, right);
+ expect((await pixel(uploads.blobs[0]!, x, y))[3]).toBe(expected);
+ }
+ }
+ });
+
+ it.each(['overlapping dots', 'sparse full-layer buffers'] as const)(
+ 'preflights cumulative pressure work for %s before allocating or sampling a refused layer',
+ async (kind) => {
+ const objects =
+ kind === 'overlapping dots'
+ ? Array.from({ length: 10000 }, () => pressureDot)
+ : [
+ { ...rectangle, rect: { x: 0, y: 0, width: 1024, height: 1024 } },
+ ...Array.from({ length: 100 }, () => ({ ...pressureDot, strokeWidth: 1, points: [512, 512, 0.5] })),
+ ];
+ const contexts = vi.spyOn(OffscreenCanvas.prototype, 'getContext');
+ try {
+ const result = await convert(objects);
+ expect(result.record).toBeNull();
+ expect(result.problems).toEqual(['Painted: legacy-conversion-work-limit']);
+ expect(uploads.blobs).toHaveLength(0);
+ expect(contexts).not.toHaveBeenCalled();
+ } finally {
+ contexts.mockRestore();
+ }
+ }
+ );
+
+ it('shares pressure work across layers and refuses the next layer before extra sampling or full-output buffers', async () => {
+ const canvas = new OffscreenCanvas(1, 1);
+ canvas.getContext('2d')!.fillRect(0, 0, 1, 1);
+ const png = await canvas.convertToBlob({ type: 'image/png' });
+ const encode = vi.spyOn(OffscreenCanvas.prototype, 'convertToBlob').mockResolvedValue(png);
+ const reads = vi.spyOn(OffscreenCanvasRenderingContext2D.prototype, 'getImageData');
+ const buffers = vi.spyOn(OffscreenCanvasRenderingContext2D.prototype, 'createImageData');
+ try {
+ const result = await convertLegacyCanvasMetadata(
+ {
+ canvas_v2_metadata: {
+ rasterLayers: Array.from({ length: 11 }, (_, index) => ({
+ id: `layer-${index}`,
+ name: `Layer ${index}`,
+ isEnabled: true,
+ isLocked: false,
+ position: { x: 0, y: 0 },
+ opacity: 1,
+ objects: [pressureDot],
+ })),
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ },
+ },
+ captureAccountScope()
+ );
+ expect(result.problems).toEqual(['Layer 0: legacy-conversion-work-limit']);
+ expect((result.record!.document as { stacks: { raster: unknown[] } }).stacks.raster).toHaveLength(10);
+ expect(uploads.blobs).toHaveLength(10);
+ // Ten 516-square samples and ten 1024-square output buffers; the eleventh layer does neither.
+ expect(reads.mock.calls.map((call) => [call[2], call[3]])).toEqual(Array.from({ length: 10 }, () => [516, 516]));
+ expect(buffers).toHaveBeenCalledTimes(10);
+ for (const call of buffers.mock.calls) {
+ expect(call).toEqual([1024, 1024]);
+ }
+ expect(reads.mock.calls.reduce((sum, call) => sum + call[2]! * call[3]!, 0)).toBe(2_662_560);
+ } finally {
+ buffers.mockRestore();
+ reads.mockRestore();
+ encode.mockRestore();
+ canvas.width = 1;
+ canvas.height = 1;
+ }
+ });
+
+ it.each([0, 4, 100])('refuses huge point inputs before smoothing with only %s remaining work units', (remaining) => {
+ let pointReads = 0;
+ const points = new Proxy(Array<number>(999_999).fill(0), {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ pointReads++;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ const budget = { workUnits: remaining };
+ for (let attempt = 0; attempt < 100; attempt++) {
+ expect(() => prepareLegacyOpacityStroke({ ...pressureDot, points }, { width: 1, height: 1 }, budget)).toThrow(
+ 'legacy-conversion-work-limit'
+ );
+ }
+ expect(pointReads).toBe(0);
+ expect(budget.workUnits).toBeGreaterThanOrEqual(0);
+ });
+
+ it('charges rejected stamp planning so later attempts cannot repeat raw-point smoothing or segment work', () => {
+ let pointReads = 0;
+ const points = new Proxy(Array.from({ length: 250 }, (_, index) => [index % 2 ? 10000 : 0, 0, 0.5]).flat(), {
+ get(target, property, receiver) {
+ if (typeof property === 'string' && /^\d+$/.test(property)) {
+ pointReads++;
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ const planning = vi.spyOn(Math, 'hypot');
+ const budget = { workUnits: 10000 };
+ const prepare = () =>
+ prepareLegacyOpacityStroke({ ...pressureDot, strokeWidth: 1, points }, { width: 1, height: 1 }, budget);
+ try {
+ expect(prepare).toThrow('legacy-conversion-work-limit');
+ expect(pointReads).toBeGreaterThan(0);
+ expect(planning).toHaveBeenCalledOnce();
+ const firstPointReads = pointReads;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ expect(prepare).toThrow('legacy-conversion-work-limit');
+ }
+ expect(pointReads).toBe(firstPointReads);
+ expect(planning).toHaveBeenCalledOnce();
+ expect(budget.workUnits).toBeGreaterThanOrEqual(0);
+ } finally {
+ planning.mockRestore();
+ }
+ });
+
+ it('keeps rejected preparation charged across layers while retaining usable image-only layers', async () => {
+ const points = Array.from({ length: 250 }, (_, index) => [index % 2 ? 10000 : 0, 0, 0.5]).flat();
+ const layer = {
+ id: 'legacy',
+ name: 'Painted',
+ isEnabled: true,
+ isLocked: false,
+ position: { x: 0, y: 0 },
+ opacity: 1,
+ objects: [{ ...pressureDot, points }],
+ };
+ const planning = vi.spyOn(Math, 'hypot');
+ const contexts = vi.spyOn(OffscreenCanvas.prototype, 'getContext');
+ try {
+ const result = await convertLegacyCanvasMetadata(
+ {
+ canvas_v2_metadata: {
+ rasterLayers: [
+ {
+ ...layer,
+ id: 'saved',
+ name: 'Already saved',
+ objects: [
+ {
+ id: 'image',
+ type: 'image',
+ image: { image_name: 'saved.png', width: 64, height: 64 },
+ },
+ ],
+ },
+ ...Array.from({ length: 100 }, (_, index) => ({ ...layer, id: `rejected-${index}` })),
+ ],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ },
+ },
+ captureAccountScope()
+ );
+ expect(result.problems).toEqual(Array<string>(100).fill('Painted: legacy-conversion-work-limit'));
+ expect((result.record!.document as { stacks: { raster: unknown[] } }).stacks.raster).toMatchObject([
+ { id: 'saved', source: { type: 'image', image: { imageName: 'saved.png' } } },
+ ]);
+ // Only the first layer starts planning: its first segment exhausts the shared work reservation.
+ expect(planning).toHaveBeenCalledOnce();
+ expect(contexts).not.toHaveBeenCalled();
+ expect(uploads.blobs).toHaveLength(0);
+ } finally {
+ contexts.mockRestore();
+ planning.mockRestore();
+ }
+ });
+
+ it('refuses oversized or malformed legacy objects without uploading a blank replacement', async () => {
+ const result = await convert([{ ...rectangle, rect: { x: 0, y: 0, width: 1000000, height: 1000000 } }]);
+ expect(result.record).toBeNull();
+ expect(result.problems).toEqual(['Painted: legacy-layer-too-large']);
+ expect(uploads.blobs).toHaveLength(0);
+ expect((await convert([{ type: 'not-an-object' }])).record).toBeNull();
+ });
+});
+
+it('stops a superseded project before raster uploads and bounds conversions in one untrusted record', async () => {
+ const layer = {
+ id: 'legacy',
+ name: 'Painted',
+ isEnabled: true,
+ isLocked: false,
+ position: { x: 0, y: 0 },
+ opacity: 1,
+ objects: [{ ...rectangle, rect: { x: 0, y: 0, width: 1, height: 1 } }],
+ };
+ const metadata = {
+ canvas_v2_metadata: {
+ rasterLayers: Array.from({ length: 129 }, (_, index) => ({
+ ...layer,
+ id: `layer-${index}`,
+ name: `Layer ${index}`,
+ })),
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ },
+ };
+ await expect(convertLegacyCanvasMetadata(metadata, captureAccountScope(), () => false)).rejects.toThrow(
+ 'canvas-changed'
+ );
+ expect(uploads.blobs).toHaveLength(0);
+ // Pixel tests above cover PNG encoding; this case exercises the per-record upload limit.
+ const canvas = new OffscreenCanvas(1, 1);
+ canvas.getContext('2d')!.fillRect(0, 0, 1, 1);
+ const png = await canvas.convertToBlob({ type: 'image/png' });
+ const encode = vi.spyOn(OffscreenCanvas.prototype, 'convertToBlob').mockResolvedValue(png);
+ try {
+ const result = await convertLegacyCanvasMetadata(metadata, captureAccountScope());
+ expect(uploads.blobs).toHaveLength(128);
+ expect(result.problems).toEqual(['Layer 0: legacy-conversion-limit']);
+ } finally {
+ encode.mockRestore();
+ }
+});
+
+it.each(['project', 'account'] as const)(
+ 'leaves in-flight uploads reclaimable and refuses a %s change during the last upload',
+ async (change) => {
+ let markStarted!: () => void;
+ let release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ markStarted = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let current = true;
+ uploads.onUpload = () => {
+ markStarted();
+ return held;
+ };
+ const pending = convert([rectangle], {}, () => current);
+ const settled = pending.catch(() => undefined);
+ try {
+ await Promise.race([
+ started,
+ settled.then(() => {
+ throw new Error('Conversion ended before the upload started');
+ }),
+ ]);
+ expect(uploads.blobs).toHaveLength(1);
+ expect(uploads.options[0]).toMatchObject({ isIntermediate: true });
+ if (change === 'project') {
+ current = false;
+ } else {
+ accountLifecycle.activate('another-account');
+ }
+ const rejected = expect(pending).rejects.toThrow();
+ release();
+ await rejected;
+ expect(uploads.blobs).toHaveLength(1);
+ } finally {
+ release();
+ await settled;
+ }
+ }
+);
+
+it('keeps unanswered conversion uploads intermediate instead of leaving an unknown durable image', async () => {
+ uploads.onUpload = () => Promise.reject(new TypeError('Failed to fetch'));
+ const result = await convert([rectangle]);
+ expect(result.record).toBeNull();
+ expect(result.createdImageNames).toEqual([]);
+ expect(uploads.options).toEqual([expect.objectContaining({ isIntermediate: true })]);
+});
+
+it('tracks only newly rasterized paint during a partial conversion, excluding borrowed image assets', async () => {
+ const common = { name: 'Layer', isEnabled: true, isLocked: false, position: { x: 0, y: 0 }, opacity: 1 };
+ const result = await convertLegacyCanvasMetadata(
+ {
+ canvas_v2_metadata: {
+ rasterLayers: [
+ { ...common, id: 'paint', objects: [rectangle] },
+ {
+ ...common,
+ id: 'borrowed',
+ objects: [{ id: 'image', type: 'image', image: { image_name: 'borrowed.png', width: 320, height: 200 } }],
+ },
+ { ...common, id: 'invalid', objects: [{ type: 'unsupported' }] },
+ ],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ },
+ },
+ captureAccountScope()
+ );
+ expect(result.record).not.toBeNull();
+ expect(result.problems).toHaveLength(1);
+ expect(result.createdImageNames).toEqual(['legacy-paint-1.png']);
+ expect(uploads.options).toEqual([expect.objectContaining({ isIntermediate: true })]);
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts
new file mode 100644
index 0000000000..4a31e1df5c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasMetadata.ts
@@ -0,0 +1,727 @@
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type {
+ CanvasDocumentContractV3,
+ CanvasLayerContract,
+ CanvasLayerSourceContract,
+} from '@workbench/canvas-engine/api';
+
+import { galleryImageUrls } from '@features/gallery/utility';
+import { createItemId } from '@platform/browser/randomUuid';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { apiFetchRaw } from '@platform/transport/http';
+import { uploadCanvasImage } from '@workbench/canvas-operations/backend/canvasImages';
+import { createEmptyCanvasDocument, isRecord } from '@workbench/canvasMigration';
+import { isStorableControlWeight, isStorableControlStepRange } from '@workbench/controlAdapters';
+import { getStroke } from 'perfect-freehand';
+import { z } from 'zod';
+
+import { applyLegacyCanvasAdjustments } from './legacyCanvasAdjustments';
+import { drawLegacyOpacityStroke, prepareLegacyOpacityStroke } from './legacyCanvasPressure';
+
+const number = z.number().finite();
+const point = z.object({ x: number, y: number });
+const rect = point.extend({ width: number.positive(), height: number.positive() });
+const color = z.object({
+ r: number.min(0).max(255),
+ g: number.min(0).max(255),
+ b: number.min(0).max(255),
+ a: number.min(0).max(1).default(1),
+});
+const image = z.object({ image_name: z.string().min(1), width: number.positive(), height: number.positive() });
+const objectImage = z.union([
+ image,
+ z.object({
+ dataURL: z.string().regex(/^data:image\/(?:png|jpeg|webp);base64,/u),
+ width: number.positive(),
+ height: number.positive(),
+ }),
+]);
+const operation = z
+ .enum([
+ 'source-over',
+ 'source-in',
+ 'source-out',
+ 'source-atop',
+ 'destination-over',
+ 'destination-in',
+ 'destination-out',
+ 'destination-atop',
+ 'lighter',
+ 'copy',
+ 'xor',
+ 'multiply',
+ 'screen',
+ 'overlay',
+ 'darken',
+ 'lighten',
+ 'color-dodge',
+ 'color-burn',
+ 'hard-light',
+ 'soft-light',
+ 'difference',
+ 'exclusion',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+ ])
+ .default('source-over');
+const common = { id: z.string(), clip: rect.nullable().optional() };
+const stroke = {
+ ...common,
+ points: z.array(number).max(1_000_000),
+ strokeWidth: number.positive(),
+ pressureAffectsWidth: z.boolean().default(true),
+ pressureAffectsOpacity: z.boolean().default(false),
+};
+const object = z.discriminatedUnion('type', [
+ z.object({ ...common, type: z.literal('image'), image: objectImage }),
+ z.object({ ...stroke, type: z.literal('brush_line'), color, globalCompositeOperation: operation }),
+ z.object({ ...stroke, type: z.literal('eraser_line') }),
+ z.object({ ...stroke, type: z.literal('brush_line_with_pressure'), color, globalCompositeOperation: operation }),
+ z.object({ ...stroke, type: z.literal('eraser_line_with_pressure') }),
+ z.object({ ...common, type: z.literal('rect'), rect, color, compositeOperation: operation }),
+ z.object({ ...common, type: z.literal('oval'), rect, color, compositeOperation: operation }),
+ z.object({
+ ...common,
+ type: z.literal('polygon'),
+ points: z.array(number).max(1_000_000),
+ color,
+ compositeOperation: operation,
+ }),
+ z.object({
+ ...common,
+ type: z.literal('lasso'),
+ points: z.array(number).max(1_000_000),
+ compositeOperation: operation,
+ }),
+ z.object({
+ ...common,
+ type: z.literal('gradient'),
+ bboxRect: rect,
+ gradientType: z.enum(['linear', 'radial']),
+ rect,
+ start: point.optional(),
+ end: point.optional(),
+ center: point.optional(),
+ radius: number.nonnegative().optional(),
+ clipCenter: point,
+ clipRadius: number.nonnegative(),
+ clipAngle: number.optional(),
+ clipEnabled: z.boolean().default(true),
+ fgColor: color,
+ bgColor: color,
+ globalCompositeOperation: operation,
+ }),
+]);
+type LegacyObject = z.infer<typeof object>;
+const rgba = (c: z.infer<typeof color>): string => `rgba(${c.r},${c.g},${c.b},${c.a})`;
+const fill = z.object({ style: z.enum(['solid', 'grid', 'crosshatch', 'diagonal', 'horizontal', 'vertical']), color });
+const adapter = z.object({
+ type: z.enum(['controlnet', 't2i_adapter', 'control_lora', 'z_image_control', 'anima_lllite']),
+ model: z.record(z.string(), z.unknown()).nullable(),
+ weight: number.min(-1).max(2),
+ beginEndStepPct: z.tuple([number.min(0).max(1), number.min(0).max(1)]).default([0, 1]),
+ controlMode: z.enum(['balanced', 'more_prompt', 'more_control', 'unbalanced']).nullable().default(null),
+});
+const layer = z.object({
+ id: z.string(),
+ name: z.string().nullable(),
+ isEnabled: z.boolean(),
+ isLocked: z.boolean(),
+ position: point,
+ opacity: number.min(0).max(1),
+ objects: z.array(object).max(10000),
+ controlAdapter: adapter.optional(),
+ withTransparencyEffect: z.boolean().optional(),
+ fill: fill.optional(),
+ positivePrompt: z.string().nullable().optional(),
+ negativePrompt: z.string().nullable().optional(),
+ autoNegative: z.boolean().optional(),
+ referenceImages: z.array(z.object({ id: z.string(), config: z.record(z.string(), z.unknown()) })).optional(),
+ noiseLevel: number.min(0).max(1).optional(),
+ denoiseLimit: number.min(0).max(1).optional(),
+ globalCompositeOperation: z.string().optional(),
+ isTransparencyLocked: z.boolean().optional(),
+ adjustments: z.record(z.string(), z.unknown()).optional(),
+});
+
+/** Konva's open Line with tension 0.3, used by legacy non-pressure brush and eraser objects. */
+const legacyLineControls = (points: number[]) => {
+ const controls: { x: number; y: number; beforeX: number; beforeY: number; afterX: number; afterY: number }[] = [];
+ for (let i = 2; i < points.length - 2; i += 2) {
+ const x0 = points[i - 2]!,
+ y0 = points[i - 1]!,
+ x = points[i]!,
+ y = points[i + 1]!,
+ x2 = points[i + 2]!,
+ y2 = points[i + 3]!;
+ const before = Math.hypot(x - x0, y - y0),
+ after = Math.hypot(x2 - x, y2 - y),
+ total = before + after;
+ const a = total ? (0.3 * before) / total : 0,
+ b = total ? (0.3 * after) / total : 0;
+ controls.push({
+ x,
+ y,
+ beforeX: x - a * (x2 - x0),
+ beforeY: y - a * (y2 - y0),
+ afterX: x + b * (x2 - x0),
+ afterY: y + b * (y2 - y0),
+ });
+ }
+ return controls;
+};
+
+const strokeLegacyLine = (ctx: OffscreenCanvasRenderingContext2D, points: number[]): void => {
+ if (points.length < 2) {
+ return;
+ }
+ ctx.moveTo(points[0]!, points[1]!);
+ const controls = legacyLineControls(points);
+ const first = controls[0];
+ if (first) {
+ ctx.quadraticCurveTo(first.beforeX, first.beforeY, first.x, first.y);
+ for (let i = 1; i < controls.length; i++) {
+ const previous = controls[i - 1]!,
+ current = controls[i]!;
+ ctx.bezierCurveTo(previous.afterX, previous.afterY, current.beforeX, current.beforeY, current.x, current.y);
+ }
+ const last = controls.at(-1)!;
+ ctx.quadraticCurveTo(last.afterX, last.afterY, points.at(-2)!, points.at(-1)!);
+ } else if (points.length >= 4) {
+ ctx.lineTo(points[2]!, points[3]!);
+ }
+};
+
+/** Legacy object lists become one durable paint bitmap per layer; unsupported/damaged layers are never replaced by blanks. */
+const rasterizeLegacyObjects = async (
+ objects: LegacyObject[],
+ owner: AccountScope,
+ adjustments: unknown,
+ isCurrent: () => boolean,
+ budget: { pixels: number; uploads: number; workUnits: number },
+ createdImageNames: string[]
+): Promise<CanvasLayerSourceContract> => {
+ if (objects.length === 0) {
+ return { type: 'paint', bitmap: null };
+ }
+ if (
+ adjustments === undefined &&
+ objects.length === 1 &&
+ objects[0]?.type === 'image' &&
+ 'image_name' in objects[0].image
+ ) {
+ const ref = objects[0].image;
+ return { type: 'image', image: { imageName: ref.image_name, width: ref.width, height: ref.height } };
+ }
+ let minX = Infinity,
+ minY = Infinity,
+ maxX = -Infinity,
+ maxY = -Infinity;
+ const include = (x: number, y: number, padding = 0): void => {
+ minX = Math.min(minX, x - padding);
+ minY = Math.min(minY, y - padding);
+ maxX = Math.max(maxX, x + padding);
+ maxY = Math.max(maxY, y + padding);
+ };
+ for (const item of objects) {
+ if (item.type === 'image') {
+ include(0, 0);
+ include(item.image.width, item.image.height);
+ } else if ('rect' in item) {
+ include(item.rect.x, item.rect.y);
+ include(item.rect.x + item.rect.width, item.rect.y + item.rect.height);
+ } else {
+ const stride = item.type.endsWith('_with_pressure') ? 3 : 2;
+ if (item.points.length % stride !== 0) {
+ throw new Error('invalid-points');
+ }
+ for (let i = 0; i < item.points.length; i += stride) {
+ include(item.points[i]!, item.points[i + 1]!, 'strokeWidth' in item ? item.strokeWidth : 0);
+ }
+ if (stride === 2 && 'strokeWidth' in item) {
+ for (const handle of legacyLineControls(item.points)) {
+ include(handle.beforeX, handle.beforeY, item.strokeWidth);
+ include(handle.afterX, handle.afterY, item.strokeWidth);
+ }
+ }
+ }
+ }
+ minX = Math.floor(minX);
+ minY = Math.floor(minY);
+ const width = Math.ceil(maxX) - minX,
+ height = Math.ceil(maxY) - minY;
+ // Bound each layer surface; pressure scratch and full-output work are reserved separately below.
+ if (
+ !Number.isFinite(width * height) ||
+ width < 1 ||
+ height < 1 ||
+ width > 16384 ||
+ height > 16384 ||
+ width * height > 16_777_216
+ ) {
+ throw new Error('legacy-layer-too-large');
+ }
+ if (budget.pixels < width * height || budget.uploads === 0) {
+ throw new Error('legacy-conversion-limit');
+ }
+ assertAccountScopeCurrent(owner);
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ if (budget.workUnits < width * height) {
+ throw new Error('legacy-conversion-work-limit');
+ }
+ budget.workUnits -= width * height;
+ const opacityStrokes = new Map<LegacyObject, ReturnType<typeof prepareLegacyOpacityStroke>>();
+ // Preparation and reservations stay charged even if this layer is refused later.
+ for (const item of objects) {
+ if (item.type === 'brush_line_with_pressure' && item.pressureAffectsOpacity) {
+ opacityStrokes.set(item, prepareLegacyOpacityStroke(item, { width, height }, budget));
+ }
+ }
+ budget.pixels -= width * height;
+ budget.uploads -= 1;
+ const canvas = new OffscreenCanvas(width, height);
+ try {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('canvas-unavailable');
+ }
+ ctx.translate(-minX, -minY);
+ for (const item of objects) {
+ assertAccountScopeCurrent(owner);
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ ctx.save();
+ try {
+ if (item.clip) {
+ ctx.beginPath();
+ ctx.rect(item.clip.x, item.clip.y, item.clip.width, item.clip.height);
+ ctx.clip();
+ }
+ ctx.fillStyle = 'color' in item ? rgba(item.color) : 'white';
+ ctx.strokeStyle = ctx.fillStyle;
+ if ('compositeOperation' in item) {
+ ctx.globalCompositeOperation = item.compositeOperation;
+ }
+ if ('globalCompositeOperation' in item) {
+ ctx.globalCompositeOperation = item.globalCompositeOperation;
+ }
+ if (item.type === 'image') {
+ let blob: Blob;
+ if ('image_name' in item.image) {
+ const response = await apiFetchRaw(galleryImageUrls.full(item.image.image_name), { signal: owner.signal });
+ if (!response.ok) {
+ throw new Error('image-unavailable');
+ }
+ blob = await response.blob();
+ } else {
+ const [prefix, encoded] = item.image.dataURL.split(',');
+ const bytes = Uint8Array.from(atob(encoded!), (character) => character.charCodeAt(0));
+ blob = new Blob([bytes], { type: prefix!.slice(5, prefix!.indexOf(';')) });
+ }
+ const bitmap = await createImageBitmap(blob, {
+ resizeWidth: Math.round(item.image.width),
+ resizeHeight: Math.round(item.image.height),
+ });
+ try {
+ assertAccountScopeCurrent(owner);
+ ctx.drawImage(bitmap, 0, 0, item.image.width, item.image.height);
+ } finally {
+ bitmap.close();
+ }
+ } else if (item.type === 'rect' || item.type === 'oval') {
+ const r = item.rect;
+ ctx.beginPath();
+ if (item.type === 'rect') {
+ ctx.rect(r.x, r.y, r.width, r.height);
+ } else {
+ ctx.ellipse(r.x + r.width / 2, r.y + r.height / 2, r.width / 2, r.height / 2, 0, 0, 2 * Math.PI);
+ }
+ ctx.fill();
+ } else if (item.type === 'gradient') {
+ let gradient: CanvasGradient;
+ if (item.gradientType === 'linear' && item.start && item.end) {
+ gradient = ctx.createLinearGradient(
+ item.rect.x + item.start.x,
+ item.rect.y + item.start.y,
+ item.rect.x + item.end.x,
+ item.rect.y + item.end.y
+ );
+ } else if (item.center && item.radius) {
+ gradient = ctx.createRadialGradient(
+ item.rect.x + item.center.x,
+ item.rect.y + item.center.y,
+ 0,
+ item.rect.x + item.center.x,
+ item.rect.y + item.center.y,
+ item.radius
+ );
+ } else {
+ throw new Error('invalid-gradient');
+ }
+ gradient.addColorStop(0, rgba(item.fgColor));
+ gradient.addColorStop(1, rgba(item.bgColor));
+ ctx.beginPath();
+ ctx.rect(item.bboxRect.x, item.bboxRect.y, item.bboxRect.width, item.bboxRect.height);
+ ctx.clip();
+ if (item.clipEnabled) {
+ ctx.beginPath();
+ if (item.gradientType === 'radial') {
+ ctx.arc(item.clipCenter.x, item.clipCenter.y, item.clipRadius, 0, 2 * Math.PI);
+ } else if (item.start && item.end) {
+ const dx = Math.cos(item.clipAngle ?? 0),
+ dy = Math.sin(item.clipAngle ?? 0);
+ const extent = Math.max(Math.hypot(item.bboxRect.width, item.bboxRect.height) * 2, 1);
+ const halfPlane = (x: number, y: number, sign: number): void => {
+ ctx.moveTo(x - dy * extent, y + dx * extent);
+ ctx.lineTo(x + dy * extent, y - dx * extent);
+ ctx.lineTo(x + dy * extent + dx * sign * extent, y - dx * extent + dy * sign * extent);
+ ctx.lineTo(x - dy * extent + dx * sign * extent, y + dx * extent + dy * sign * extent);
+ ctx.closePath();
+ };
+ halfPlane(item.rect.x + item.start.x, item.rect.y + item.start.y, 1);
+ ctx.clip();
+ ctx.beginPath();
+ halfPlane(item.rect.x + item.end.x, item.rect.y + item.end.y, -1);
+ }
+ ctx.clip();
+ }
+ ctx.fillStyle = gradient;
+ ctx.fillRect(item.rect.x, item.rect.y, item.rect.width, item.rect.height);
+ } else if (item.type === 'polygon' || item.type === 'lasso') {
+ if (item.points.length % 2 !== 0) {
+ throw new Error('invalid-points');
+ }
+ ctx.beginPath();
+ for (let i = 0; i < item.points.length; i += 2) {
+ if (i === 0) {
+ ctx.moveTo(item.points[i]!, item.points[i + 1]!);
+ } else {
+ ctx.lineTo(item.points[i]!, item.points[i + 1]!);
+ }
+ }
+ ctx.closePath();
+ ctx.fill();
+ } else {
+ if (item.type.startsWith('eraser')) {
+ ctx.globalCompositeOperation = 'destination-out';
+ }
+ if (item.type === 'brush_line_with_pressure' && item.pressureAffectsOpacity) {
+ drawLegacyOpacityStroke(ctx, opacityStrokes.get(item)!, { x: minX, y: minY, width, height });
+ } else if (item.type.endsWith('_with_pressure')) {
+ const points: number[][] = [];
+ for (let i = 0; i < item.points.length; i += 3) {
+ points.push([item.points[i]!, item.points[i + 1]!, Math.max(0, Math.min(1, item.points[i + 2]!))]);
+ }
+ const outline = getStroke(points, {
+ size: item.strokeWidth / 2,
+ thinning: item.pressureAffectsWidth ? 1 : 0,
+ simulatePressure: false,
+ last: true,
+ });
+ if (outline.length >= 4) {
+ const [first, second, third] = outline;
+ ctx.beginPath();
+ ctx.moveTo(first![0]!, first![1]!);
+ ctx.quadraticCurveTo(
+ second![0]!,
+ second![1]!,
+ (second![0]! + third![0]!) / 2,
+ (second![1]! + third![1]!) / 2
+ );
+ for (let i = 2; i < outline.length - 1; i++) {
+ const a = outline[i]!,
+ b = outline[i + 1]!;
+ ctx.quadraticCurveTo(a[0]!, a[1]!, (a[0]! + b[0]!) / 2, (a[1]! + b[1]!) / 2);
+ }
+ ctx.closePath();
+ ctx.fill();
+ }
+ } else {
+ ctx.lineWidth = item.strokeWidth;
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ ctx.beginPath();
+ strokeLegacyLine(ctx, item.points);
+ if (item.points.length === 2) {
+ ctx.arc(item.points[0]!, item.points[1]!, item.strokeWidth / 2, 0, 2 * Math.PI);
+ ctx.fill();
+ } else {
+ ctx.stroke();
+ }
+ }
+ }
+ } finally {
+ ctx.restore();
+ }
+ }
+ if (adjustments !== undefined) {
+ const pixels = ctx.getImageData(0, 0, width, height);
+ applyLegacyCanvasAdjustments(pixels, adjustments);
+ ctx.putImageData(pixels, 0, 0);
+ }
+ const blob = await canvas.convertToBlob({ type: 'image/png' });
+ assertAccountScopeCurrent(owner);
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ // Until the recall commits, even an upload whose response is lost must stay reclaimable.
+ const uploaded = await uploadCanvasImage(blob, { isIntermediate: true, signal: owner.signal });
+ createdImageNames.push(uploaded.imageName);
+ assertAccountScopeCurrent(owner);
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ return { type: 'paint', bitmap: uploaded, offset: { x: minX, y: minY } };
+ } finally {
+ canvas.width = 1;
+ canvas.height = 1;
+ }
+};
+
+export const convertLegacyCanvasMetadata = async (
+ metadata: Record<string, unknown>,
+ owner: AccountScope,
+ isCurrent: () => boolean = () => true
+): Promise<{ record: Record<string, unknown> | null; problems: string[]; createdImageNames: string[] }> => {
+ const raw = metadata.canvas_v2_metadata;
+ const budget = { pixels: 64 * 1024 * 1024, uploads: 128, workUnits: 64 * 1024 * 1024 };
+ const problems: string[] = [];
+ const createdImageNames: string[] = [];
+ const document = createEmptyCanvasDocument(
+ typeof metadata.width === 'number' ? metadata.width : 1024,
+ typeof metadata.height === 'number' ? metadata.height : 1024
+ );
+ const controlModels: Record<string, unknown> = Object.create(null);
+ if (!isRecord(raw)) {
+ // recall_parameters names already prepared control maps, unlike legacy authored object lists.
+ if (!Array.isArray(metadata.control_layers)) {
+ return { record: null, problems: 'control_layers' in metadata ? ['invalid-control'] : [], createdImageNames };
+ }
+ for (const control of metadata.control_layers.slice(0, 10000)) {
+ if (
+ !isRecord(control) ||
+ !isRecord(control.image) ||
+ !(typeof control.model_key === 'string' || isRecord(control.model))
+ ) {
+ problems.push('invalid-control');
+ continue;
+ }
+ const weight = control.weight === undefined ? 1 : control.weight;
+ const range = [
+ control.begin_step_percent === undefined ? 0 : control.begin_step_percent,
+ control.end_step_percent === undefined ? 1 : control.end_step_percent,
+ ];
+ if (!isStorableControlWeight(weight) || !isStorableControlStepRange(range)) {
+ problems.push('invalid-control');
+ continue;
+ }
+ const asset = image.safeParse(control.processed_image ?? control.image);
+ if (!asset.success) {
+ problems.push('invalid-control-image');
+ continue;
+ }
+ const id = createItemId('control');
+ const modelKey =
+ typeof control.model_key === 'string'
+ ? control.model_key
+ : isRecord(control.model) && typeof control.model.key === 'string'
+ ? control.model.key
+ : null;
+ if (isRecord(control.model)) {
+ controlModels[id] = control.model;
+ }
+ document.stacks.control.push({
+ id,
+ name: typeof control.name === 'string' ? control.name : 'Control layer',
+ isEnabled: control.is_enabled !== false,
+ isLocked: false,
+ opacity: 1,
+ blendMode: 'normal',
+ transform: {
+ x: isRecord(control.position) && typeof control.position.x === 'number' ? control.position.x : 0,
+ y: isRecord(control.position) && typeof control.position.y === 'number' ? control.position.y : 0,
+ rotation: 0,
+ scaleX: 1,
+ scaleY: 1,
+ },
+ type: 'control',
+ source: {
+ type: 'image',
+ image: { imageName: asset.data.image_name, width: asset.data.width, height: asset.data.height },
+ },
+ withTransparencyEffect: false,
+ adapter: {
+ model: modelKey,
+ kind: 'controlnet',
+ weight,
+ beginEndStepPct: range,
+ controlMode:
+ control.control_mode === 'more_prompt' ||
+ control.control_mode === 'more_control' ||
+ control.control_mode === 'unbalanced'
+ ? control.control_mode
+ : 'balanced',
+ },
+ });
+ }
+ if (metadata.control_layers.length && !document.stacks.control.length) {
+ return { record: null, problems, createdImageNames };
+ }
+ } else {
+ const stacks = {
+ rasterLayers: 'raster',
+ controlLayers: 'control',
+ inpaintMasks: 'inpaint_mask',
+ regionalGuidance: 'regional_guidance',
+ } as const;
+ if (
+ !Object.keys(stacks).every((key) => Array.isArray(raw[key])) ||
+ Object.keys(stacks).reduce((sum, key) => sum + (raw[key] as unknown[]).length, 0) > 10000
+ ) {
+ return { record: null, problems: ['invalid-legacy-document'], createdImageNames };
+ }
+ for (const [key, stack] of Object.entries(stacks)) {
+ // Legacy arrays are bottom-first; current forests are top-first.
+ for (const value of [...(raw[key] as unknown[])].reverse()) {
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ const parsed = layer.safeParse(value);
+ if (!parsed.success) {
+ problems.push(isRecord(value) && typeof value.name === 'string' ? value.name : 'invalid-legacy-layer');
+ continue;
+ }
+ const item = parsed.data;
+ try {
+ // Unsupported composite/adjustment semantics must never silently produce a different image.
+ if (
+ item.globalCompositeOperation &&
+ ![
+ 'source-over',
+ 'multiply',
+ 'screen',
+ 'overlay',
+ 'darken',
+ 'lighten',
+ 'color-dodge',
+ 'color-burn',
+ 'hard-light',
+ 'soft-light',
+ 'difference',
+ 'exclusion',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+ ].includes(item.globalCompositeOperation)
+ ) {
+ throw new Error('unsupported-blend');
+ }
+ const source = await rasterizeLegacyObjects(
+ item.objects,
+ owner,
+ item.adjustments,
+ isCurrent,
+ budget,
+ createdImageNames
+ );
+ assertAccountScopeCurrent(owner);
+ const base = {
+ id: item.id,
+ name: item.name ?? 'Recalled layer',
+ isEnabled: item.isEnabled,
+ isLocked: item.isLocked,
+ opacity: item.opacity,
+ blendMode:
+ item.globalCompositeOperation === 'source-over' || !item.globalCompositeOperation
+ ? 'normal'
+ : item.globalCompositeOperation,
+ transform: { x: item.position.x, y: item.position.y, scaleX: 1, scaleY: 1, rotation: 0 },
+ };
+ let result: unknown;
+ if (stack === 'raster') {
+ result = { ...base, type: stack, source, isTransparencyLocked: item.isTransparencyLocked };
+ } else if (stack === 'control' && item.controlAdapter) {
+ controlModels[item.id] = item.controlAdapter.model;
+ result = {
+ ...base,
+ type: stack,
+ source,
+ withTransparencyEffect: item.withTransparencyEffect ?? false,
+ adapter: {
+ ...item.controlAdapter,
+ kind: item.controlAdapter.type,
+ model: item.controlAdapter.model?.key ?? null,
+ },
+ };
+ } else {
+ if (source.type !== 'image' && source.type !== 'paint') {
+ throw new Error('invalid-mask');
+ }
+ const mask = {
+ bitmap: source.type === 'image' ? source.image : source.bitmap,
+ offset: source.type === 'paint' ? source.offset : undefined,
+ fill: { style: item.fill?.style ?? 'solid', color: item.fill ? rgba(item.fill.color) : 'red' },
+ };
+ if (stack === 'inpaint_mask') {
+ result = {
+ ...base,
+ type: stack,
+ mask,
+ ...(item.noiseLevel === undefined ? {} : { noise: { level: item.noiseLevel, isEnabled: true } }),
+ ...(item.denoiseLimit === undefined ? {} : { denoise: { limit: item.denoiseLimit, isEnabled: true } }),
+ };
+ } else {
+ result = {
+ ...base,
+ type: stack,
+ mask,
+ positivePrompt: item.positivePrompt ?? null,
+ negativePrompt: item.negativePrompt ?? null,
+ autoNegative: item.autoNegative ?? false,
+ referenceImages: (item.referenceImages ?? []).map((ref) => {
+ const asset = image.safeParse(ref.config.image);
+ return {
+ ...ref,
+ isEnabled: true,
+ config: {
+ ...ref.config,
+ image: asset.success
+ ? {
+ imageName: asset.data.image_name,
+ width: asset.data.width,
+ height: asset.data.height,
+ imageUrl: '',
+ thumbnailUrl: '',
+ queuedAt: '',
+ sourceQueueItemId: '',
+ }
+ : null,
+ },
+ };
+ }),
+ };
+ }
+ }
+ // The current canvas loader below validates this wire projection before anything can commit.
+ document.stacks[stack as keyof CanvasDocumentContractV3['stacks']].push(result as CanvasLayerContract);
+ } catch (error) {
+ assertAccountScopeCurrent(owner);
+ if (!isCurrent()) {
+ throw new Error('canvas-changed');
+ }
+ problems.push(`${item.name ?? item.id}: ${error instanceof Error ? error.message : 'unavailable'}`);
+ }
+ }
+ }
+ if (Object.values(document.stacks).every((nodes) => nodes.length === 0)) {
+ return { record: null, problems, createdImageNames };
+ }
+ }
+ return { record: { version: 1, document, controlModels }, problems, createdImageNames };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasPressure.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasPressure.ts
new file mode 100644
index 0000000000..3b2566956d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/legacyCanvasPressure.ts
@@ -0,0 +1,393 @@
+/** Legacy opacity strokes use max coverage per stamp; source-over would darken overlapping stamps. */
+interface Coordinate {
+ x: number;
+ y: number;
+}
+interface CoordinateWithPressure extends Coordinate {
+ pressure: number;
+}
+interface RgbaColor {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+interface PressureStrokeRenderOp {
+ type: 'dot';
+ x: number;
+ y: number;
+ radius: number;
+ color: RgbaColor;
+}
+const MIN_PRESSURE_FACTOR = 0.05;
+const PRESSURE_SMOOTHING_CENTER_WEIGHT = 0.6;
+const PRESSURE_SMOOTHING_NEIGHBOR_WEIGHT = 0.2;
+const OPACITY_SMOOTHING_CENTER_WEIGHT = 0.5;
+const OPACITY_SMOOTHING_NEIGHBOR_WEIGHT = 0.25;
+const OPACITY_SMOOTHING_PASSES = 2;
+const OPACITY_ENDPOINT_CENTER_WEIGHT = 0.25;
+const OPACITY_ENDPOINT_NEIGHBOR_WEIGHT = 0.75;
+const OPACITY_DELTA_STEP_SCALE = 12;
+const MIN_OPACITY_STAMP_SPACING_PX = 1;
+const OPACITY_STAMP_SPACING_STROKE_WIDTH_SCALE = 0.03;
+const MAX_OPACITY_STAMPS_PER_SEGMENT = 128;
+
+const reserveWork = (budget: { workUnits: number }, units: number): void => {
+ if (units > budget.workUnits) {
+ throw new Error('legacy-conversion-work-limit');
+ }
+ budget.workUnits -= units;
+};
+
+const clampPressure = (pressure: number): number => Math.min(Math.max(pressure, 0), 1);
+
+const getPressureWidthFactor = (pressure: number, pressureAffectsWidth: boolean): number => {
+ if (!pressureAffectsWidth) {
+ return 1;
+ }
+
+ return Math.max(clampPressure(pressure), MIN_PRESSURE_FACTOR);
+};
+
+const scaleColorOpacity = (color: RgbaColor, opacityFactor: number): RgbaColor => ({
+ ...color,
+ a: Math.min(Math.max(color.a * opacityFactor, 0), 1),
+});
+
+const chunkPressurePoints = (points: number[]): CoordinateWithPressure[] => {
+ const chunked: CoordinateWithPressure[] = [];
+
+ for (let i = 0; i < points.length; i += 3) {
+ const x = points[i];
+ const y = points[i + 1];
+ const pressure = points[i + 2];
+
+ if (x === undefined || y === undefined || pressure === undefined) {
+ continue;
+ }
+
+ chunked.push({ x, y, pressure });
+ }
+
+ return chunked;
+};
+
+const smoothPressurePointsWithWeights = (
+ points: CoordinateWithPressure[],
+ centerWeight: number,
+ neighborWeight: number,
+ passes: number = 1
+): CoordinateWithPressure[] => {
+ if (points.length <= 2) {
+ return points;
+ }
+
+ let smoothedPoints = points;
+
+ for (let pass = 0; pass < passes; pass++) {
+ smoothedPoints = smoothedPoints.map((point, index) => {
+ if (index === 0 || index === smoothedPoints.length - 1) {
+ return point;
+ }
+
+ const prevPoint = smoothedPoints[index - 1];
+ const nextPoint = smoothedPoints[index + 1];
+
+ if (!prevPoint || !nextPoint) {
+ return point;
+ }
+
+ return {
+ ...point,
+ pressure: clampPressure(
+ prevPoint.pressure * neighborWeight + point.pressure * centerWeight + nextPoint.pressure * neighborWeight
+ ),
+ };
+ });
+ }
+
+ return smoothedPoints;
+};
+
+const smoothPressurePoints = (points: CoordinateWithPressure[]): CoordinateWithPressure[] =>
+ smoothPressurePointsWithWeights(points, PRESSURE_SMOOTHING_CENTER_WEIGHT, PRESSURE_SMOOTHING_NEIGHBOR_WEIGHT);
+
+const smoothStrokeGeometryPoints = (points: CoordinateWithPressure[]): CoordinateWithPressure[] => {
+ if (points.length <= 2) {
+ return points;
+ }
+
+ const smoothed: CoordinateWithPressure[] = [];
+ const firstPoint = points[0];
+ const lastPoint = points.at(-1);
+
+ if (!firstPoint || !lastPoint) {
+ return points;
+ }
+
+ smoothed.push(firstPoint);
+
+ for (let i = 0; i < points.length - 1; i++) {
+ const point = points[i];
+ const nextPoint = points[i + 1];
+
+ if (!point || !nextPoint) {
+ continue;
+ }
+
+ smoothed.push({
+ x: point.x * 0.75 + nextPoint.x * 0.25,
+ y: point.y * 0.75 + nextPoint.y * 0.25,
+ pressure: clampPressure(point.pressure * 0.75 + nextPoint.pressure * 0.25),
+ });
+ smoothed.push({
+ x: point.x * 0.25 + nextPoint.x * 0.75,
+ y: point.y * 0.25 + nextPoint.y * 0.75,
+ pressure: clampPressure(point.pressure * 0.25 + nextPoint.pressure * 0.75),
+ });
+ }
+
+ smoothed.push(lastPoint);
+
+ return smoothed;
+};
+
+const smoothOpacityPressurePoints = (points: CoordinateWithPressure[]): CoordinateWithPressure[] =>
+ smoothPressurePointsWithWeights(
+ points,
+ OPACITY_SMOOTHING_CENTER_WEIGHT,
+ OPACITY_SMOOTHING_NEIGHBOR_WEIGHT,
+ OPACITY_SMOOTHING_PASSES
+ );
+
+const smoothOpacityEndpointPressurePoints = (points: CoordinateWithPressure[]): CoordinateWithPressure[] => {
+ if (points.length <= 1) {
+ return points;
+ }
+
+ const smoothedPoints = [...points];
+ const firstPoint = smoothedPoints[0];
+ const secondPoint = smoothedPoints[1];
+ const lastPoint = smoothedPoints.at(-1);
+ const penultimatePoint = smoothedPoints.at(-2);
+
+ if (firstPoint && secondPoint) {
+ smoothedPoints[0] = {
+ ...firstPoint,
+ pressure: clampPressure(
+ firstPoint.pressure * OPACITY_ENDPOINT_CENTER_WEIGHT + secondPoint.pressure * OPACITY_ENDPOINT_NEIGHBOR_WEIGHT
+ ),
+ };
+ }
+
+ if (lastPoint && penultimatePoint) {
+ smoothedPoints[smoothedPoints.length - 1] = {
+ ...lastPoint,
+ pressure: clampPressure(
+ lastPoint.pressure * OPACITY_ENDPOINT_CENTER_WEIGHT +
+ penultimatePoint.pressure * OPACITY_ENDPOINT_NEIGHBOR_WEIGHT
+ ),
+ };
+ }
+
+ return smoothedPoints;
+};
+
+const buildOpacityStampRenderOps = (arg: {
+ pressurePoints: CoordinateWithPressure[];
+ strokeWidth: number;
+ color: RgbaColor;
+ pressureAffectsWidth: boolean;
+ includeLeadingDot: boolean;
+ reserveStamp: (radius: number) => void;
+}): PressureStrokeRenderOp[] => {
+ const { pressurePoints, strokeWidth, color, pressureAffectsWidth, includeLeadingDot, reserveStamp } = arg;
+
+ if (pressurePoints.length === 0) {
+ return [];
+ }
+
+ if (pressurePoints.length === 1) {
+ if (!includeLeadingDot) {
+ return [];
+ }
+
+ const point = pressurePoints[0];
+
+ if (!point) {
+ return [];
+ }
+
+ const widthFactor = getPressureWidthFactor(point.pressure, pressureAffectsWidth);
+ const opacityFactor = clampPressure(point.pressure);
+ reserveStamp((strokeWidth * widthFactor) / 2);
+
+ return [
+ {
+ type: 'dot',
+ x: point.x,
+ y: point.y,
+ radius: (strokeWidth * widthFactor) / 2,
+ color: scaleColorOpacity(color, opacityFactor),
+ },
+ ];
+ }
+
+ const ops: PressureStrokeRenderOp[] = [];
+ for (let i = 1; i < pressurePoints.length; i++) {
+ const prevPoint = pressurePoints[i - 1];
+ const nextPoint = pressurePoints[i];
+
+ if (!prevPoint || !nextPoint) {
+ continue;
+ }
+
+ const distance = Math.hypot(nextPoint.x - prevPoint.x, nextPoint.y - prevPoint.y);
+ const averageWidthFactor =
+ (getPressureWidthFactor(prevPoint.pressure, pressureAffectsWidth) +
+ getPressureWidthFactor(nextPoint.pressure, pressureAffectsWidth)) /
+ 2;
+ const stampSpacing = Math.max(
+ MIN_OPACITY_STAMP_SPACING_PX,
+ strokeWidth * averageWidthFactor * OPACITY_STAMP_SPACING_STROKE_WIDTH_SCALE
+ );
+ const stampCount = Math.min(
+ MAX_OPACITY_STAMPS_PER_SEGMENT,
+ Math.max(
+ 1,
+ Math.ceil(distance / stampSpacing),
+ Math.ceil(Math.abs(nextPoint.pressure - prevPoint.pressure) * OPACITY_DELTA_STEP_SCALE)
+ )
+ );
+ const sampleStart = includeLeadingDot && i === 1 ? 0 : 1;
+
+ for (let sampleIndex = sampleStart; sampleIndex <= stampCount; sampleIndex++) {
+ const t = sampleIndex / stampCount;
+ const samplePoint = lerpPointWithPressure(prevPoint, nextPoint, t);
+ const widthFactor = getPressureWidthFactor(samplePoint.pressure, pressureAffectsWidth);
+ const opacityFactor = clampPressure(samplePoint.pressure);
+
+ if (ops.length >= 100000) {
+ throw new Error('legacy-stroke-too-large');
+ }
+ reserveStamp((strokeWidth * widthFactor) / 2);
+ ops.push({
+ type: 'dot',
+ x: samplePoint.x,
+ y: samplePoint.y,
+ radius: (strokeWidth * widthFactor) / 2,
+ color: scaleColorOpacity(color, opacityFactor),
+ });
+ }
+ }
+
+ return ops;
+};
+
+const lerp = (from: number, to: number, t: number): number => from + (to - from) * t;
+
+const lerpPointWithPressure = (
+ from: CoordinateWithPressure,
+ to: CoordinateWithPressure,
+ t: number
+): CoordinateWithPressure => ({
+ x: lerp(from.x, to.x, t),
+ y: lerp(from.y, to.y, t),
+ pressure: lerp(from.pressure, to.pressure, t),
+});
+
+export const prepareLegacyOpacityStroke = (
+ options: {
+ points: number[];
+ strokeWidth: number;
+ color: RgbaColor;
+ pressureAffectsWidth: boolean;
+ },
+ bounds: { width: number; height: number },
+ budget: { workUnits: number }
+) => {
+ // Reserve output surface, ImageData, put/draw and the initial stamp surface before inspecting points.
+ reserveWork(budget, 4 * bounds.width * bounds.height + 1);
+ // Twenty units per raw point cover chunking, expanded geometry, smoothing passes and segment planning.
+ reserveWork(budget, Math.ceil(options.points.length / 3) * 20);
+ const pressurePoints = smoothOpacityEndpointPressurePoints(
+ smoothOpacityPressurePoints(smoothStrokeGeometryPoints(smoothPressurePoints(chunkPressurePoints(options.points))))
+ );
+ let sampledPixels = 0;
+ let stampSize = 1;
+ const ops = buildOpacityStampRenderOps({
+ ...options,
+ pressurePoints,
+ includeLeadingDot: true,
+ reserveStamp: (radius) => {
+ const size = Math.ceil(radius * 2 + 4);
+ const pixels = size * size;
+ if (sampledPixels + pixels > 16 * 1024 * 1024) {
+ throw new Error('legacy-stroke-too-large');
+ }
+ // One planning unit, each clear/read/coverage merge, and any growth of the stamp surface.
+ reserveWork(budget, 1 + 3 * pixels + Math.max(0, pixels - stampSize * stampSize));
+ sampledPixels += pixels;
+ stampSize = Math.max(stampSize, size);
+ },
+ });
+ return { ops, stampSize };
+};
+
+export const drawLegacyOpacityStroke = (
+ ctx: OffscreenCanvasRenderingContext2D,
+ { ops, stampSize }: ReturnType<typeof prepareLegacyOpacityStroke>,
+ bounds: { x: number; y: number; width: number; height: number }
+): void => {
+ const patch = new OffscreenCanvas(bounds.width, bounds.height);
+ // Sampling must fit a whole stamp even when the output is only a thin row or column.
+ let stamp: OffscreenCanvas | null = null;
+ try {
+ stamp = new OffscreenCanvas(stampSize, stampSize);
+ const patchCtx = patch.getContext('2d');
+ const stampCtx = stamp.getContext('2d', { willReadFrequently: true });
+ if (!patchCtx || !stampCtx) {
+ throw new Error('canvas-unavailable');
+ }
+ const output = patchCtx.createImageData(bounds.width, bounds.height);
+ for (const op of ops) {
+ const x = Math.floor(op.x - op.radius - 2),
+ y = Math.floor(op.y - op.radius - 2);
+ const width = Math.ceil(op.radius * 2 + 4),
+ height = width;
+ stampCtx.clearRect(0, 0, width, height);
+ stampCtx.beginPath();
+ stampCtx.arc(op.x - x, op.y - y, op.radius, 0, Math.PI * 2);
+ stampCtx.fill();
+ const pixels = stampCtx.getImageData(0, 0, width, height).data;
+ for (let row = 0; row < height; row++) {
+ for (let col = 0; col < width; col++) {
+ const targetX = x + col - bounds.x,
+ targetY = y + row - bounds.y;
+ if (targetX < 0 || targetY < 0 || targetX >= bounds.width || targetY >= bounds.height) {
+ continue;
+ }
+ const index = (targetY * bounds.width + targetX) * 4;
+ const alpha = Math.round(
+ (pixels[(row * width + col) * 4 + 3]! * Math.round(clampPressure(op.color.a) * 255)) / 255
+ );
+ if (alpha > output.data[index + 3]!) {
+ output.data[index] = op.color.r;
+ output.data[index + 1] = op.color.g;
+ output.data[index + 2] = op.color.b;
+ output.data[index + 3] = alpha;
+ }
+ }
+ }
+ }
+ patchCtx.putImageData(output, 0, 0);
+ ctx.drawImage(patch, bounds.x, bounds.y);
+ } finally {
+ patch.width = 1;
+ patch.height = 1;
+ if (stamp) {
+ stamp.width = 1;
+ stamp.height = 1;
+ }
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
index 77a8db13d3..bf89402303 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts
@@ -10,6 +10,7 @@ import { galleryKeys } from '@features/gallery/queries';
import { getDefaultGenerateSettings } from '@features/generation/settings';
import { queryClient } from '@platform/query/client';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
import { getProjectWidgetInstance } from '@workbench/widgetState';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -55,6 +56,13 @@ const createProject = (boardId = 'board-1', generateOverrides: Partial<GenerateW
negativePrompt: 'avoid blur',
positivePrompt: 'a canvas prompt',
seed: 123,
+ steps: 23,
+ cfgScale: 6,
+ cfgRescaleMultiplier: 0.1,
+ scheduler: 'euler',
+ clipSkip: 1,
+ seamlessXAxis: false,
+ seamlessYAxis: true,
...generateOverrides,
};
// Following the selected board, so the board under test is where saves go.
@@ -63,17 +71,21 @@ const createProject = (boardId = 'board-1', generateOverrides: Partial<GenerateW
return project;
};
-const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ bbox }) as unknown as CanvasDocumentContractV3;
+const createDocument = (bbox: Rect): CanvasDocumentContractV3 => ({ ...createEmptyCanvasDocument(), bbox });
const createHarness = (
options: {
document?: CanvasDocumentContractV3 | null;
exportResult?: RasterCompositeExportResult;
onFlush?: () => void;
+ project?: Project;
} = {}
) => {
const order: string[] = [];
let document = options.document === undefined ? createDocument(defaultRect) : options.document;
+ let project = options.project ?? createProject();
+ project = { ...project, canvas: { ...project.canvas, document: document ?? project.canvas.document } };
+ const getProject = vi.fn((projectId: string) => (projectId === project.id ? project : null));
const exportResult = options.exportResult ?? { blob: defaultBlob, rect: defaultRect, status: 'ok' };
const flushPendingUploads = vi.fn(() => {
order.push('flush');
@@ -103,9 +115,18 @@ const createHarness = (
exportRasterComposite,
flushPendingUploads,
getDocument,
+ getProject,
order,
+ project,
setDocument: (next: CanvasDocumentContractV3 | null) => {
document = next;
+ if (next) {
+ project = { ...project, canvas: { ...project.canvas, document: next } };
+ }
+ },
+ setProject: (next: Project) => {
+ project = next;
+ document = next.canvas.document;
},
uploadImage,
};
@@ -137,6 +158,7 @@ const listGalleryBoardsInCache = (...boardIds: string[]) =>
describe('saveCanvasToGallery', () => {
afterEach(() => {
queryClient.clear();
+ vi.unstubAllGlobals();
});
beforeEach(() => {
@@ -154,14 +176,15 @@ describe('saveCanvasToGallery', () => {
await expect(
saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
})
).resolves.toEqual({ boardId: 'board-1', imageName: 'saved.png', status: 'saved' });
- expect(harness.order).toEqual(['flush', 'document', 'export', 'upload']);
+ expect(harness.order).toEqual(['flush', 'document', 'export', 'document', 'upload']);
expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'content' });
expect(harness.uploadImage).toHaveBeenCalledWith(defaultBlob, {
boardId: 'board-1',
@@ -169,11 +192,22 @@ describe('saveCanvasToGallery', () => {
imageCategory: 'general',
isIntermediate: false,
metadata: {
+ metadata_source: 'canvas_save',
+ vae: null,
+ steps: 23,
+ cfg_scale: 6,
+ cfg_rescale_multiplier: 0.1,
+ scheduler: 'euler',
+ clip_skip: 1,
+ seamless_x: false,
+ seamless_y: true,
+ loras: [],
+ ref_images: [],
height: 456,
model: { base: 'sd-1', hash: 'model-hash', key: 'model-key', name: 'Test Model', type: 'main' },
negative_prompt: 'avoid blur',
positive_prompt: 'a canvas prompt',
- seed: 123,
+ canvas_v3_metadata: expect.objectContaining({ version: 1, document: createDocument(defaultRect) }),
width: 123,
},
signal: expect.any(AbortSignal),
@@ -191,7 +225,8 @@ describe('saveCanvasToGallery', () => {
await saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'bbox',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -201,16 +236,191 @@ describe('saveCanvasToGallery', () => {
expect(harness.uploadImage).toHaveBeenCalledWith(defaultBlob, expect.objectContaining({ fileName: 'bbox.png' }));
});
+ it('captures the post-flush document and settings after a cold board read, keeping the click-time destination', async () => {
+ queryClient.clear();
+ const boards = deferred<Response>();
+ const fetchBoards = vi.fn<typeof fetch>((url) =>
+ new URL(String(url)).pathname === '/api/v1/boards/'
+ ? boards.promise
+ : Promise.resolve(Response.json({ total: 0 }))
+ );
+ vi.stubGlobal('fetch', fetchBoards);
+ const harness = createHarness();
+ const flush = deferred<void>();
+ harness.flushPendingUploads.mockReturnValueOnce(flush.promise);
+
+ const save = saveCanvasToGallery({
+ engine: harness.engine,
+ getProject: harness.getProject,
+ project: harness.project,
+ region: 'bbox',
+ scopedDefaults: {},
+ uploadImage: harness.uploadImage,
+ });
+
+ await vi.waitFor(() => expect(fetchBoards).toHaveBeenCalled());
+ expect(harness.flushPendingUploads).not.toHaveBeenCalled();
+ const whileListingBoards = structuredClone(harness.project);
+ whileListingBoards.canvas.document.bbox = { height: 40, width: 30, x: 5, y: 6 };
+ getProjectWidgetInstance(whileListingBoards, 'generate')!.state.values.positivePrompt =
+ 'edited during board lookup';
+ getProjectWidgetInstance(whileListingBoards, 'canvas')!.state.values.denoisingStrength = 0.4;
+ getProjectWidgetInstance(whileListingBoards, 'gallery')!.state.values.selectedBoardId = 'board-physical';
+ harness.setProject(whileListingBoards);
+ boards.resolve(
+ Response.json(
+ ['board-1', 'board-physical'].map((board_id) => ({
+ archived: false,
+ asset_count: 0,
+ board_id,
+ board_name: board_id,
+ image_count: 0,
+ }))
+ )
+ );
+
+ await vi.waitFor(() => expect(harness.flushPendingUploads).toHaveBeenCalledOnce());
+ const afterUploads = structuredClone(whileListingBoards);
+ const capturedBbox = { height: 80, width: 60, x: 15, y: 16 };
+ afterUploads.canvas.document.bbox = capturedBbox;
+ Object.assign(getProjectWidgetInstance(afterUploads, 'generate')!.state.values, {
+ positivePrompt: 'edited while paint was uploading',
+ steps: 31,
+ });
+ Object.assign(getProjectWidgetInstance(afterUploads, 'canvas')!.state.values, {
+ denoisingStrength: 0.6,
+ maskBlur: 8,
+ scaleMethod: 'manual',
+ scaledHeight: 768,
+ scaledWidth: 1024,
+ });
+ harness.setProject(afterUploads);
+ flush.resolve();
+
+ await expect(save).resolves.toEqual({ boardId: 'board-1', imageName: 'saved.png', status: 'saved' });
+ expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'rect', rect: capturedBbox });
+ expect(harness.uploadImage.mock.calls[0]?.[1]).toMatchObject({
+ boardId: 'board-1',
+ metadata: {
+ positive_prompt: 'edited while paint was uploading',
+ steps: 31,
+ canvas_v3_metadata: {
+ document: { bbox: capturedBbox },
+ settings: {
+ strength: 0.6,
+ compositing: { maskBlur: 8 },
+ scaling: { height: 768, method: 'manual', width: 1024 },
+ },
+ },
+ },
+ });
+ });
+
+ it('captures current settings with the unchanged document after async export', async () => {
+ const harness = createHarness();
+ const exported = deferred<RasterCompositeExportResult>();
+ harness.exportRasterComposite.mockReturnValueOnce(exported.promise);
+ const save = saveCanvasToGallery({
+ engine: harness.engine,
+ getProject: harness.getProject,
+ project: harness.project,
+ region: 'canvas',
+ scopedDefaults: {},
+ uploadImage: harness.uploadImage,
+ });
+
+ await vi.waitFor(() => expect(harness.exportRasterComposite).toHaveBeenCalledOnce());
+ const edited = structuredClone(harness.project);
+ edited.canvas.document = harness.project.canvas.document;
+ Object.assign(getProjectWidgetInstance(edited, 'generate')!.state.values, {
+ positivePrompt: 'edited during export',
+ steps: 51,
+ });
+ getProjectWidgetInstance(edited, 'canvas')!.state.values.denoisingStrength = 0.2;
+ harness.setProject(edited);
+ exported.resolve({ blob: defaultBlob, rect: defaultRect, status: 'ok' });
+
+ await expect(save).resolves.toMatchObject({ status: 'saved' });
+ expect(harness.uploadImage.mock.calls[0]?.[1]?.metadata).toMatchObject({
+ positive_prompt: 'edited during export',
+ steps: 51,
+ canvas_v3_metadata: { document: { bbox: defaultRect }, settings: { strength: 0.2 } },
+ });
+ });
+
+ it.each(['closed-project', 'mismatched-document', 'expired-account'] as const)(
+ 'does not upload a %s after pending paint uploads finish',
+ async (reason) => {
+ const harness = createHarness();
+ const flush = deferred<void>();
+ harness.flushPendingUploads.mockReturnValueOnce(flush.promise);
+ const save = saveCanvasToGallery({
+ engine: harness.engine,
+ getProject: harness.getProject,
+ project: harness.project,
+ region: 'canvas',
+ scopedDefaults: {},
+ uploadImage: harness.uploadImage,
+ });
+
+ await vi.waitFor(() => expect(harness.flushPendingUploads).toHaveBeenCalledOnce());
+ if (reason === 'closed-project') {
+ harness.getProject.mockReturnValue(null);
+ } else if (reason === 'mismatched-document') {
+ harness.getDocument.mockReturnValue(createDocument({ ...defaultRect, x: 999 }));
+ } else {
+ accountLifecycle.activate('another-account');
+ }
+ flush.resolve();
+
+ await expect(save).resolves.toEqual({ status: 'stale' });
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ }
+ );
+
+ it.each(['edited-document', 'project-document-mismatch', 'closed-project'] as const)(
+ 'does not upload a %s after async export',
+ async (reason) => {
+ const harness = createHarness();
+ const exported = deferred<RasterCompositeExportResult>();
+ harness.exportRasterComposite.mockReturnValueOnce(exported.promise);
+ const save = saveCanvasToGallery({
+ engine: harness.engine,
+ getProject: harness.getProject,
+ project: harness.project,
+ region: 'canvas',
+ scopedDefaults: {},
+ uploadImage: harness.uploadImage,
+ });
+
+ await vi.waitFor(() => expect(harness.exportRasterComposite).toHaveBeenCalledOnce());
+ if (reason === 'edited-document') {
+ harness.setDocument(createDocument({ ...defaultRect, x: 999 }));
+ } else if (reason === 'project-document-mismatch') {
+ const edited = structuredClone(harness.project);
+ edited.canvas.document.bbox.x = 999;
+ harness.getProject.mockReturnValue(edited);
+ } else {
+ harness.getProject.mockReturnValue(null);
+ }
+ exported.resolve({ blob: defaultBlob, rect: defaultRect, status: 'ok' });
+
+ await expect(save).resolves.toEqual({ status: 'stale' });
+ expect(harness.uploadImage).not.toHaveBeenCalled();
+ }
+ );
+
it.each([
['board-physical', 'board-physical'],
['none', undefined],
['by_date:2026-07-15', undefined],
])('normalizes selected board %s to upload board %s', async (selectedBoardId, expectedBoardId) => {
- const harness = createHarness();
+ const harness = createHarness({ project: createProject(selectedBoardId) });
await saveCanvasToGallery({
engine: harness.engine,
- project: createProject(selectedBoardId),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -224,7 +434,7 @@ describe('saveCanvasToGallery', () => {
['a date bucket is selected', 'by_date:2026-07-15'],
])('saves to the project board when %s', async (_case, selectedBoardId) => {
const harness = createHarness();
- const project = createProject();
+ const project = harness.project;
const gallery = getProjectWidgetInstance(project, 'gallery')!;
gallery.state.values = {
@@ -236,6 +446,7 @@ describe('saveCanvasToGallery', () => {
await saveCanvasToGallery({
engine: harness.engine,
+ getProject: harness.getProject,
project,
region: 'canvas',
scopedDefaults: {},
@@ -252,24 +463,29 @@ describe('saveCanvasToGallery', () => {
name: 'Unsupported Model',
type: 'main',
};
- const harness = createHarness();
-
- await saveCanvasToGallery({
- engine: harness.engine,
+ const harness = createHarness({
project: createProject('none', {
model: unsupportedModel,
modelKey: unsupportedModel.key,
negativePromptEnabled: false,
}),
+ });
+
+ await saveCanvasToGallery({
+ engine: harness.engine,
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
});
const metadata = harness.uploadImage.mock.calls[0]?.[1]?.metadata;
+ expect(metadata).not.toHaveProperty('seed');
+ expect(metadata).not.toHaveProperty('generation_mode');
expect(metadata).not.toHaveProperty('model');
expect(metadata).not.toHaveProperty('negative_prompt');
- expect(metadata).toMatchObject({ height: 456, positive_prompt: 'a canvas prompt', seed: 123, width: 123 });
+ expect(metadata).toMatchObject({ height: 456, positive_prompt: 'a canvas prompt', width: 123 });
});
it.each(['empty', 'stale', 'not-ready'] as const)('returns %s without uploading', async (status) => {
@@ -278,7 +494,8 @@ describe('saveCanvasToGallery', () => {
await expect(
saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -294,7 +511,8 @@ describe('saveCanvasToGallery', () => {
await expect(
saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'bbox',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -312,7 +530,8 @@ describe('saveCanvasToGallery', () => {
await expect(
saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -329,7 +548,8 @@ describe('saveCanvasToGallery', () => {
await expect(
saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
@@ -344,7 +564,8 @@ describe('saveCanvasToGallery', () => {
harness.exportRasterComposite.mockReturnValueOnce(exportResult.promise);
const save = saveCanvasToGallery({
engine: harness.engine,
- project: createProject(),
+ getProject: harness.getProject,
+ project: harness.project,
region: 'canvas',
scopedDefaults: {},
uploadImage: harness.uploadImage,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
index 1c41857362..47211b155d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts
@@ -1,4 +1,11 @@
-import type { AdjustmentRefusal, LayerUnreadable } from '@workbench/canvas-engine/api';
+import type { ControlLayerGraphInput } from '@features/generation/graph';
+import type { ModelConfig } from '@features/models';
+import type {
+ AdjustmentRefusal,
+ CanvasDocumentContractV3,
+ CanvasNodeContract,
+ LayerUnreadable,
+} from '@workbench/canvas-engine/api';
import type { Rect } from '@workbench/canvas-engine/types';
import type { Project } from '@workbench/projectContracts';
import type { ScopedDefaults } from '@workbench/settings/contracts';
@@ -11,12 +18,16 @@ import {
isSupportedGenerateModel,
normalizeGenerateWidgetValues,
} from '@features/generation/settings';
+import { getModelsSnapshot } from '@features/models';
import { queryClient } from '@platform/query/client';
import {
assertAccountScopeCurrent,
captureAccountScope,
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
+import { readCanvasCompositingSettings } from '@workbench/widgets/canvas/invoke/canvasCompositing';
+import { readCanvasScaling } from '@workbench/widgets/canvas/invoke/canvasScaling';
+import { readCanvasDenoisingStrength } from '@workbench/widgets/canvas/invoke/canvasStrength';
import { getProjectWidgetValues, getResolvedProjectWidgetValues } from '@workbench/widgetState';
import type { CanvasCompositeExportEngine, CanvasCompositeRegion } from './exportCanvasComposite';
@@ -33,6 +44,54 @@ export type SaveCanvasToGalleryResult =
| LayerUnreadable
| AdjustmentRefusal;
+/** Image metadata is independent of project persistence: no staging, history, project ids or stored media URLs. */
+export const recordCanvasMetadata = (
+ document: CanvasDocumentContractV3,
+ {
+ controls,
+ models = [],
+ settings = {},
+ }: {
+ controls?: readonly ControlLayerGraphInput[];
+ models?: readonly ModelConfig[];
+ settings?: Record<string, unknown>;
+ } = {}
+): Record<string, unknown> => {
+ const controlModels: Record<string, unknown> = Object.create(null);
+ const copy = structuredClone(document);
+ const controlsById = new Map(controls?.map((control) => [control.id, control]));
+ const modelsByKey = new Map(models.map((model) => [model.key, model]));
+ const visit = (nodes: CanvasNodeContract[]): void => {
+ for (const node of nodes) {
+ if (node.type === 'group') {
+ visit(node.children);
+ } else if (node.type === 'control') {
+ const executed = controlsById.get(node.id);
+ const model = executed?.model ?? modelsByKey.get(node.adapter.model ?? '');
+ if (model) {
+ controlModels[node.id] = toModelIdentifier({ ...model });
+ node.adapter.model = model.key;
+ }
+ if (executed) {
+ node.adapter.kind = executed.kind;
+ node.adapter.controlMode = executed.controlMode;
+ node.adapter.beginEndStepPct = [...executed.beginEndStepPct];
+ node.adapter.weight = executed.weight;
+ }
+ } else if (node.type === 'regional_guidance') {
+ for (const reference of node.referenceImages) {
+ if (reference.config.image) {
+ reference.config.image.imageUrl = '';
+ reference.config.image.thumbnailUrl = '';
+ }
+ }
+ }
+ }
+ };
+ Object.values(copy.stacks).forEach(visit);
+ return { controlModels, document: copy, settings: structuredClone(settings), version: 1 };
+};
+
const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, unknown> => {
const generateValues = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));
const dimensions = { height: rect.height, width: rect.width };
@@ -46,10 +105,24 @@ const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, u
return {
...dimensions,
+ metadata_source: 'canvas_save',
+ steps: generateValues.steps,
+ cfg_scale: generateValues.cfgScale,
+ cfg_rescale_multiplier: generateValues.cfgRescaleMultiplier,
+ scheduler: generateValues.scheduler,
+ clip_skip: generateValues.clipSkip,
+ seamless_x: generateValues.seamlessXAxis,
+ seamless_y: generateValues.seamlessYAxis,
+ loras: generateValues.loras.map((lora) => ({
+ model: toModelIdentifier(lora.model),
+ weight: lora.weight,
+ isEnabled: lora.isEnabled,
+ })),
+ ref_images: structuredClone(generateValues.referenceImages),
+ vae: generateValues.vae ? toModelIdentifier(generateValues.vae) : null,
...(isSupportedGenerateModel(generateValues.model) ? { model: toModelIdentifier(generateValues.model) } : {}),
...(generateValues.negativePromptEnabled ? { negative_prompt: effectivePrompts.negativePrompt } : {}),
positive_prompt: effectivePrompts.positivePrompt,
- seed: generateValues.seed,
};
};
@@ -85,13 +158,15 @@ export const resolveCanvasSaveBoardId = async (
export const saveCanvasToGallery = async (options: {
engine: CanvasCompositeExportEngine;
region: CanvasGallerySaveRegion;
+ /** The originating project's current immutable state, read after export to pair metadata with its document. */
+ getProject: (projectId: string) => Project | null;
project: Project;
/** The user's defaults captured with `project`: the destination follows the Gallery's resolved settings. */
scopedDefaults: ScopedDefaults;
uploadImage?: typeof uploadCanvasImage;
}): Promise<SaveCanvasToGalleryResult> => {
const owner = captureAccountScope();
- const { engine, project, region, scopedDefaults, uploadImage = uploadCanvasImage } = options;
+ const { engine, getProject, project, region, scopedDefaults, uploadImage = uploadCanvasImage } = options;
try {
const boardId = await resolveCanvasSaveBoardId(project, scopedDefaults);
@@ -102,13 +177,28 @@ export const saveCanvasToGallery = async (options: {
if (exported.status !== 'ok') {
return exported;
}
-
+ const capturedProject = getProject(project.id);
+ if (!capturedProject || capturedProject.canvas.document !== exported.document) {
+ return { status: 'stale' };
+ }
+ const canvasValues = getProjectWidgetValues(capturedProject, 'canvas');
+ const metadata = {
+ ...buildCanvasSaveMetadata(capturedProject, exported.rect),
+ canvas_v3_metadata: recordCanvasMetadata(exported.document, {
+ models: getModelsSnapshot().models,
+ settings: {
+ strength: readCanvasDenoisingStrength(canvasValues),
+ compositing: readCanvasCompositingSettings(canvasValues),
+ scaling: readCanvasScaling(canvasValues),
+ },
+ }),
+ };
const uploaded = await uploadImage(exported.blob, {
boardId,
fileName: region === 'canvas' ? 'canvas.png' : 'bbox.png',
imageCategory: 'general',
isIntermediate: false,
- metadata: buildCanvasSaveMetadata(project, exported.rect),
+ metadata,
signal: owner.signal,
});
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index a867c1f5f7..ebc7e3708f 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -221,6 +221,12 @@ export const useRegisterFirstPartyCommands = () => {
return project ? getProjectWidgetValues(project, 'generate') : {};
},
+ canvasTarget: {
+ commands,
+ projectId: activeProject.id,
+ getProject: () =>
+ queries.isActiveProject(activeProject.id) ? (queries.getProject(activeProject.id) ?? null) : null,
+ },
image,
isCanvasFrame: activeProject.invocation.sourceId === 'canvas',
kind,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts
new file mode 100644
index 0000000000..aa8818ec74
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts
@@ -0,0 +1,1373 @@
+import type * as GalleryModule from '@features/gallery';
+import type { GalleryImage } from '@features/gallery';
+import type * as GalleryBackendModule from '@features/gallery/data/backend';
+import type { MainModelConfig } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/api';
+import type { TFunction } from 'i18next';
+
+import { compileCanvasGraph } from '@features/generation/canvasGraph';
+import { setArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
+import { getDefaultGenerateSettings } from '@features/generation/settings';
+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { QueryClient } from '@tanstack/react-query';
+import * as CanvasOperations from '@workbench/canvas-operations/api';
+import { recordCanvasMetadata } from '@workbench/canvas-operations/saveCanvasToGallery';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({ metadata: vi.fn(), resolveMany: vi.fn(), makeCanvasAsset: vi.fn() }));
+vi.mock('@features/gallery', async (original) => ({
+ ...(await original<typeof GalleryModule>()),
+ galleryImages: api,
+ galleryDurability: { makeCanvasAsset: api.makeCanvasAsset },
+}));
+vi.mock('@features/gallery/data/backend', async (original) => ({
+ ...(await original<typeof GalleryBackendModule>()),
+ getGalleryImageMetadata: api.metadata,
+}));
+
+import { commitCanvasRecall, prepareCanvasRecall } from './canvasRecall';
+import { executeImageRecall } from './executeImageRecall';
+import { executeRecallParameters } from './executeRecallParameters';
+
+const main: MainModelConfig = { base: 'sdxl', key: 'main', name: 'SDXL', type: 'main' };
+const controlModel = {
+ base: 'sdxl',
+ key: 'control-installed',
+ name: 'Edges',
+ type: 'controlnet',
+ hash: 'control-hash',
+} as ModelConfig;
+const models = [main as ModelConfig, controlModel];
+const t = ((key: string) => key) as TFunction;
+const base = {
+ id: 'layer',
+ name: 'Authored layer',
+ isEnabled: true,
+ isLocked: false,
+ opacity: 0.7,
+ blendMode: 'normal' as const,
+ transform: { x: -40, y: 70, scaleX: 0.5, scaleY: -1, rotation: 0.2 },
+};
+const source = { type: 'image' as const, image: { imageName: 'map.png', width: 640, height: 480 } };
+const control = (): CanvasControlLayerContract => ({
+ ...base,
+ id: 'control',
+ type: 'control',
+ source,
+ withTransparencyEffect: true,
+ adapter: { kind: 'controlnet', model: null, weight: 0.5, beginEndStepPct: [0.2, 0.8], controlMode: 'more_control' },
+});
+const document = () => ({
+ ...createEmptyCanvasDocument(2048, 1536),
+ bbox: { x: -128, y: 96, width: 768, height: 1024 },
+ stacks: {
+ raster: [{ ...base, id: 'raster', type: 'raster', source } as CanvasLayerContract],
+ control: [control()],
+ inpaint_mask: [
+ {
+ ...base,
+ id: 'mask',
+ type: 'inpaint_mask',
+ mask: {
+ bitmap: { imageName: 'mask.png', width: 320, height: 200 },
+ offset: { x: -20, y: 40 },
+ fill: { style: 'solid', color: 'red' },
+ },
+ noise: { level: 0.4, isEnabled: true },
+ } as CanvasLayerContract,
+ ],
+ regional_guidance: [
+ {
+ ...base,
+ id: 'region',
+ type: 'regional_guidance',
+ positivePrompt: 'A bird',
+ negativePrompt: 'blue',
+ autoNegative: true,
+ mask: { bitmap: null, fill: { style: 'grid', color: 'red' } },
+ referenceImages: [],
+ } as CanvasLayerContract,
+ ],
+ },
+});
+const record = () =>
+ recordCanvasMetadata(document(), {
+ controls: [
+ {
+ id: 'control',
+ imageName: 'executed-composite.png',
+ model: controlModel,
+ kind: 'controlnet',
+ weight: 0.5,
+ beginEndStepPct: [0.2, 0.8],
+ controlMode: 'more_control',
+ },
+ ],
+ settings: { strength: 0.35 },
+ });
+const largeRecord = () => {
+ const document = createEmptyCanvasDocument();
+ document.stacks.raster = Array.from({ length: 2006 }, (_, index) => ({
+ ...base,
+ id: `layer-${index}`,
+ name: `Layer ${index}`,
+ type: 'raster',
+ source: {
+ type: 'image',
+ image: { imageName: `asset-${index === 2005 ? 0 : index}.png`, width: 64, height: 64 },
+ },
+ }));
+ return recordCanvasMetadata(document, { settings: { strength: 0.35 } });
+};
+const targetFor = (store: ReturnType<typeof createWorkbenchStore>) => {
+ const projectId = store.queries.getSnapshot().activeProject.id;
+ return { commands: store.commands, projectId, getProject: () => store.queries.getProject(projectId) ?? null };
+};
+
+seedArchitectureCapabilities();
+beforeEach(() => {
+ accountLifecycle.activate('canvas-recall-tests');
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ api.metadata.mockReset();
+ api.makeCanvasAsset.mockReset().mockResolvedValue(undefined);
+ api.resolveMany.mockImplementation((names: string[]) => Promise.resolve(names.map((imageName) => ({ imageName }))));
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('canvas record to recall', () => {
+ it('recalls a compiled output with executed automatic controls, transformed sources, masks, regions and authored geometry', async () => {
+ const authored = document();
+ const canvasRecord = record();
+ const compiled = compileCanvasGraph({
+ model: main,
+ settings: { ...getDefaultGenerateSettings(main), seed: 12 },
+ projectSettings: { useCpuNoise: true, useNsfwChecker: false, useWatermark: false },
+ mode: 'txt2img',
+ destination: 'gallery',
+ bbox: authored.bbox,
+ compositeImageName: null,
+ compositing: DEFAULT_CANVAS_COMPOSITING,
+ strength: 0.35,
+ canvasMetadata: canvasRecord,
+ controlLayers: [
+ {
+ id: 'control',
+ imageName: 'executed-composite.png',
+ model: controlModel,
+ kind: 'controlnet',
+ weight: 0.5,
+ beginEndStepPct: [0.2, 0.8],
+ controlMode: 'more_control',
+ },
+ ],
+ });
+ const metadata = Object.values(compiled.backendGraph.nodes).find((node) => node.type === 'core_metadata')!;
+ expect(metadata.control_layers).toEqual([
+ {
+ type: 'controlnet',
+ layer_id: 'control',
+ model: controlModel,
+ image: { image_name: 'executed-composite.png', width: 768, height: 1024 },
+ position: { x: -128, y: 96 },
+ weight: 0.5,
+ begin_step_percent: 0.2,
+ end_step_percent: 0.8,
+ control_mode: 'more_control',
+ },
+ ]);
+ expect(metadata.controlnets).toEqual([
+ {
+ image: { image_name: 'executed-composite.png', width: 768, height: 1024 },
+ control_model: controlModel,
+ control_weight: 0.5,
+ begin_step_percent: 0.2,
+ end_step_percent: 0.8,
+ control_mode: 'more_control',
+ },
+ ]);
+ // Later UI mutations cannot rewrite the captured record.
+ authored.stacks.control[0]!.adapter.weight = 1.5;
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const previous = target.getProject()!.canvas.document;
+ const plan = await prepareCanvasRecall({ metadata, model: main, models, owner: captureAccountScope() });
+ expect(plan.problems).toEqual([]);
+ expect(commitCanvasRecall({ plan, target, expectedDocument: previous, restorePointName: 'Before recall' })).toBe(
+ true
+ );
+ const recalled = target.getProject()!;
+ expect(recalled.canvas.document.bbox).toEqual({ x: -128, y: 96, width: 768, height: 1024 });
+ expect(recalled.canvas.document.stacks.control[0]).toMatchObject({
+ source,
+ transform: base.transform,
+ adapter: { model: 'control-installed', weight: 0.5 },
+ });
+ expect(recalled.canvas.document.stacks.inpaint_mask[0]).toMatchObject({
+ mask: { offset: { x: -20, y: 40 } },
+ noise: { level: 0.4 },
+ });
+ expect(recalled.canvas.document.stacks.regional_guidance[0]).toMatchObject({
+ positivePrompt: 'A bird',
+ autoNegative: true,
+ });
+ expect(recalled.canvas.snapshots.at(-1)?.document).toEqual(previous);
+ expect(getProjectWidgetValues(recalled, 'canvas').denoisingStrength).toBe(0.35);
+ expect(api.resolveMany).toHaveBeenCalledOnce();
+ expect(api.resolveMany.mock.calls[0]![0].sort()).toEqual(['map.png', 'mask.png']);
+ });
+
+ it.each([false, true])('resolves a large record in bounded batches, with missing assets: %s', async (missing) => {
+ const missingNames = missing ? new Set(['asset-1000.png', 'asset-2004.png']) : new Set<string>();
+ api.resolveMany.mockImplementation((names: string[]) => {
+ if (names.length > 1000) {
+ return Promise.reject(new Error('422: too many image names'));
+ }
+ return Promise.resolve(names.filter((name) => !missingNames.has(name)).map((imageName) => ({ imageName })));
+ });
+ const plan = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: largeRecord() },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(api.resolveMany.mock.calls.map(([names]) => names.length)).toEqual([1000, 1000, 5]);
+ const requestedNames = api.resolveMany.mock.calls.flatMap(([names]) => names);
+ expect(requestedNames).toHaveLength(2005);
+ expect(new Set(requestedNames).size).toBe(2005);
+ expect(plan.document?.stacks.raster).toHaveLength(missing ? 2004 : 2006);
+ expect(plan.problems).toEqual(missing ? ['Layer 1000', 'Layer 2004'] : []);
+ expect(plan.partial).toBe(missing);
+ });
+
+ it.each(['account', 'project', 'document'] as const)(
+ 'stops large-record asset reads when the originating %s changes between batches',
+ async (change) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const originalDocument = target.getProject()!.canvas.document;
+ let release!: (images: { imageName: string }[]) => void;
+ api.resolveMany.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ })
+ );
+ const owner = captureAccountScope();
+ const pending = prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: largeRecord() },
+ model: main,
+ models,
+ owner,
+ isCurrent: () =>
+ store.queries.isActiveProject(target.projectId) && target.getProject()?.canvas.document === originalDocument,
+ });
+ expect(api.resolveMany).toHaveBeenCalledOnce();
+ if (change === 'account') {
+ accountLifecycle.activate('another-account');
+ } else if (change === 'project') {
+ store.commands.projects.create();
+ } else {
+ store.commands.canvas.apply(target.projectId, {
+ type: 'setCanvasBbox',
+ bbox: { ...originalDocument.bbox, x: 100 },
+ });
+ }
+ release(Array.from({ length: 1000 }, (_, index) => ({ imageName: `asset-${index}.png` })));
+ if (change === 'account') {
+ await expect(pending).rejects.toThrow();
+ } else {
+ const plan = await pending;
+ expect(plan.document).toBeNull();
+ expect(plan.settings).toEqual({});
+ expect(plan.problems).toEqual(['canvas-changed']);
+ }
+ expect(api.resolveMany).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('resolves a reinstalled portable control identity and refuses incompatible, ambiguous and missing assets without clearing work', async () => {
+ const saved = record();
+ const reinstalled = { ...controlModel, key: 'reinstalled' };
+ const restored = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: saved },
+ model: main,
+ models: [reinstalled],
+ owner: captureAccountScope(),
+ });
+ expect(restored.document?.stacks.control[0]).toMatchObject({ adapter: { model: 'reinstalled' } });
+ api.resolveMany.mockResolvedValue([{ imageName: 'mask.png' }]);
+ const partial = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: saved },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ const store = createWorkbenchStore(),
+ target = targetFor(store),
+ original = target.getProject()!.canvas.document;
+ const originalIds = original.stacks.inpaint_mask.map((node) => node.id);
+ expect(partial.partial).toBe(true);
+ commitCanvasRecall({ plan: partial, target, expectedDocument: original, restorePointName: 'Before recall' });
+ expect(target.getProject()!.canvas.document.stacks.inpaint_mask.map((node) => node.id)).toEqual(
+ expect.arrayContaining(originalIds)
+ );
+ expect(target.getProject()!.canvas.snapshots).toHaveLength(0);
+ api.resolveMany.mockImplementation((names: string[]) => Promise.resolve(names.map((imageName) => ({ imageName }))));
+ for (const catalog of [
+ [{ ...controlModel, base: 'sd-1' }],
+ [],
+ [reinstalled, { ...reinstalled, key: 'duplicate' }],
+ ]) {
+ const result = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: saved },
+ model: main,
+ models: catalog,
+ owner: captureAccountScope(),
+ });
+ expect(result.document?.stacks.control).toEqual([]);
+ expect(result.partial).toBe(true);
+ }
+ });
+
+ it('distinguishes absence, explicit empty, malformed and future records; fences changes and project closure', async () => {
+ const store = createWorkbenchStore(),
+ target = targetFor(store),
+ before = target.getProject()!.canvas.document;
+ const prepare = (metadata: unknown) =>
+ prepareCanvasRecall({ metadata, model: main, models, owner: captureAccountScope() });
+ expect((await prepare({})).document).toBeNull();
+ for (const raw of [null, { version: 2 }, { version: 1, document: { version: 3, stacks: { control: 'wrong' } } }]) {
+ const plan = await prepare({ canvas_v3_metadata: raw });
+ expect(plan.document).toBeNull();
+ expect(plan.problems).not.toEqual([]);
+ }
+ const empty = await prepare({ canvas_v3_metadata: recordCanvasMetadata(createEmptyCanvasDocument()) });
+ expect(empty.document).not.toBeNull();
+ expect(
+ commitCanvasRecall({
+ plan: empty,
+ target: { ...target, getProject: () => null },
+ expectedDocument: before,
+ restorePointName: 'Before recall',
+ })
+ ).toBe(false);
+ store.commands.canvas.apply(target.projectId, { type: 'setCanvasBbox', bbox: { ...before.bbox, x: 100 } });
+ expect(
+ commitCanvasRecall({ plan: empty, target, expectedDocument: before, restorePointName: 'Before recall' })
+ ).toBe(false);
+ expect(target.getProject()!.canvas.document.bbox.x).toBe(100);
+ const latest = target.getProject()!.canvas.document;
+ expect(
+ commitCanvasRecall({
+ plan: await prepare({ canvas_v3_metadata: recordCanvasMetadata(createEmptyCanvasDocument()) }),
+ target,
+ expectedDocument: latest,
+ restorePointName: 'Before recall',
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.inpaint_mask).toEqual([]);
+ });
+
+ it.each(['all', 'remix'] as const)(
+ 'restores canvas through the shared image %s action used by gallery, preview and staging',
+ async (kind) => {
+ const store = createWorkbenchStore(),
+ target = targetFor(store);
+ api.metadata.mockResolvedValue({ canvas_v3_metadata: record() });
+ const image = { imageName: 'output.png', width: 768, height: 1024 } as GalleryImage;
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image,
+ kind,
+ models,
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.control[0]).toMatchObject({
+ adapter: { model: controlModel.key },
+ });
+ }
+ );
+
+ it.each(['all', 'remix', 'api'] as const)(
+ 'preserves the whole Canvas and recalls valid Generate fields when the %s asset lookup fails',
+ async (surface) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const before = target.getProject()!;
+ const canvasSettings = getProjectWidgetValues(before, 'canvas');
+ const notifications = vi.spyOn(store.commands.notifications, 'add');
+ const feedbackT = ((key: string, values?: Record<string, string>) =>
+ key.endsWith('image-lookup-failed')
+ ? 'Canvas images could not be checked'
+ : (values?.items ?? values?.detail ?? key)) as TFunction;
+ const parameters = {
+ positive_prompt: 'A recalled landscape',
+ seed: 456,
+ steps: 31,
+ denoise_strength: 0.4,
+ control_layers: [{ model_key: controlModel.key, image: { image_name: 'map.png', width: 640, height: 480 } }],
+ };
+ api.metadata.mockResolvedValue({ ...parameters, canvas_v3_metadata: largeRecord() });
+ if (surface === 'api') {
+ api.resolveMany.mockRejectedValueOnce(new TypeError('Failed to fetch'));
+ } else {
+ // The second batch fails after some assets were verified; none of the Canvas may replace authored work.
+ api.resolveMany.mockImplementationOnce((names: string[]) =>
+ Promise.resolve(names.map((imageName) => ({ imageName })))
+ );
+ api.resolveMany.mockRejectedValueOnce(new ApiError('Image service unavailable', 503));
+ }
+ const applied =
+ surface === 'api'
+ ? await executeRecallParameters({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ models,
+ owner: captureAccountScope(),
+ parameters,
+ projectId: target.projectId,
+ t: feedbackT,
+ })
+ : await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'out.png', width: 512, height: 512 } as GalleryImage,
+ kind: surface,
+ models,
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t: feedbackT,
+ });
+ expect(applied).toBe(true);
+ const after = target.getProject()!;
+ expect(after.canvas).toBe(before.canvas);
+ expect(getProjectWidgetValues(after, 'canvas')).toEqual(canvasSettings);
+ expect(getProjectWidgetValues(after, 'generate')).toMatchObject({
+ positivePrompt: 'A recalled landscape',
+ steps: 31,
+ });
+ if (surface !== 'remix') {
+ expect(getProjectWidgetValues(after, 'generate').seed).toBe(456);
+ }
+ expect(notifications).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'info', message: 'Canvas images could not be checked' })
+ );
+ expect(api.resolveMany).toHaveBeenCalledTimes(surface === 'api' ? 1 : 2);
+ }
+ );
+
+ it.each([
+ ['gallery', 'account'],
+ ['api', 'account'],
+ ['gallery', 'project'],
+ ['api', 'project'],
+ ] as const)(
+ 'keeps the %s caller inert when its originating %s changes before lookup rejects',
+ async (surface, change) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const owner = captureAccountScope();
+ let active = true;
+ const canvasTarget = { ...target, getProject: () => (active ? target.getProject() : null) };
+ const notifications = vi.spyOn(store.commands.notifications, 'add');
+ const reportError = vi.spyOn(store.commands.notifications, 'reportError');
+ const settings = vi.spyOn(store.commands.generation, 'setSettings');
+ let reject!: (error: unknown) => void;
+ api.resolveMany.mockImplementationOnce(
+ () =>
+ new Promise((_, rejectLookup) => {
+ reject = rejectLookup;
+ })
+ );
+ const parameters = {
+ positive_prompt: 'Do not recall',
+ denoise_strength: 0.4,
+ control_layers: [{ model_key: controlModel.key, image: { image_name: 'map.png', width: 640, height: 480 } }],
+ };
+ api.metadata.mockResolvedValue({ ...parameters, canvas_v3_metadata: record() });
+ const pending =
+ surface === 'api'
+ ? executeRecallParameters({
+ commands: store.commands,
+ canvasTarget,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ models,
+ owner,
+ parameters,
+ projectId: target.projectId,
+ t,
+ })
+ : executeImageRecall({
+ commands: store.commands,
+ canvasTarget,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'out.png', width: 512, height: 512 } as GalleryImage,
+ kind: 'all',
+ models,
+ owner,
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t,
+ });
+ await vi.waitFor(() => expect(api.resolveMany).toHaveBeenCalled());
+ const before = target.getProject();
+ if (change === 'account') {
+ accountLifecycle.activate('another-account');
+ } else {
+ active = false;
+ }
+ reject(new ApiError('Image service unavailable', 503));
+ expect(await pending).toBe(false);
+ expect(target.getProject()).toBe(before);
+ expect(settings).not.toHaveBeenCalled();
+ expect(notifications).not.toHaveBeenCalled();
+ expect(reportError).not.toHaveBeenCalled();
+ }
+ );
+
+ it('does not classify asset-mapping programmer errors as unavailable images', async () => {
+ const failure = new TypeError('Cannot read properties of undefined');
+ api.resolveMany.mockRejectedValueOnce(failure);
+ await expect(
+ prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: record() },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ })
+ ).rejects.toBe(failure);
+ });
+
+ it('recalls API controls using processed maps and denoise strength, preserving other stacks, then appends or explicitly clears only controls', async () => {
+ const store = createWorkbenchStore(),
+ target = targetFor(store),
+ originalMask = target.getProject()!.canvas.document.stacks.inpaint_mask;
+ const execute = (parameters: Record<string, unknown>) =>
+ executeRecallParameters({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ models,
+ owner: captureAccountScope(),
+ parameters,
+ projectId: target.projectId,
+ t,
+ });
+ const control = {
+ model_key: controlModel.key,
+ image: { image_name: 'original.png', width: 640, height: 480 },
+ processed_image: { image_name: 'map.png', width: 640, height: 480 },
+ weight: 0.6,
+ };
+ expect(await execute({ control_layers: [control], denoise_strength: 0.45 })).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.control[0]).toMatchObject({ source, adapter: { weight: 0.6 } });
+ expect(target.getProject()!.canvas.document.stacks.inpaint_mask).toEqual(originalMask);
+ expect(await execute({ append: true, control_layers: [control] })).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.control).toHaveLength(2);
+ expect(await execute({ control_layers: [] })).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.control).toEqual([]);
+ expect(target.getProject()!.canvas.document.stacks.inpaint_mask).toEqual(originalMask);
+ expect(await execute({ control_layers: [control] })).toBe(true);
+ expect(await execute({ control_layers: null, denoise_strength: null })).toBe(true);
+ expect(target.getProject()!.canvas.document.stacks.control).toEqual([]);
+ expect(getProjectWidgetValues(target.getProject()!, 'canvas').denoisingStrength).toBe(0.75);
+ const beforeMalformed = target.getProject()!.canvas.document;
+ expect(await execute({ control_layers: [{ ...control, weight: 'not a weight' }] })).toBe(false);
+ expect(target.getProject()!.canvas.document).toBe(beforeMalformed);
+ });
+
+ it('reads legacy image-backed controls, rasters and masks without treating the legacy empty record as Clear Canvas', async () => {
+ const legacyBase = {
+ id: 'old',
+ name: 'Old layer',
+ isEnabled: true,
+ isLocked: false,
+ position: { x: -10, y: 20 },
+ opacity: 1,
+ objects: [{ id: 'image', type: 'image', image: { image_name: 'map.png', width: 640, height: 480 } }],
+ };
+ const legacy = {
+ rasterLayers: [{ ...legacyBase, id: 'raster' }],
+ controlLayers: [
+ {
+ ...legacyBase,
+ id: 'control',
+ controlAdapter: {
+ type: 'controlnet',
+ model: controlModel,
+ weight: 0.75,
+ controlMode: 'balanced',
+ beginEndStepPct: [0, 1],
+ },
+ },
+ ],
+ inpaintMasks: [{ ...legacyBase, id: 'mask', fill: { style: 'grid', color: { r: 255, g: 0, b: 0 } } }],
+ regionalGuidance: [],
+ };
+ const plan = await prepareCanvasRecall({
+ metadata: { canvas_v2_metadata: legacy },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.problems).toEqual([]);
+ expect(plan.document?.stacks.control[0]).toMatchObject({
+ transform: { x: -10, y: 20 },
+ adapter: { model: controlModel.key },
+ });
+ expect(plan.document?.stacks.inpaint_mask[0]).toMatchObject({ mask: { bitmap: { imageName: 'map.png' } } });
+ const empty = await prepareCanvasRecall({
+ metadata: { canvas_v2_metadata: { rasterLayers: [], controlLayers: [], inpaintMasks: [], regionalGuidance: [] } },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(empty.document).toBeNull();
+ });
+
+ it('rejects account-stale lookups before commit', async () => {
+ let release!: (value: unknown[]) => void;
+ api.resolveMany.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ })
+ );
+ const pending = prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: record() },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ accountLifecycle.activate('another-account');
+ release([{ imageName: 'map.png' }, { imageName: 'mask.png' }]);
+ await expect(pending).rejects.toThrow();
+ });
+});
+
+it('keeps a staged generation session while adding recalled layers and refuses a stale project after asset lookup', async () => {
+ const store = createWorkbenchStore(),
+ target = targetFor(store);
+ const project = target.getProject()!;
+ store.commands.canvas.appendStagingCandidate({
+ projectId: target.projectId,
+ candidate: {
+ imageName: 'staged.png',
+ imageUrl: '',
+ thumbnailUrl: '',
+ height: 100,
+ width: 100,
+ queuedAt: '',
+ sourceQueueItemId: '',
+ placement: { x: 0, y: 0, width: 100, height: 100, opacity: 1 },
+ },
+ });
+ const before = target.getProject()!;
+ const plan = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: record() },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ commitCanvasRecall({ plan, target, expectedDocument: before.canvas.document, restorePointName: 'Before recall' });
+ expect(target.getProject()!.canvas.stagingArea).toEqual(before.canvas.stagingArea);
+ expect(target.getProject()!.canvas.documentRevision).toBe(project.canvas.documentRevision);
+ expect(plan.problems).toContain('canvas-pending-results');
+ expect(target.getProject()!.canvas.document.stacks.control).toHaveLength(1);
+
+ let release!: (value: unknown[]) => void;
+ api.resolveMany.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ })
+ );
+ api.metadata.mockResolvedValue({
+ positive_prompt: 'do not apply to a different project',
+ canvas_v3_metadata: record(),
+ });
+ let active = true;
+ api.resolveMany.mockClear();
+ const pending = executeImageRecall({
+ commands: store.commands,
+ canvasTarget: { ...target, getProject: () => (active ? target.getProject() : null) },
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'out.png' } as GalleryImage,
+ kind: 'all',
+ models,
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t,
+ });
+ await vi.waitFor(() => expect(api.resolveMany).toHaveBeenCalled());
+ const current = target.getProject();
+ active = false;
+ release([{ imageName: 'map.png' }, { imageName: 'mask.png' }]);
+ expect(await pending).toBe(false);
+ expect(target.getProject()).toBe(current);
+});
+
+it('recalls complete Canvas processing settings through their owner bounds and skips damaged control values', async () => {
+ const saved = recordCanvasMetadata(document(), {
+ models: [controlModel],
+ settings: {
+ strength: 0.6,
+ compositing: {
+ ...DEFAULT_CANVAS_COMPOSITING,
+ infillTileSize: 64,
+ infillPatchmatchDownscaleSize: 10,
+ maskBlur: 48,
+ coherenceMode: 'Staged',
+ },
+ scaling: { method: 'manual', width: 1536, height: 768 },
+ },
+ });
+ const plan = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: saved },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.settings).toMatchObject({
+ denoisingStrength: 0.6,
+ infillTileSize: 64,
+ infillPatchmatchDownscaleSize: 10,
+ maskBlur: 48,
+ coherenceMode: 'Staged',
+ scaleMethod: 'manual',
+ scaledWidth: 1536,
+ scaledHeight: 768,
+ });
+ const damaged = record();
+ const raw = damaged.document as ReturnType<typeof document>;
+ raw.stacks.control[0]!.adapter.weight = Number.NaN;
+ const malformed = await prepareCanvasRecall({
+ metadata: { canvas_v3_metadata: damaged },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(malformed.document?.stacks.control).toEqual([]);
+ expect(malformed.partial).toBe(true);
+ expect(malformed.document?.stacks.raster).toHaveLength(1);
+});
+
+const standaloneControl = () => ({
+ control_model: { base: 'sdxl', type: 'controlnet', hash: 'control-hash', key: 'old-install', name: 'Edges' },
+ image: { image_name: 'original.png' },
+ processed_image: { image_name: 'processed.png' },
+ control_weight: 0.65,
+ begin_step_percent: 0.15,
+ end_step_percent: 0.85,
+ control_mode: 'more_control',
+});
+
+it.each(['all', 'remix'] as const)(
+ 'recalls standalone name-only controls through Gallery %s with actual map dimensions and a restore point',
+ async (kind) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ target.commands.canvas.apply(target.projectId, { type: 'replaceCanvasDocument', document: document() });
+ const before = target.getProject()!.canvas.document;
+ const t2i = { base: 'sdxl', type: 't2i_adapter', key: 't2i', name: 'Sketch' } as ModelConfig;
+ api.metadata.mockResolvedValue({
+ width: 1024,
+ height: 768,
+ controlnets: [standaloneControl()],
+ t2iAdapters: [
+ {
+ t2i_adapter_model: t2i,
+ image: { image_name: 'sketch.png' },
+ weight: 0.4,
+ begin_step_percent: 0,
+ end_step_percent: 0.6,
+ },
+ ],
+ });
+ api.resolveMany.mockImplementation((names: string[]) =>
+ Promise.resolve(names.map((imageName) => ({ imageName, width: 512, height: 256 })))
+ );
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'legacy.png', width: 1024, height: 768 } as GalleryImage,
+ kind,
+ models: [...models, t2i],
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(api.resolveMany).toHaveBeenCalledExactlyOnceWith(['processed.png', 'sketch.png'], expect.any(AbortSignal));
+ const after = target.getProject()!.canvas;
+ expect(after.document.stacks.control).toEqual([
+ expect.objectContaining({
+ source: { type: 'image', image: { imageName: 'processed.png', width: 512, height: 256 } },
+ transform: { x: -128, y: 96, rotation: 0, scaleX: 1.5, scaleY: 4 },
+ adapter: {
+ model: controlModel.key,
+ kind: 'controlnet',
+ weight: 0.65,
+ beginEndStepPct: [0.15, 0.85],
+ controlMode: 'more_control',
+ },
+ }),
+ expect.objectContaining({
+ adapter: expect.objectContaining({ model: 't2i', kind: 't2i_adapter', weight: 0.4, beginEndStepPct: [0, 0.6] }),
+ }),
+ ]);
+ expect(after.document.stacks.raster).toEqual(before.stacks.raster);
+ expect(after.snapshots.at(-1)?.document).toEqual(before);
+ }
+);
+
+it.each([
+ ['flux', 'control_lora', 'control_lora'],
+ ['anima', 'controlnet', 'anima_lllite'],
+ ['qwen-image', 'controlnet', 'qwen_image_control'],
+ ['flux2', 'controlnet', 'flux2_control'],
+] as const)('infers standalone %s control kind from installed model identity', async (base, type, kind) => {
+ const adapter = {
+ base,
+ type,
+ key: 'installed',
+ name: 'Installed',
+ hash: 'portable',
+ cond_in_channels: 3,
+ } as ModelConfig;
+ const model = { base, key: 'main', name: 'Main', type: 'main', variant: 'dev' } as MainModelConfig;
+ api.resolveMany.mockResolvedValue([{ imageName: 'processed.png', width: 640, height: 480 }]);
+ const plan = await prepareCanvasRecall({
+ metadata: {
+ controlnets: [
+ {
+ ...standaloneControl(),
+ control_model: { base, type, hash: 'portable' },
+ begin_step_percent: 0,
+ end_step_percent: 1,
+ },
+ ],
+ },
+ model,
+ models: [model, adapter],
+ owner: captureAccountScope(),
+ });
+ expect(plan.problems).toEqual([]);
+ expect(plan.document?.stacks.control[0]).toMatchObject({ adapter: { model: 'installed', kind } });
+});
+
+it.each([
+ { controlnets: [] },
+ { controlnets: 'damaged' },
+ { controlnets: [{ ...standaloneControl(), control_weight: [0.2, 0.9] }] },
+ { controlnets: [{ ...standaloneControl(), resize_mode: 'crop_resize' }] },
+ { controlnets: [{ ...standaloneControl(), control_model: { key: 'deleted' } }] },
+ { controlnets: [{ ...standaloneControl(), processed_image: { image_name: 'deleted.png' } }] },
+])('preserves authored Canvas when standalone controls cannot be restored: %j', async (metadata) => {
+ api.resolveMany.mockImplementation((names: string[]) =>
+ Promise.resolve(
+ names.filter((name) => name !== 'deleted.png').map((imageName) => ({ imageName, width: 320, height: 200 }))
+ )
+ );
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ target.commands.canvas.apply(target.projectId, { type: 'replaceCanvasDocument', document: document() });
+ const before = target.getProject()!.canvas;
+ const add = vi.spyOn(store.commands.notifications, 'add');
+ api.metadata.mockResolvedValue({ ...metadata, positive_prompt: 'still independent' });
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'legacy.png', width: 1024, height: 768 } as GalleryImage,
+ kind: 'all',
+ models,
+ projectId: target.projectId,
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas).toBe(before);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({
+ positivePrompt: 'still independent',
+ });
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+});
+
+it.each([false, true])(
+ 'keeps modern control records authoritative over standalone aliases (empty=%s)',
+ async (empty) => {
+ const control = {
+ model: controlModel,
+ image: { image_name: 'modern.png', width: 300, height: 200 },
+ position: { x: -70, y: 90 },
+ weight: 0.3,
+ };
+ api.resolveMany.mockResolvedValue([{ imageName: 'modern.png', width: 600, height: 400 }]);
+ const plan = await prepareCanvasRecall({
+ metadata: { control_layers: empty ? [] : [control], controlnets: [standaloneControl()] },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.document?.stacks.control).toHaveLength(empty ? 0 : 1);
+ if (empty) {
+ expect(api.resolveMany).not.toHaveBeenCalled();
+ } else {
+ expect(api.resolveMany).toHaveBeenCalledExactlyOnceWith(['modern.png'], expect.any(AbortSignal));
+ expect(plan.document?.stacks.control[0]).toMatchObject({
+ transform: { x: -70, y: 90, scaleX: 1, scaleY: 1 },
+ source: { image: { width: 600, height: 400 } },
+ });
+ }
+ }
+);
+
+it('bounds standalone asset reads, deduplicates maps and refuses a stale project before the next batch', async () => {
+ let current = true;
+ const controls = Array.from({ length: 1002 }, (_, index) => ({
+ ...standaloneControl(),
+ processed_image: { image_name: `map-${index % 1001}.png` },
+ }));
+ api.resolveMany.mockImplementation((names: string[]) => {
+ current = false;
+ return Promise.resolve(names.map((imageName) => ({ imageName, width: 64, height: 64 })));
+ });
+ const plan = await prepareCanvasRecall({
+ metadata: { controlnets: controls },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ isCurrent: () => current,
+ });
+ expect(api.resolveMany).toHaveBeenCalledOnce();
+ expect(api.resolveMany.mock.calls[0]![0]).toHaveLength(1000);
+ expect(plan.document).toBeNull();
+ expect(plan.problems).toContain('canvas-changed');
+});
+
+it('reports legacy vector loss as partial instead of replacing authored work', async () => {
+ const layer = {
+ id: 'raster',
+ name: 'Legacy raster',
+ isEnabled: true,
+ isLocked: false,
+ position: { x: 0, y: 0 },
+ opacity: 1,
+ objects: [{ id: 'image', type: 'image', image: { image_name: 'raster.png', width: 320, height: 200 } }],
+ };
+ const plan = await prepareCanvasRecall({
+ metadata: {
+ canvas_v2_metadata: {
+ rasterLayers: [layer],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ vectorLayers: [{ id: 'vector' }],
+ },
+ },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.document?.stacks.raster).toHaveLength(1);
+ expect(plan.partial).toBe(true);
+ expect(plan.problems).toContain('unsupported-legacy-layers');
+});
+
+it.each(['partial', 'pending'] as const)(
+ 'fits standalone maps to the active frame while preserving authored work in a %s merge',
+ async (mode) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ target.commands.canvas.apply(target.projectId, { type: 'replaceCanvasDocument', document: document() });
+ if (mode === 'pending') {
+ store.commands.canvas.appendStagingCandidate({
+ projectId: target.projectId,
+ candidate: {
+ imageName: 'staged.png',
+ imageUrl: '',
+ thumbnailUrl: '',
+ width: 100,
+ height: 100,
+ queuedAt: '',
+ sourceQueueItemId: '',
+ placement: { x: 0, y: 0, width: 100, height: 100, opacity: 1 },
+ },
+ });
+ }
+ const before = target.getProject()!.canvas;
+ api.resolveMany.mockResolvedValue([{ imageName: 'processed.png', width: 256, height: 512 }]);
+ const controls = [
+ standaloneControl(),
+ ...(mode === 'partial' ? [{ ...standaloneControl(), control_weight: [0.2, 0.9] }] : []),
+ ];
+ const plan = await prepareCanvasRecall({
+ metadata: { width: 1024, height: 768, controlnets: controls },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(
+ commitCanvasRecall({ plan, target, expectedDocument: before.document, restorePointName: 'Before recall' })
+ ).toBe(true);
+ const after = target.getProject()!.canvas;
+ expect(after.document.bbox).toEqual(before.document.bbox);
+ expect(after.document.stacks.raster).toEqual(before.document.stacks.raster);
+ expect(after.document.stacks.control).toHaveLength(2);
+ expect(
+ after.document.stacks.control.find(
+ (node) =>
+ node.type === 'control' && node.source.type === 'image' && node.source.image.imageName === 'processed.png'
+ )
+ ).toMatchObject({
+ transform: { x: -128, y: 96, rotation: 0, scaleX: 3, scaleY: 2 },
+ });
+ expect(after.stagingArea).toEqual(before.stagingArea);
+ expect(after.snapshots).toHaveLength(0);
+ expect(plan.partial).toBe(true);
+ }
+);
+
+it('preserves authored controls for a malformed modern list rather than interpreting it as an empty list', async () => {
+ const plan = await prepareCanvasRecall({
+ metadata: { control_layers: null, controlnets: [standaloneControl()] },
+ model: main,
+ models,
+ owner: captureAccountScope(),
+ });
+ expect(plan.document).toBeNull();
+ expect(plan.problems).toContain('invalid-control');
+ expect(api.resolveMany).not.toHaveBeenCalled();
+});
+
+it('keeps Generate recall independent when the second standalone-control asset batch fails', async () => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const before = target.getProject()!.canvas;
+ api.metadata.mockResolvedValue({
+ positive_prompt: 'independent',
+ controlnets: Array.from({ length: 1001 }, (_, index) => ({
+ ...standaloneControl(),
+ processed_image: { image_name: `map-${index}.png` },
+ })),
+ });
+ api.resolveMany
+ .mockImplementationOnce((names: string[]) =>
+ Promise.resolve(names.map((imageName) => ({ imageName, width: 64, height: 64 })))
+ )
+ .mockRejectedValueOnce(new ApiError('Unavailable', 503));
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'legacy.png', width: 512, height: 512 } as GalleryImage,
+ kind: 'remix',
+ models,
+ queryClient: new QueryClient(),
+ projectId: target.projectId,
+ t,
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas).toBe(before);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({ positivePrompt: 'independent' });
+ expect(api.resolveMany.mock.calls.map(([names]) => names.length)).toEqual([1000, 1]);
+});
+
+it('stops reference hydration after the originating project changes before the second batch or any commit', async () => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const ipModel = { base: 'sdxl', type: 'ip_adapter', key: 'ip', name: 'IP' } as ModelConfig;
+ api.metadata.mockResolvedValue({
+ positive_prompt: 'stale',
+ ipAdapters: Array.from({ length: 1001 }, (_, index) => ({
+ ip_adapter_model: ipModel,
+ image: { image_name: `ref-${index}.png` },
+ weight: 0.5,
+ method: 'full',
+ clip_vision_model: 'ViT-H',
+ begin_step_percent: 0,
+ end_step_percent: 1,
+ })),
+ });
+ const setSettings = vi.spyOn(store.commands.generation, 'setSettings');
+ const before = target.getProject()!.canvas;
+ api.resolveMany.mockImplementation((names: string[]) => {
+ store.commands.projects.create();
+ return Promise.resolve(names.map((imageName) => ({ imageName, width: 64, height: 64 })));
+ });
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: {
+ ...target,
+ getProject: () => (store.queries.isActiveProject(target.projectId) ? target.getProject() : null),
+ },
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'legacy.png', width: 512, height: 512 } as GalleryImage,
+ kind: 'all',
+ models: [...models, ipModel],
+ queryClient: new QueryClient(),
+ projectId: target.projectId,
+ t,
+ })
+ ).toBe(false);
+ expect(api.resolveMany).toHaveBeenCalledOnce();
+ expect(setSettings).not.toHaveBeenCalled();
+ expect(target.getProject()!.canvas).toBe(before);
+});
+
+it.each([
+ ['array', 'all'],
+ ['array', 'remix'],
+ ['entities', 'all'],
+ ['entities', 'remix'],
+] as const)(
+ 'warns when Gallery %s historical references are refused during %s, preserving existing references and Canvas',
+ async (shape, kind) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const before = target.getProject()!.canvas;
+ const ipModel = { base: 'sdxl', key: 'ip', name: 'IP', type: 'ip_adapter' } as ModelConfig;
+ const currentReference = {
+ id: 'current',
+ isEnabled: true,
+ config: {
+ type: 'ip_adapter',
+ model: ipModel,
+ image: { original: { image: { image_name: 'current.png', width: 100, height: 100 } } },
+ weight: 0.5,
+ beginEndStepPct: [0, 1],
+ clipVisionModel: 'ViT-H',
+ method: 'full',
+ },
+ };
+ const refused = { id: 'old', ipAdapter: { type: 'ip_adapter', image: null } };
+ api.metadata.mockResolvedValue({
+ positive_prompt: 'still recallable',
+ canvas_v2_metadata: {
+ rasterLayers: [],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ referenceImages: shape === 'array' ? [refused] : { entities: [refused] },
+ },
+ });
+ const add = vi.spyOn(store.commands.notifications, 'add');
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key, referenceImages: [currentReference] }),
+ image: { imageName: 'historical.png', width: 512, height: 512 } as GalleryImage,
+ kind,
+ models: [...models, ipModel],
+ queryClient: new QueryClient(),
+ projectId: target.projectId,
+ t,
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas).toBe(before);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({
+ positivePrompt: 'still recallable',
+ referenceImages: [currentReference],
+ });
+ expect(api.resolveMany).not.toHaveBeenCalled();
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: 'widgets.gallery.itemActions.recall.partiallyRecalled',
+ message: 'widgets.gallery.itemActions.recall.referenceImagesPartial',
+ })
+ );
+ }
+);
+
+const convertedPaintRecall = (partial = true) => {
+ const recalled = createEmptyCanvasDocument();
+ const paint = (id: string) => ({
+ ...base,
+ id,
+ name: id,
+ type: 'raster' as const,
+ source: { type: 'paint' as const, bitmap: { imageName: `${id}.png`, width: 64, height: 64 } },
+ });
+ recalled.stacks.raster = [
+ paint('created-a'),
+ paint('created-b'),
+ {
+ ...base,
+ id: 'borrowed',
+ type: 'raster',
+ source: { type: 'image', image: { imageName: 'borrowed.png', width: 64, height: 64 } },
+ },
+ ];
+ if (partial) {
+ recalled.stacks.control = [
+ {
+ ...control(),
+ id: 'rejected',
+ adapter: { ...control().adapter, model: 'incompatible' },
+ source: { type: 'paint' as const, bitmap: { imageName: 'created-rejected.png', width: 64, height: 64 } },
+ },
+ ];
+ }
+ return {
+ record: {
+ version: 1,
+ document: recalled,
+ controlModels: { rejected: { ...controlModel, base: 'sd-1', key: 'incompatible' } },
+ },
+ problems: [],
+ createdImageNames: ['created-a.png', 'created-b.png', ...(partial ? ['created-rejected.png'] : [])],
+ };
+};
+
+it.each(['project', 'account', 'promotion-failure', 'project-promotion-failure'] as const)(
+ 'adopts only retained conversion outputs after all recall writes when %s changes during promotion',
+ async (change) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const owner = captureAccountScope();
+ const localization = createInstance();
+ await localization.init({
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: Object.values(
+ import.meta.glob('../../../public/locales/en.json', { eager: true, import: 'default' })
+ )[0] as Record<string, unknown>,
+ },
+ },
+ });
+ vi.spyOn(CanvasOperations, 'prepareLegacyCanvasMetadata').mockResolvedValue(convertedPaintRecall());
+ api.metadata.mockResolvedValue({ positive_prompt: 'recalled prompt', canvas_v2_metadata: {} });
+ let resolve!: () => void;
+ let reject!: (reason: Error) => void;
+ api.makeCanvasAsset.mockImplementationOnce(
+ () =>
+ new Promise<void>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ })
+ );
+ const add = vi.spyOn(store.commands.notifications, 'add');
+ const pending = executeImageRecall({
+ commands: store.commands,
+ canvasTarget: {
+ ...target,
+ getProject: () => (store.queries.isActiveProject(target.projectId) ? target.getProject() : null),
+ },
+ getGenerateValues: () => ({ modelKey: main.key, ...getProjectWidgetValues(target.getProject()!, 'generate') }),
+ image: { imageName: 'legacy.png', width: 512, height: 512 } as GalleryImage,
+ kind: 'all',
+ models,
+ queryClient: new QueryClient(),
+ projectId: target.projectId,
+ owner,
+ t: localization.t.bind(localization) as TFunction,
+ });
+ await vi.waitFor(() => expect(api.makeCanvasAsset).toHaveBeenCalledExactlyOnceWith('created-a.png'));
+ expect(target.getProject()!.canvas.document.stacks.raster).toHaveLength(3);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({
+ positivePrompt: 'recalled prompt',
+ });
+ // No recalled snapshot may overwrite an edit made during the durability request.
+ store.commands.generation.setSettings(
+ { ...getDefaultGenerateSettings(main), model: main, steps: 47 },
+ target.projectId
+ );
+ const noticesBefore = add.mock.calls.length;
+ if (change === 'project' || change === 'project-promotion-failure') {
+ store.commands.projects.create();
+ } else if (change === 'account') {
+ accountLifecycle.activate('another-account');
+ }
+ if (change === 'promotion-failure' || change === 'project-promotion-failure') {
+ reject(new Error('Promotion unavailable'));
+ } else {
+ resolve();
+ }
+ expect(await pending).toBe(true);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({ steps: 47 });
+ expect(api.makeCanvasAsset.mock.calls.map(([name]) => name)).toEqual(
+ change === 'account' ? ['created-a.png'] : ['created-a.png', 'created-b.png']
+ );
+ if (change === 'promotion-failure') {
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message:
+ 'Canvas was recalled, but some restored paint images are still temporary. Keep the project open or save it before closing to protect them from intermediate cleanup.',
+ })
+ );
+ } else {
+ expect(add.mock.calls).toHaveLength(noticesBefore);
+ }
+ }
+);
+
+it.each(['validation', 'commit'] as const)(
+ 'leaves prepared pixels reclaimable after a failed %s while recalling independent Generate fields',
+ async (failure) => {
+ const store = createWorkbenchStore();
+ const target = targetFor(store);
+ const previous = target.getProject()!.canvas.document;
+ const converted = convertedPaintRecall(false);
+ vi.spyOn(CanvasOperations, 'prepareLegacyCanvasMetadata').mockResolvedValue(
+ failure === 'validation'
+ ? { ...converted, record: { ...converted.record, document: { ...converted.record.document, version: 999 } } }
+ : converted
+ );
+ if (failure === 'commit') {
+ const apply = store.commands.canvas.apply;
+ vi.spyOn(store.commands.canvas, 'apply').mockImplementation((projectId, mutation, origin) =>
+ mutation.type === 'replaceCanvasDocument' ? false : apply(projectId, mutation, origin)
+ );
+ }
+ api.metadata.mockResolvedValue({ positive_prompt: 'independent prompt', canvas_v2_metadata: {} });
+ expect(
+ await executeImageRecall({
+ commands: store.commands,
+ canvasTarget: target,
+ getGenerateValues: () => ({ modelKey: main.key }),
+ image: { imageName: 'legacy.png', width: 512, height: 512 } as GalleryImage,
+ kind: 'all',
+ models,
+ queryClient: new QueryClient(),
+ projectId: target.projectId,
+ t,
+ })
+ ).toBe(true);
+ expect(target.getProject()!.canvas.document).toBe(previous);
+ expect(getProjectWidgetValues(target.getProject()!, 'generate')).toMatchObject({
+ positivePrompt: 'independent prompt',
+ });
+ expect(api.makeCanvasAsset).not.toHaveBeenCalled();
+ }
+);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
new file mode 100644
index 0000000000..b94fc614f0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts
@@ -0,0 +1,601 @@
+import type { GalleryImage } from '@features/gallery';
+import type { GenerateModelConfig, ComponentModelConfig } from '@features/generation/contracts';
+import type { CanvasDocumentContractV3, CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';
+import type { Project } from '@workbench/projectContracts';
+import type { WorkbenchCommands } from '@workbench/workbenchStore';
+import type { TFunction } from 'i18next';
+
+import { galleryDurability, galleryImages } from '@features/gallery';
+import { galleryImageUrls } from '@features/gallery/utility';
+import {
+ getRegionalGuidanceSupport,
+ isControlKindSupportedForBase,
+ getControlValidationReason,
+} from '@features/generation/graph';
+import { createItemId } from '@platform/browser/randomUuid';
+import { assertAccountScopeCurrent, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { prepareLegacyCanvasMetadata, getCanvasEngine } from '@workbench/canvas-operations/api';
+import { createEmptyCanvasState, isRecord, loadCanvasState } from '@workbench/canvasMigration';
+import { deriveControlKind, isStorableControlWeight, isStorableControlStepRange } from '@workbench/controlAdapters';
+import {
+ readCanvasCompositingSettings,
+ CANVAS_COMPOSITING_KEYS,
+} from '@workbench/widgets/canvas/invoke/canvasCompositing';
+import { readCanvasScaling, CANVAS_SCALING_KEYS } from '@workbench/widgets/canvas/invoke/canvasScaling';
+
+import { resolveRecordedModel, toRecordedModelRef } from './recordedModel';
+
+// Matches MAX_IMAGE_BATCH_SIZE in invokeai/app/api/routers/images.py.
+const IMAGE_LOOKUP_BATCH_SIZE = 1000;
+
+export interface CanvasRecallTarget {
+ commands: Pick<WorkbenchCommands, 'canvas' | 'widgets'>;
+ /** Null when the originating project is closed or no longer active. */
+ getProject(): Project | null;
+ projectId: string;
+}
+
+export interface CanvasRecallPlan {
+ document: CanvasDocumentContractV3 | null;
+ /** Only acknowledged intermediate uploads produced by this preparation, never borrowed assets. */
+ createdImageNames?: readonly string[];
+ /** Partial recall merges instead of replacing authored work. */
+ partial: boolean;
+ controlsOnly?: boolean;
+ /** Standalone executed maps have frame-relative placement, never authored Canvas coordinates. */
+ fitControlsToFrame?: boolean;
+ problems: string[];
+ settings: Record<string, unknown>;
+}
+
+export const hasCanvasMetadata = (metadata: unknown): boolean =>
+ isRecord(metadata) &&
+ ('canvas_v3_metadata' in metadata ||
+ 'canvas_v2_metadata' in metadata ||
+ 'control_layers' in metadata ||
+ 'controlnets' in metadata ||
+ 't2iAdapters' in metadata);
+
+export const readCanvasStrength = (metadata: unknown): number | null => {
+ if (!isRecord(metadata)) {
+ return null;
+ }
+ const record = isRecord(metadata.canvas_v3_metadata) ? metadata.canvas_v3_metadata : null;
+ const settings = record && isRecord(record.settings) ? record.settings : null;
+ const value = metadata.denoise_strength ?? metadata.strength ?? settings?.strength;
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0.01 && value <= 1 ? value : null;
+};
+
+/** Never default missing settings: a sparse old record must not reset unrelated canvas preferences. */
+const readCanvasSettings = (metadata: Record<string, unknown>): Record<string, unknown> => {
+ const patch: Record<string, unknown> = {};
+ const strength = readCanvasStrength(metadata);
+ if (strength !== null) {
+ patch.denoisingStrength = strength;
+ }
+ const record = isRecord(metadata.canvas_v3_metadata) ? metadata.canvas_v3_metadata : null;
+ const settings = record && isRecord(record.settings) ? record.settings : null;
+ if (settings && isRecord(settings.compositing)) {
+ const raw = settings.compositing;
+ const normalized = readCanvasCompositingSettings(raw);
+ for (const key of Object.values(CANVAS_COMPOSITING_KEYS)) {
+ const value = raw[key],
+ canonical = normalized[key];
+ if (value === undefined) {
+ continue;
+ }
+ if (key === 'infillColorValue') {
+ if (
+ isRecord(value) &&
+ typeof canonical === 'object' &&
+ ['r', 'g', 'b', 'a'].every((channel) => value[channel] === canonical[channel as keyof typeof canonical])
+ ) {
+ patch[key] = canonical;
+ }
+ } else if (value === canonical) {
+ patch[key] = canonical;
+ }
+ }
+ }
+ if (settings && isRecord(settings.scaling)) {
+ const raw = settings.scaling;
+ const normalized = readCanvasScaling({ scaleMethod: raw.method, scaledWidth: raw.width, scaledHeight: raw.height });
+ for (const side of ['method', 'width', 'height'] as const) {
+ if (raw[side] !== undefined && raw[side] === normalized[side]) {
+ patch[CANVAS_SCALING_KEYS[side]] = normalized[side];
+ }
+ }
+ }
+ return patch;
+};
+
+const resolveModel = (value: unknown, models: readonly ComponentModelConfig[]): ComponentModelConfig | null => {
+ const ref = typeof value === 'string' ? toRecordedModelRef({ key: value }) : toRecordedModelRef(value);
+ const model = ref ? resolveRecordedModel(ref, models, { ambiguous: 'refuse', hashMiss: 'refuse' }) : null;
+ if (
+ !model ||
+ model === 'ambiguous' ||
+ (ref?.base && ref.base !== model.base) ||
+ (ref?.type && ref.type !== model.type)
+ ) {
+ return null;
+ }
+ return model;
+};
+
+const sourceNames = (layer: CanvasLayerContract): string[] => {
+ const names: string[] = [];
+ if ('source' in layer) {
+ if (layer.source.type === 'image') {
+ names.push(layer.source.image.imageName);
+ }
+ if (layer.source.type === 'paint' && layer.source.bitmap) {
+ names.push(layer.source.bitmap.imageName);
+ }
+ } else if (layer.mask.bitmap) {
+ names.push(layer.mask.bitmap.imageName);
+ }
+ if (layer.type === 'control' && layer.original) {
+ if (layer.original.type === 'image') {
+ names.push(layer.original.image.imageName);
+ }
+ if (layer.original.type === 'paint' && layer.original.bitmap) {
+ names.push(layer.original.bitmap.imageName);
+ }
+ }
+ if (layer.type === 'regional_guidance') {
+ for (const ref of layer.referenceImages) {
+ if (ref.config.image) {
+ names.push(ref.config.image.imageName);
+ }
+ }
+ }
+ return names;
+};
+
+/** Bounded bulk asset lookups, strict document validation, portable model resolution, no project mutation. */
+export const prepareCanvasRecall = async ({
+ metadata,
+ model,
+ models,
+ owner,
+ isCurrent,
+ resolvedImages = new Map<string, GalleryImage>(),
+}: {
+ isCurrent?: () => boolean;
+ /** Internal recursion reuses asset reads from standalone control projection. */
+ resolvedImages?: Map<string, GalleryImage>;
+ metadata: unknown;
+ model: GenerateModelConfig;
+ models: readonly ComponentModelConfig[];
+ owner: AccountScope;
+}): Promise<CanvasRecallPlan> => {
+ const plan: CanvasRecallPlan = { document: null, partial: false, problems: [], settings: {} };
+ if (!isRecord(metadata)) {
+ return plan;
+ }
+ plan.settings = readCanvasSettings(metadata);
+ if (('strength' in metadata || 'denoise_strength' in metadata) && readCanvasStrength(metadata) === null) {
+ plan.problems.push('invalid-strength');
+ }
+ if (!hasCanvasMetadata(metadata)) {
+ return plan;
+ }
+ // Bound JSON as well as the canvas loader's 10,000 nodes / ten levels. Never traverse arbitrary metadata recursively.
+ if (JSON.stringify(metadata).length > 32 * 1024 * 1024) {
+ plan.problems.push('record-too-large');
+ return plan;
+ }
+ const lookupImages = async (names: string[]): Promise<boolean> => {
+ if (isCurrent && !isCurrent()) {
+ plan.settings = {};
+ plan.problems.push('canvas-changed');
+ return false;
+ }
+ const missing = [...new Set(names)].filter((name) => !resolvedImages.has(name));
+ assertAccountScopeCurrent(owner);
+ for (let offset = 0; offset < missing.length; offset += IMAGE_LOOKUP_BATCH_SIZE) {
+ try {
+ const images = await galleryImages.resolveMany(
+ missing.slice(offset, offset + IMAGE_LOOKUP_BATCH_SIZE),
+ owner.signal
+ );
+ assertAccountScopeCurrent(owner);
+ if (isCurrent && !isCurrent()) {
+ plan.settings = {};
+ plan.problems.push('canvas-changed');
+ return false;
+ }
+ for (const image of images) {
+ resolvedImages.set(image.imageName, image);
+ }
+ } catch (error) {
+ assertAccountScopeCurrent(owner);
+ if (isCurrent && !isCurrent()) {
+ plan.settings = {};
+ plan.problems.push('canvas-changed');
+ return false;
+ }
+ const networkFailure =
+ error instanceof TypeError &&
+ [
+ 'Failed to fetch',
+ 'NetworkError when attempting to fetch resource.',
+ 'Load failed',
+ 'fetch failed',
+ ].includes(error.message);
+ if (!(error instanceof ApiError) && !networkFailure) {
+ throw error;
+ }
+ plan.settings = {};
+ plan.partial = true;
+ plan.problems.push('image-lookup-failed');
+ return false;
+ }
+ }
+ return true;
+ };
+ const record = metadata.canvas_v3_metadata;
+ if (!isRecord(record) || record.version !== 1) {
+ if ('canvas_v3_metadata' in metadata) {
+ plan.problems.push('invalid-record');
+ return plan;
+ }
+ let legacyMetadata = metadata;
+ const standalone = !('canvas_v2_metadata' in metadata) && !('control_layers' in metadata);
+ if (!('canvas_v2_metadata' in metadata)) {
+ let controls: unknown[];
+ if (standalone) {
+ controls = [];
+ for (const key of ['controlnets', 't2iAdapters'] as const) {
+ if (!(key in metadata)) {
+ continue;
+ }
+ const entries = metadata[key];
+ if (!Array.isArray(entries)) {
+ plan.problems.push('invalid-control');
+ continue;
+ }
+ if (controls.length + entries.length > 10000) {
+ plan.problems.push('record-too-large');
+ }
+ for (const entry of entries.slice(0, 10000 - controls.length)) {
+ controls.push(
+ isRecord(entry)
+ ? {
+ ...entry,
+ model: entry[key === 'controlnets' ? 'control_model' : 't2i_adapter_model'],
+ weight: key === 'controlnets' ? entry.control_weight : entry.weight,
+ }
+ : entry
+ );
+ }
+ }
+ // Old aliases describe executed adapters; an empty or damaged list never means Clear Canvas.
+ if (controls.length === 0) {
+ plan.problems.push('invalid-control');
+ return plan;
+ }
+ } else {
+ if (!Array.isArray(metadata.control_layers)) {
+ plan.problems.push('invalid-control');
+ return plan;
+ }
+ if (metadata.control_layers.length > 10000) {
+ plan.problems.push('record-too-large');
+ }
+ controls = metadata.control_layers.slice(0, 10000);
+ }
+ const names = controls.flatMap((control) => {
+ const asset = isRecord(control) ? (control.processed_image ?? control.image) : null;
+ return isRecord(asset) && typeof asset.image_name === 'string' && asset.image_name ? [asset.image_name] : [];
+ });
+ if (!(await lookupImages(names))) {
+ return plan;
+ }
+ controls = controls.map((control) => {
+ if (!isRecord(control)) {
+ return control;
+ }
+ if (
+ standalone &&
+ control.control_mode !== undefined &&
+ !['balanced', 'more_prompt', 'more_control', 'unbalanced'].includes(String(control.control_mode))
+ ) {
+ plan.problems.push('invalid-control');
+ return null;
+ }
+ if (standalone && Array.isArray(control.weight)) {
+ plan.problems.push('unsupported-control');
+ return null;
+ }
+ if (
+ standalone &&
+ control.resize_mode !== undefined &&
+ control.resize_mode !== 'just_resize' &&
+ control.resize_mode !== 'just_resize_simple'
+ ) {
+ plan.problems.push('unsupported-control');
+ return null;
+ }
+ const asset = control.processed_image ?? control.image;
+ const resolved =
+ isRecord(asset) && typeof asset.image_name === 'string' ? resolvedImages.get(asset.image_name) : null;
+ if (!resolved) {
+ plan.problems.push('invalid-control-image');
+ }
+ return {
+ ...control,
+ image: resolved
+ ? {
+ image_name: resolved.imageName,
+ width: resolved.width ?? (isRecord(asset) ? asset.width : undefined),
+ height: resolved.height ?? (isRecord(asset) ? asset.height : undefined),
+ }
+ : null,
+ processed_image: null,
+ };
+ });
+ legacyMetadata = { ...metadata, control_layers: controls };
+ }
+ if (
+ isRecord(metadata.canvas_v2_metadata) &&
+ Array.isArray(metadata.canvas_v2_metadata.vectorLayers) &&
+ metadata.canvas_v2_metadata.vectorLayers.length > 0
+ ) {
+ plan.problems.push('unsupported-legacy-layers');
+ }
+ let converted;
+ try {
+ converted = await prepareLegacyCanvasMetadata(legacyMetadata, owner, isCurrent);
+ } catch (error) {
+ assertAccountScopeCurrent(owner);
+ if (isCurrent && !isCurrent()) {
+ plan.settings = {};
+ plan.problems.push('canvas-changed');
+ return plan;
+ }
+ throw error;
+ }
+ assertAccountScopeCurrent(owner);
+ plan.problems.push(...converted.problems);
+ plan.createdImageNames = converted.createdImageNames;
+ if (!converted.record) {
+ return plan;
+ }
+ return prepareCanvasRecall({
+ resolvedImages,
+ metadata: { ...metadata, canvas_v3_metadata: converted.record },
+ model,
+ models,
+ owner,
+ isCurrent,
+ }).then((result) => ({
+ ...result,
+ createdImageNames: converted.createdImageNames,
+ partial: result.partial || plan.problems.length > 0,
+ controlsOnly: !('canvas_v2_metadata' in metadata),
+ fitControlsToFrame: standalone,
+ problems: [...plan.problems, ...result.problems],
+ }));
+ }
+ const rawDocument = record.document;
+ if (!isRecord(rawDocument) || ![3, 4, 5, 6].includes(Number(rawDocument.version))) {
+ plan.problems.push('invalid-document');
+ return plan;
+ }
+ const bbox = rawDocument.bbox;
+ if (
+ !isRecord(bbox) ||
+ ![rawDocument.width, rawDocument.height, bbox.width, bbox.height].every(
+ (value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0
+ ) ||
+ ![bbox.x, bbox.y].every((value) => typeof value === 'number' && Number.isFinite(value))
+ ) {
+ plan.problems.push('invalid-document');
+ return plan;
+ }
+ const loaded = loadCanvasState({ ...createEmptyCanvasState(), version: rawDocument.version, document: rawDocument });
+ if (loaded.status !== 'loaded') {
+ plan.problems.push('invalid-document');
+ return plan;
+ }
+ if (isCurrent && !isCurrent()) {
+ plan.settings = {};
+ plan.problems.push('canvas-changed');
+ return plan;
+ }
+ const document = loaded.value.document;
+ // Project hydration repairs old adapter values. A metadata recall reports and skips damaged controls instead.
+ const invalidControlIds = new Set<string>();
+ const inspectAdapters = (nodes: unknown[], depth: number): void => {
+ if (depth > 10) {
+ return;
+ }
+ for (const raw of nodes) {
+ if (!isRecord(raw)) {
+ continue;
+ }
+ if (raw.type === 'group' && Array.isArray(raw.children)) {
+ inspectAdapters(raw.children, depth + 1);
+ } else if (
+ raw.type === 'control' &&
+ typeof raw.id === 'string' &&
+ (!isRecord(raw.adapter) ||
+ !isStorableControlWeight(raw.adapter.weight) ||
+ !isStorableControlStepRange(raw.adapter.beginEndStepPct))
+ ) {
+ invalidControlIds.add(raw.id);
+ }
+ }
+ };
+ if (isRecord(rawDocument.stacks) && Array.isArray(rawDocument.stacks.control)) {
+ inspectAdapters(rawDocument.stacks.control, 0);
+ }
+ const leaves: CanvasLayerContract[] = [];
+ const collect = (nodes: CanvasNodeContract[]): void => {
+ for (const node of nodes) {
+ if (node.type === 'group') {
+ collect(node.children);
+ } else {
+ leaves.push(node);
+ }
+ }
+ };
+ Object.values(document.stacks).forEach(collect);
+ const names = [...new Set(leaves.flatMap(sourceNames))];
+ if (!(await lookupImages(names))) {
+ return plan;
+ }
+ const available = new Set(resolvedImages.keys());
+ const controlModels = isRecord(record.controlModels) ? record.controlModels : {};
+ const keep = (nodes: CanvasNodeContract[]): CanvasNodeContract[] =>
+ nodes.flatMap((node): CanvasNodeContract[] => {
+ if (node.type === 'group') {
+ const children = keep(node.children);
+ return children.length || node.children.length === 0 ? [{ ...node, children }] : [];
+ }
+ if (sourceNames(node).some((name) => !available.has(name))) {
+ plan.problems.push(node.name);
+ return [];
+ }
+ if (node.type === 'control' && invalidControlIds.has(node.id)) {
+ plan.problems.push(node.name);
+ return [];
+ }
+ if (node.type === 'control' && (node.adapter.model || controlModels[node.id])) {
+ const resolved = resolveModel(controlModels[node.id] ?? node.adapter.model, models);
+ const kind = resolved ? deriveControlKind(resolved) : null;
+ if (
+ !resolved ||
+ resolved.base !== model.base ||
+ !kind ||
+ !isControlKindSupportedForBase(model.base, kind) ||
+ getControlValidationReason({
+ adapterModel: resolved,
+ kind,
+ weight: node.adapter.weight,
+ beginEndStepPct: node.adapter.beginEndStepPct,
+ mainBase: model.base,
+ mainVariant: model.variant ?? undefined,
+ controlLoraIndex: 0,
+ })
+ ) {
+ plan.problems.push(node.name);
+ return [];
+ }
+ node.adapter = { ...node.adapter, model: resolved.key, kind };
+ }
+ if (node.type === 'regional_guidance') {
+ const support = getRegionalGuidanceSupport(model.base);
+ if (!support && node.isEnabled) {
+ plan.problems.push(node.name);
+ return [];
+ }
+ node.referenceImages = node.referenceImages.filter((ref) => {
+ const resolved = ref.config.model ? resolveModel(ref.config.model, models) : null;
+ if (
+ ref.config.model &&
+ (!resolved ||
+ resolved.base !== model.base ||
+ resolved.type !== ref.config.type ||
+ support?.referenceImages !== ref.config.type)
+ ) {
+ plan.problems.push(node.name);
+ return false;
+ }
+ if (resolved) {
+ ref.config.model = resolved;
+ }
+ if (ref.config.image) {
+ ref.config.image.imageUrl = galleryImageUrls.full(ref.config.image.imageName);
+ ref.config.image.thumbnailUrl = galleryImageUrls.thumbnail(ref.config.image.imageName);
+ }
+ ref.id = createItemId('regional-reference');
+ return true;
+ });
+ }
+ return [node];
+ });
+ for (const stack of ['raster', 'control', 'regional_guidance', 'inpaint_mask'] as const) {
+ document.stacks[stack] = keep(document.stacks[stack]);
+ }
+ plan.partial = plan.problems.length > 0;
+ if (leaves.length > 0 && Object.values(document.stacks).every((nodes) => nodes.length === 0)) {
+ return plan;
+ }
+ plan.document = document;
+ return plan;
+};
+
+export { commitCanvasRecall } from '@workbench/canvas-operations/api';
+
+/**
+ * Adopt only this preparation's pixels retained by a successful commit. Call after all synchronous Canvas/Generate
+ * writes. Capture the committed name set once: subsequent project navigation must not redirect or abandon adoption.
+ * Failed/unknown uploads and rejected layers remain intermediate, so server cleanup can reclaim them.
+ */
+export const finalizeCanvasRecallAssets = async (
+ plan: CanvasRecallPlan,
+ target: CanvasRecallTarget,
+ owner: AccountScope
+): Promise<boolean> => {
+ if (!plan.createdImageNames?.length) {
+ return true;
+ }
+ const document = target.getProject()?.canvas.document;
+ if (!document || !isAccountScopeCurrent(owner)) {
+ return false;
+ }
+ const retained = new Set<string>();
+ const visit = (nodes: CanvasNodeContract[]): void => {
+ for (const node of nodes) {
+ if (node.type === 'group') {
+ visit(node.children);
+ } else {
+ sourceNames(node).forEach((name) => retained.add(name));
+ }
+ }
+ };
+ Object.values(document.stacks).forEach(visit);
+ const adopted = [...new Set(plan.createdImageNames)].filter((name) => retained.has(name));
+ let complete = true;
+ for (const imageName of adopted) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+ try {
+ await galleryDurability.makeCanvasAsset(imageName);
+ } catch {
+ // The recall already applied; recent grace, open-project holds and saved references still protect these pixels.
+ complete = false;
+ }
+ }
+ return complete;
+};
+
+/** Persist pending paint before any replacement. A changed document then fails the captured-identity commit fence. */
+export const settleCanvasRecall = async (
+ plan: CanvasRecallPlan,
+ target: CanvasRecallTarget,
+ owner: AccountScope
+): Promise<void> => {
+ if (!plan.document) {
+ return;
+ }
+ try {
+ await getCanvasEngine(target.projectId)?.lifecycle.flushPendingUploads({ waitForHeldPixels: false });
+ assertAccountScopeCurrent(owner);
+ } catch (error) {
+ assertAccountScopeCurrent(owner);
+ plan.document = null;
+ plan.settings = {};
+ plan.problems.push(error instanceof Error ? error.message : 'canvas-busy');
+ }
+};
+
+export const getCanvasRecallProblemsMessage = (problems: readonly string[], t: TFunction): string =>
+ [...new Set(problems)]
+ .map((problem) => t(`widgets.gallery.itemActions.recall.canvasReasons.${problem}`, { defaultValue: problem }))
+ .join(', ');
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
index e992c68d1e..b1bed1848e 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
@@ -818,3 +818,272 @@ describe('executeImageRecall', () => {
expect(oldCommands.add).not.toHaveBeenCalled();
});
});
+
+const legacyIPAdapter = () => ({
+ ip_adapter_model: { model_name: 'Portrait', base_model: 'sdxl', model_type: 'ip_adapter' },
+ image: { image_name: 'portrait.png' },
+ clip_vision_model: 'ViT-G',
+ method: 'style_precise',
+ weight: 0.65,
+ begin_step_percent: 0.2,
+ end_step_percent: 0.9,
+});
+const portraitModel = { key: 'portrait-installed', name: 'Portrait', base: 'sdxl', type: 'ip_adapter' } as ModelConfig;
+
+it.each(['all', 'remix'] as const)(
+ 'hydrates v4 name-only IP-Adapters for Gallery %s without losing adapter settings',
+ async (kind) => {
+ accountLifecycle.activate('ip-recall-tests');
+ const { commands, setSettings, add } = createCommands();
+ const client = new QueryClient();
+ galleryApi.galleryImages.metadata.mockResolvedValue({ ipAdapters: [legacyIPAdapter()] });
+ galleryApi.galleryImages.resolveMany
+ .mockReset()
+ .mockResolvedValue([{ ...image, imageName: 'portrait.png', width: 333, height: 222 }]);
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind,
+ models: [model, portraitModel],
+ queryClient: client,
+ t,
+ })
+ ).toBe(true);
+ expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledExactlyOnceWith(
+ ['portrait.png'],
+ expect.any(AbortSignal)
+ );
+ expect(setSettings).toHaveBeenCalledWith(
+ expect.objectContaining({
+ referenceImages: [
+ {
+ id: 'legacy-ip-adapter-0',
+ isEnabled: true,
+ config: {
+ type: 'ip_adapter',
+ model: portraitModel,
+ image: { original: { image: { image_name: 'portrait.png', width: 333, height: 222 } } },
+ weight: 0.65,
+ clipVisionModel: 'ViT-G',
+ method: 'style_precise',
+ beginEndStepPct: [0.2, 0.9],
+ },
+ },
+ ],
+ }),
+ undefined
+ );
+ expect(add).not.toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+ }
+);
+
+it.each(['deleted', 'lookup-failed', 'unsupported-weight', 'multi-image', 'missing-model', 'malformed'] as const)(
+ 'keeps existing references and recalls independent Generate fields when v4 adapters are %s',
+ async (failure) => {
+ accountLifecycle.activate('ip-failure-tests');
+ const { commands, setSettings, add } = createCommands();
+ const current = {
+ id: 'current',
+ isEnabled: true,
+ config: {
+ type: 'ip_adapter',
+ model: portraitModel,
+ image: { original: { image: { image_name: 'current.png', width: 100, height: 100 } } },
+ weight: 0.7,
+ beginEndStepPct: [0, 1],
+ method: 'full',
+ clipVisionModel: 'ViT-H',
+ },
+ };
+ const adapter = legacyIPAdapter();
+ const bad =
+ failure === 'unsupported-weight'
+ ? { ...adapter, weight: [0.2, 0.9] }
+ : failure === 'multi-image'
+ ? { ...adapter, image: [{ image_name: 'one.png' }, { image_name: 'two.png' }] }
+ : failure === 'missing-model'
+ ? { ...adapter, ip_adapter_model: { key: 'deleted' } }
+ : failure === 'malformed'
+ ? { ...adapter, end_step_percent: -1 }
+ : adapter;
+ galleryApi.galleryImages.metadata.mockResolvedValue({ positive_prompt: 'independent', ipAdapters: [bad] });
+ galleryApi.galleryImages.resolveMany.mockReset();
+ if (failure === 'lookup-failed') {
+ galleryApi.galleryImages.resolveMany.mockRejectedValue(new ApiError('Unavailable', 503));
+ } else {
+ galleryApi.galleryImages.resolveMany.mockResolvedValue(
+ failure === 'deleted' ? [] : [{ ...image, imageName: 'portrait.png' }]
+ );
+ }
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key, referenceImages: [current] }),
+ image,
+ kind: 'all',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(setSettings).toHaveBeenCalledWith(
+ expect.objectContaining({
+ positivePrompt: 'independent',
+ referenceImages: [expect.objectContaining({ id: 'current' })],
+ }),
+ undefined
+ );
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+ }
+);
+
+it('keeps supported IP entries while reporting malformed and unsupported siblings', async () => {
+ accountLifecycle.activate('ip-partial-tests');
+ const { commands, setSettings, add } = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ ipAdapters: [legacyIPAdapter(), { ...legacyIPAdapter(), weight: [1, 2] }, null],
+ });
+ galleryApi.galleryImages.resolveMany.mockReset().mockResolvedValue([{ ...image, imageName: 'portrait.png' }]);
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind: 'remix',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(setSettings.mock.calls[0]![0].referenceImages).toHaveLength(1);
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+});
+
+it('uses sequential bounded reference batches and lets Generate recall survive a second-batch failure', async () => {
+ accountLifecycle.activate('ip-batch-tests');
+ const { commands, setSettings, add } = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ positive_prompt: 'independent',
+ ipAdapters: Array.from({ length: 1002 }, (_, index) => ({
+ ...legacyIPAdapter(),
+ image: { image_name: `ref-${index % 1001}.png` },
+ })),
+ });
+ galleryApi.galleryImages.resolveMany
+ .mockReset()
+ .mockImplementationOnce((names: string[]) => Promise.resolve(names.map((imageName) => ({ ...image, imageName }))))
+ .mockRejectedValueOnce(new TypeError('Failed to fetch'));
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind: 'all',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(galleryApi.galleryImages.resolveMany.mock.calls.map(([names]) => names.length)).toEqual([1000, 1]);
+ expect(setSettings).toHaveBeenCalledWith(
+ expect.objectContaining({ positivePrompt: 'independent', referenceImages: [] }),
+ undefined
+ );
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+});
+
+it('abandons name-only reference hydration after account expiry before another batch or Generate commit', async () => {
+ accountLifecycle.activate('ip-expiry-tests');
+ const { commands, setSettings, add } = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ positive_prompt: 'wrong account',
+ ipAdapters: Array.from({ length: 1001 }, (_, index) => ({
+ ...legacyIPAdapter(),
+ image: { image_name: `ref-${index}.png` },
+ })),
+ });
+ galleryApi.galleryImages.resolveMany.mockReset().mockImplementation((names: string[]) => {
+ accountLifecycle.activate('different-account');
+ return Promise.resolve(names.map((imageName) => ({ ...image, imageName })));
+ });
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind: 'all',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(false);
+ expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledOnce();
+ expect(setSettings).not.toHaveBeenCalled();
+ expect(add).not.toHaveBeenCalled();
+});
+
+it('surfaces reference asset mapping errors instead of treating them as recoverable transport failures', async () => {
+ accountLifecycle.activate('ip-mapping-tests');
+ const { commands, setSettings, add } = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ positive_prompt: 'must not hide the error',
+ ipAdapters: [legacyIPAdapter()],
+ });
+ galleryApi.galleryImages.resolveMany.mockReset().mockRejectedValue(new TypeError('Invalid gallery image DTO'));
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind: 'all',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(false);
+ expect(setSettings).not.toHaveBeenCalled();
+ expect(commands.notifications.reportError).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Invalid gallery image DTO' })
+ );
+ expect(add).not.toHaveBeenCalled();
+});
+
+it('reports bounded reference truncation while hydrating the supported records in one deduplicated read', async () => {
+ accountLifecycle.activate('ip-limit-tests');
+ const { commands, setSettings, add } = createCommands();
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ ipAdapters: Array.from({ length: 10001 }, () => legacyIPAdapter()),
+ });
+ galleryApi.galleryImages.resolveMany.mockReset().mockResolvedValue([{ ...image, imageName: 'portrait.png' }]);
+ expect(
+ await executeImageRecall({
+ commands,
+ getGenerateValues: () => ({ modelKey: model.key }),
+ image,
+ kind: 'all',
+ models: [model, portraitModel],
+ queryClient: new QueryClient(),
+ t,
+ })
+ ).toBe(true);
+ expect(galleryApi.galleryImages.resolveMany).toHaveBeenCalledExactlyOnceWith(
+ ['portrait.png'],
+ expect.any(AbortSignal)
+ );
+ const references = setSettings.mock.calls[0]![0].referenceImages;
+ expect(references).toHaveLength(10000);
+ expect(references.at(-1).id).toBe('legacy-ip-adapter-9999');
+ expect(add).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })
+ );
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
index ce3adb80f1..f8bca9a8c0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
@@ -33,11 +33,14 @@ import {
isAccountScopeCurrent,
type AccountScope,
} from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+
+import type { CanvasRecallTarget } from './canvasRecall';
import {
buildImageRecallSettings,
getImageRecallMessage,
- getMetadataReferenceImages,
+ readMetadataReferenceImages,
getImageRecallTitle,
isImageRecallKindAvailable,
type ImageRecallKind,
@@ -202,18 +205,28 @@ export const executeLoadMediaWorkflow = async ({
const getReferenceImageName = (referenceImage: GenerateReferenceImage): string | null =>
referenceImage.config.image ? getEffectiveReferenceImage(referenceImage.config.image).image_name : null;
-/** The names of the references' effective assets the gallery still has, in one bulk lookup; none asks nothing. */
-const resolveAvailableReferenceImageNames = async (
- referenceImages: readonly GenerateReferenceImage[],
- signal: AbortSignal
-): Promise<ReadonlySet<string>> => {
- const names = [...new Set(referenceImages.flatMap((referenceImage) => getReferenceImageName(referenceImage) ?? []))];
-
- if (names.length === 0) {
- return new Set();
+/** Sequential, deduplicated lookups respect the Gallery API's 1,000-name request limit. */
+const resolveReferenceImages = async (
+ names: readonly string[],
+ signal: AbortSignal,
+ isCurrent: () => boolean = () => true
+): Promise<Map<string, GalleryImage>> => {
+ const assets = new Map<string, GalleryImage>();
+ const distinctNames = [...new Set(names)];
+ for (let offset = 0; offset < distinctNames.length; offset += 1000) {
+ if (signal.aborted || !isCurrent()) {
+ throw new DOMException('Recall is no longer current', 'AbortError');
+ }
+ const batch = distinctNames.slice(offset, offset + 1000);
+ const images = await galleryImages.resolveMany(batch, signal);
+ if (signal.aborted || !isCurrent()) {
+ throw new DOMException('Recall is no longer current', 'AbortError');
+ }
+ for (const image of images) {
+ assets.set(image.imageName, image);
+ }
}
-
- return new Set((await galleryImages.resolveMany(names, signal)).map((availableImage) => availableImage.imageName));
+ return assets;
};
/** Entries without an asset, or whose effective asset is not among `availableNames`, are dropped. */
@@ -231,7 +244,17 @@ export const filterAvailableReferenceImages = async (
referenceImages: GenerateReferenceImage[],
signal: AbortSignal
): Promise<GenerateReferenceImage[]> =>
- keepAvailableReferenceImages(referenceImages, await resolveAvailableReferenceImageNames(referenceImages, signal));
+ keepAvailableReferenceImages(
+ referenceImages,
+ new Set(
+ (
+ await resolveReferenceImages(
+ referenceImages.flatMap((reference) => getReferenceImageName(reference) ?? []),
+ signal
+ )
+ ).keys()
+ )
+ );
/** Why `getCurrentGenerateValues` answered null: no supported model, or no table to initialise from. */
export const getMissingGenerateValuesMessage = (t: TFunction): string =>
@@ -272,6 +295,7 @@ export const getCurrentGenerateValues = ({
export const executeImageRecall = async ({
commands,
+ canvasTarget,
getGenerateValues,
image,
isCanvasFrame,
@@ -283,6 +307,7 @@ export const executeImageRecall = async ({
t,
}: {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
+ canvasTarget?: CanvasRecallTarget;
/** Re-read after every await: the commit writes the whole Generate record, so a snapshot would revert newer edits. */
getGenerateValues: () => Record<string, unknown>;
image: GalleryImage;
@@ -298,6 +323,10 @@ export const executeImageRecall = async ({
t: TFunction;
}): Promise<boolean> => {
const owner = callerOwner ?? captureAccountScope();
+ const originalProject = canvasTarget?.getProject();
+ if (canvasTarget && !originalProject) {
+ return false;
+ }
if (!isAccountScopeCurrent(owner)) {
return false;
}
@@ -334,12 +363,83 @@ export const executeImageRecall = async ({
kind === 'dimensions' ? null : await fetchGalleryImageMetadata(queryClient, owner, image.imageName);
// Only all/remix recall references. Checked against the record, not the built list, so the check happens before
// the snapshot below.
- const availableReferenceNames =
- kind === 'all' || kind === 'remix'
- ? await resolveAvailableReferenceImageNames(getMetadataReferenceImages(metadata) ?? [], owner.signal)
- : new Set<string>();
+ const referenceRecord = kind === 'all' || kind === 'remix' ? readMetadataReferenceImages(metadata) : null;
+ let referenceAssets = new Map<string, GalleryImage>();
+ let referenceLookupFailed = false;
+ try {
+ referenceAssets = await resolveReferenceImages(
+ referenceRecord?.names ?? [],
+ owner.signal,
+ () => isAccountScopeCurrent(owner) && (!canvasTarget || Boolean(canvasTarget.getProject()))
+ );
+ } catch (error) {
+ assertAccountScopeCurrent(owner);
+ if (canvasTarget && !canvasTarget.getProject()) {
+ return false;
+ }
+ const networkFailure =
+ error instanceof TypeError &&
+ ['Failed to fetch', 'NetworkError when attempting to fetch resource.', 'Load failed', 'fetch failed'].includes(
+ error.message
+ );
+ if (!(error instanceof ApiError) && !networkFailure) {
+ throw error;
+ }
+ referenceLookupFailed = true;
+ }
+ const hydratedReferences = referenceRecord ? readMetadataReferenceImages(metadata, referenceAssets) : null;
+ const recordedReferences = hydratedReferences?.images ?? null;
+ const availableReferenceNames = new Set(referenceAssets.keys());
assertAccountScopeCurrent(owner);
+ if (canvasTarget && !canvasTarget.getProject()) {
+ return false;
+ }
+ const canvasRecall =
+ (kind === 'all' || kind === 'remix') &&
+ canvasTarget &&
+ originalProject &&
+ metadata &&
+ ('canvas_v3_metadata' in metadata ||
+ 'canvas_v2_metadata' in metadata ||
+ 'control_layers' in metadata ||
+ 'controlnets' in metadata ||
+ 't2iAdapters' in metadata ||
+ 'strength' in metadata ||
+ 'denoise_strength' in metadata)
+ ? await import('./canvasRecall')
+ : null;
+ const initialValues = canvasRecall ? readGenerateValues() : null;
+ const initialResult = initialValues
+ ? buildImageRecallSettings({
+ currentValues: initialValues,
+ image,
+ isCanvasFrame,
+ kind,
+ metadata,
+ referenceAssets,
+ models,
+ supportedModels,
+ vaeModels,
+ })
+ : null;
+ const canvasPlan =
+ canvasRecall && initialResult
+ ? await canvasRecall.prepareCanvasRecall({
+ metadata,
+ model: initialResult.values.model,
+ models,
+ owner,
+ isCurrent: () => canvasTarget?.getProject()?.canvas.document === originalProject?.canvas.document,
+ })
+ : null;
+ if (canvasPlan && canvasRecall && canvasTarget) {
+ await canvasRecall.settleCanvasRecall(canvasPlan, canvasTarget, owner);
+ }
+ assertAccountScopeCurrent(owner);
+ if (canvasTarget && !canvasTarget.getProject()) {
+ return false;
+ }
// Every read is above: nothing yields between this snapshot and the commit, so an edit made while the record
// or its references loaded stays in the values the recall writes.
const currentGenerateValues = readGenerateValues();
@@ -355,6 +455,7 @@ export const executeImageRecall = async ({
isCanvasFrame,
kind,
metadata,
+ referenceAssets,
models,
supportedModels,
vaeModels,
@@ -388,9 +489,36 @@ export const executeImageRecall = async ({
}
}
+ let canvasApplied = false;
+ if (canvasPlan && canvasRecall && canvasTarget && originalProject) {
+ if (initialResult?.values.model.key !== result.values.model.key) {
+ canvasPlan.problems.push('model-changed');
+ } else {
+ canvasApplied = canvasRecall.commitCanvasRecall({
+ plan: canvasPlan,
+ target: canvasTarget,
+ expectedDocument: originalProject.canvas.document,
+ restorePointName: t('widgets.gallery.itemActions.recall.beforeCanvasRecall'),
+ });
+ }
+ }
const skippedConcepts = result.skipped.filter((skipped) => skipped.subject === 'concept');
const skippedRefiner = result.skipped.find((skipped) => skipped.subject === 'refiner');
const skipMessages = [
+ referenceLookupFailed ||
+ readMetadataReferenceImages(metadata, referenceAssets, models, result.values.model).partial ||
+ referenceRecord?.names.some((name) => !availableReferenceNames.has(name)) ||
+ recordedReferences?.some((reference) => {
+ const name = getReferenceImageName(reference);
+ return name === null || !availableReferenceNames.has(name);
+ })
+ ? t('widgets.gallery.itemActions.recall.referenceImagesPartial')
+ : null,
+ canvasPlan && canvasPlan.problems.length > 0
+ ? t('widgets.gallery.itemActions.recall.canvasPartial', {
+ items: canvasRecall!.getCanvasRecallProblemsMessage(canvasPlan.problems, t),
+ })
+ : null,
skippedConcepts.length > 0
? t('widgets.gallery.itemActions.recall.conceptsNotRestored', {
concepts: skippedConcepts.map((skipped) => getSkippedConceptMessage(skipped, t)).join('; '),
@@ -400,7 +528,7 @@ export const executeImageRecall = async ({
].filter((message) => message !== null);
const skipMessage = skipMessages.length > 0 ? skipMessages.join(' ') : null;
- if (result.fields.length === 0) {
+ if (result.fields.length === 0 && !canvasApplied) {
commands.notifications.add({
kind: 'info',
message: skipMessage ?? t('widgets.gallery.itemActions.recall.imageMetadataUnsupported'),
@@ -409,10 +537,14 @@ export const executeImageRecall = async ({
return false;
}
- commands.generation.setSettings(result.values, projectId);
+ if (result.fields.length > 0) {
+ commands.generation.setSettings(result.values, projectId);
+ }
commands.notifications.add({
kind: 'success',
- message: getImageRecallMessage(result.fields, t),
+ message: canvasApplied
+ ? t('widgets.gallery.itemActions.recall.canvasRecalled')
+ : getImageRecallMessage(result.fields, t),
title: getImageRecallTitle(kind, t),
});
if (skipMessage) {
@@ -422,6 +554,16 @@ export const executeImageRecall = async ({
title: t('widgets.gallery.itemActions.recall.partiallyRecalled'),
});
}
+ if (canvasApplied && canvasPlan && canvasRecall && canvasTarget) {
+ const durable = await canvasRecall.finalizeCanvasRecallAssets(canvasPlan, canvasTarget, owner);
+ if (!durable && isAccountScopeCurrent(owner) && canvasTarget.getProject()) {
+ commands.notifications.add({
+ kind: 'info',
+ title: t('widgets.gallery.itemActions.recall.partiallyRecalled'),
+ message: t('widgets.gallery.itemActions.recall.canvasImagesTemporary'),
+ });
+ }
+ }
return true;
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts
index ddaff03d9f..16dbf36851 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts
@@ -139,16 +139,21 @@ describe('executeRecallParameters', () => {
);
});
- it('explains why nothing was applied instead of committing unchanged values', async () => {
+ it.each([
+ ['denoise_strength', 0.4],
+ ['control_layers', [{ model_key: 'controlnet' }]],
+ ['control_layers', []],
+ ['denoise_strength', null],
+ ] as const)('reports %s as unsupported when no canvas destination is available', async (key, value) => {
const { add, commands, setSettings } = createCommands();
- await expect(run(commands, { denoise_strength: 0.4 })).resolves.toBe(false);
+ await expect(run(commands, { [key]: value })).resolves.toBe(false);
expect(setSettings).not.toHaveBeenCalled();
expect(add).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'info',
- message: 'denoise_strength: not supported by the Generate panel',
+ message: `${key}: not supported by the Generate panel`,
title: 'No recalled parameters applied',
})
);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts
index afdb2af4db..b88f27c617 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.ts
@@ -4,6 +4,9 @@ import type { TFunction } from 'i18next';
import { getEffectiveReferenceImage, isSupportedGenerateModel, isVaeModelConfig } from '@features/generation/settings';
import { assertAccountScopeCurrent, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';
+import { DEFAULT_CANVAS_DENOISING_STRENGTH } from '@workbench/widgets/canvas/invoke/canvasStrength';
+
+import type { CanvasRecallTarget } from './canvasRecall';
import {
filterAvailableReferenceImages,
@@ -66,6 +69,7 @@ const verifyRecalledReferenceImages = async (
/** Apply one recall payload; stop quietly if the project disappears. Return true when at least one field commits. */
export const executeRecallParameters = async ({
commands,
+ canvasTarget,
getGenerateValues,
models,
owner,
@@ -74,6 +78,7 @@ export const executeRecallParameters = async ({
t,
}: {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
+ canvasTarget?: CanvasRecallTarget;
getGenerateValues: () => Record<string, unknown> | null;
models: readonly ComponentModelConfig[];
owner: AccountScope;
@@ -85,6 +90,11 @@ export const executeRecallParameters = async ({
return false;
}
+ const originalProject = canvasTarget?.getProject();
+ if (canvasTarget && !originalProject) {
+ return false;
+ }
+
const supportedModels = models.filter(isSupportedGenerateModel);
const vaeModels = models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig);
@@ -115,11 +125,17 @@ export const executeRecallParameters = async ({
return false;
}
- const result = buildRecallParametersSettings({ currentValues, models, parameters, supportedModels, vaeModels });
+ let result = buildRecallParametersSettings({ currentValues, models, parameters, supportedModels, vaeModels });
+ let availableReferenceNames: Set<string> | null = null;
if (result.fields.includes('referenceImages')) {
const existingIds = new Set(currentValues.referenceImages.map((referenceImage) => referenceImage.id));
await verifyRecalledReferenceImages(result, existingIds, owner.signal);
+ availableReferenceNames = new Set(
+ result.values.referenceImages
+ .filter((ref) => !existingIds.has(ref.id))
+ .flatMap((ref) => (ref.config.image ? [getEffectiveReferenceImage(ref.config.image).image_name] : []))
+ );
assertAccountScopeCurrent(owner);
if (getGenerateValues() === null) {
@@ -127,6 +143,91 @@ export const executeRecallParameters = async ({
}
}
+ const canvasRecall =
+ canvasTarget && originalProject && ('control_layers' in parameters || 'denoise_strength' in parameters)
+ ? await import('./canvasRecall')
+ : null;
+ const canvasPlan = canvasRecall
+ ? await canvasRecall.prepareCanvasRecall({
+ metadata: {
+ ...parameters,
+ ...(parameters.denoise_strength === null ? { denoise_strength: DEFAULT_CANVAS_DENOISING_STRENGTH } : {}),
+ ...(parameters.control_layers === null ? { control_layers: [] } : {}),
+ },
+ model: result.values.model,
+ models,
+ owner,
+ isCurrent: () => canvasTarget?.getProject()?.canvas.document === originalProject?.canvas.document,
+ })
+ : null;
+ if (canvasPlan && canvasRecall && canvasTarget) {
+ await canvasRecall.settleCanvasRecall(canvasPlan, canvasTarget, owner);
+ }
+ assertAccountScopeCurrent(owner);
+ const latestRaw = getGenerateValues();
+ if (latestRaw === null || (canvasTarget && !canvasTarget.getProject())) {
+ return false;
+ }
+ const latest = getCurrentGenerateValues({ generateValues: latestRaw, supportedModels });
+ if (!latest) {
+ return false;
+ }
+ // Rebuild after every awaited lookup so newer prompt/model edits are not overwritten by an old snapshot.
+ const previous = result;
+ result = buildRecallParametersSettings({ currentValues: latest, models, parameters, supportedModels, vaeModels });
+ if (availableReferenceNames !== null && result.fields.includes('referenceImages')) {
+ const existingIds = new Set(latest.referenceImages.map((ref) => ref.id));
+ const kept = result.values.referenceImages.filter(
+ (ref) =>
+ existingIds.has(ref.id) ||
+ (ref.config.image && availableReferenceNames.has(getEffectiveReferenceImage(ref.config.image).image_name))
+ );
+ const anyRecalled = kept.some((ref) => !existingIds.has(ref.id));
+ if (
+ !anyRecalled &&
+ ((Array.isArray(parameters.ip_adapters) && parameters.ip_adapters.length > 0) ||
+ (Array.isArray(parameters.reference_images) && parameters.reference_images.length > 0))
+ ) {
+ result.values.referenceImages = result.retainedReferenceImages;
+ result.fields = result.fields.filter((field) => field !== 'referenceImages');
+ } else {
+ result.values.referenceImages = kept;
+ }
+ result.skipped.push(
+ ...previous.skipped.filter((skip) => skip.key === 'reference_images' && skip.reason === 'unresolved')
+ );
+ }
+ let canvasApplied = false;
+ if (canvasPlan && canvasRecall && canvasTarget && originalProject) {
+ if (previous.values.model.key !== result.values.model.key) {
+ canvasPlan.problems.push('model-changed');
+ } else {
+ canvasApplied = canvasRecall.commitCanvasRecall({
+ plan: canvasPlan,
+ target: canvasTarget,
+ expectedDocument: originalProject.canvas.document,
+ append: parameters.append === true,
+ restorePointName: t('widgets.gallery.itemActions.recall.beforeCanvasRecall'),
+ });
+ }
+ result.skipped.push(
+ ...canvasPlan.problems.map((detail) => ({
+ key: 'control_layers',
+ reason: 'unresolved' as const,
+ detail: canvasRecall.getCanvasRecallProblemsMessage([detail], t),
+ }))
+ );
+ }
+ if (canvasApplied) {
+ result.fields.push('canvas');
+ }
+ if (!canvasTarget) {
+ for (const key of ['control_layers', 'denoise_strength']) {
+ if (key in parameters) {
+ result.skipped.push({ key, reason: 'unsupported' });
+ }
+ }
+ }
const skipMessage = result.skipped.length > 0 ? getRecallParametersSkipMessage(result.skipped, t) : null;
if (result.fields.length === 0) {
@@ -138,7 +239,9 @@ export const executeRecallParameters = async ({
return false;
}
- commands.generation.setSettings(result.values, projectId);
+ if (result.fields.some((field) => field !== 'canvas')) {
+ commands.generation.setSettings(result.values, projectId);
+ }
commands.notifications.add({
kind: 'success',
message: getRecallParametersMessage(result.fields, t),
@@ -151,6 +254,16 @@ export const executeRecallParameters = async ({
title: t('widgets.gallery.itemActions.recall.parameters.partiallyApplied'),
});
}
+ if (canvasApplied && canvasPlan && canvasRecall && canvasTarget) {
+ const durable = await canvasRecall.finalizeCanvasRecallAssets(canvasPlan, canvasTarget, owner);
+ if (!durable && isAccountScopeCurrent(owner) && canvasTarget.getProject()) {
+ commands.notifications.add({
+ kind: 'info',
+ title: t('widgets.gallery.itemActions.recall.parameters.partiallyApplied'),
+ message: t('widgets.gallery.itemActions.recall.canvasImagesTemporary'),
+ });
+ }
+ }
return true;
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index d4092e8b89..a5700c2890 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -24,7 +24,12 @@ import { compileGenerateGraph } from '@features/generation/graph';
import { normalizeReferenceImages } from '@features/generation/settings';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { buildImageRecallSettings, getImageRecallCapabilities, type ImageRecallKind } from './imageRecall';
+import {
+ buildImageRecallSettings,
+ getImageRecallCapabilities,
+ readMetadataReferenceImages,
+ type ImageRecallKind,
+} from './imageRecall';
const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
@@ -2797,3 +2802,272 @@ describe('legacy records', () => {
});
});
});
+
+describe('legacy family metadata parity', () => {
+ it('restores recorded Ideogram sampler overrides and explicit preset defaults', () => {
+ const model: MainModelConfig = {
+ base: 'ideogram-4',
+ key: 'ideogram',
+ name: 'Ideogram',
+ type: 'main',
+ format: 'diffusers',
+ };
+ const recall = (metadata: unknown) =>
+ buildImageRecallSettings({
+ currentValues: createValues({ model, modelKey: model.key, ideogram4Steps: 70, ideogram4Mu: 3 }),
+ image,
+ kind: 'all',
+ metadata,
+ models: [model],
+ supportedModels: [model],
+ vaeModels: [],
+ });
+ const metadata = {
+ model,
+ ideogram4_sampler_preset: 'V4_TURBO_12',
+ ideogram4_steps: 26,
+ ideogram4_guidance_scale: 4.5,
+ ideogram4_mu: -1.5,
+ ideogram4_color_palette: ['green', 'gold'],
+ };
+ expect(recall(metadata)?.values).toMatchObject({
+ ideogram4SamplerPreset: 'V4_TURBO_12',
+ ideogram4Steps: 26,
+ ideogram4GuidanceScale: 4.5,
+ ideogram4Mu: -1.5,
+ ideogram4ColorPalette: ['green', 'gold'],
+ });
+ expect(
+ recall({ model, ideogram4_steps: null, ideogram4_guidance_scale: null, ideogram4_mu: null })?.values
+ ).toMatchObject({ ideogram4Steps: null, ideogram4GuidanceScale: null, ideogram4Mu: null });
+ expect(recall({ model, generation_mode: 'ideogram4_txt2img' })?.values).toMatchObject({
+ ideogram4Steps: null,
+ ideogram4GuidanceScale: null,
+ ideogram4Mu: null,
+ });
+ expect(recall({ model, ideogram4_steps: 2.5, ideogram4_mu: 100 })?.values).toMatchObject({
+ ideogram4Steps: 70,
+ ideogram4Mu: 3,
+ });
+ });
+
+ it('restores legacy Wan VAE and low-noise guidance without applying them to another family', () => {
+ const model: MainModelConfig = { base: 'wan', key: 'wan', name: 'Wan', type: 'main', format: 'diffusers' };
+ const vae: VaeModelConfig = { base: 'wan', key: 'wan-vae', name: 'Wan VAE', type: 'vae', latent_channels: 16 };
+ const result = buildImageRecallSettings({
+ currentValues: createValues({ model, modelKey: model.key }),
+ image,
+ kind: 'remix',
+ metadata: { model, wan_vae_model: vae, wan_guidance_scale_low_noise: 23.5 },
+ models: [model, vae],
+ supportedModels: [model],
+ vaeModels: [vae],
+ });
+ expect(result?.values).toMatchObject({ vae, wanGuidanceScaleLowNoise: 23.5 });
+ });
+});
+
+it.each(['controlnets', 't2iAdapters', 'ipAdapters'] as const)(
+ 'enables All/Remix for standalone name-only %s before asset hydration',
+ (key) => {
+ const adapter = {
+ ip_adapter_model: { key: 'ip', name: 'IP', base: 'sdxl', type: 'ip_adapter' },
+ image: { image_name: 'portrait.png' },
+ weight: 0.5,
+ clip_vision_model: 'ViT-H',
+ method: 'full',
+ begin_step_percent: 0,
+ end_step_percent: 1,
+ };
+ const capabilities = getImageRecallCapabilities({
+ currentValues: createValues(),
+ image,
+ metadata: { [key]: [adapter] },
+ models: [sdxlModel],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ });
+ expect(capabilities).toMatchObject({ all: true, remix: true });
+ }
+);
+
+it.each(['array', 'entities'] as const)(
+ 'restores historical Canvas referenceImages %s through Generate recall',
+ (shape) => {
+ const ip = { base: 'sdxl', type: 'ip_adapter', key: 'ip', name: 'IP' } as ComponentModelConfig;
+ const entry = {
+ id: 'old',
+ isEnabled: false,
+ ipAdapter: {
+ type: 'ip_adapter',
+ model: ip,
+ image: { image_name: 'portrait.png', width: 320, height: 200 },
+ weight: 0.3,
+ method: 'composition',
+ clipVisionModel: 'ViT-L',
+ beginEndStepPct: [0.1, 0.8],
+ },
+ };
+ const result = buildImageRecallSettings({
+ currentValues: createValues(),
+ image,
+ kind: 'all',
+ metadata: { canvas_v2_metadata: { referenceImages: shape === 'array' ? [entry] : { entities: [entry] } } },
+ models: [sdxlModel, ip],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ });
+ expect(result?.values.referenceImages).toEqual([
+ {
+ id: 'old',
+ isEnabled: false,
+ config: { ...entry.ipAdapter, image: { original: { image: entry.ipAdapter.image } } },
+ },
+ ]);
+ }
+);
+
+it.each([false, true])('keeps modern references authoritative over v4 aliases (empty=%s)', (empty) => {
+ const ip = { base: 'sdxl', type: 'ip_adapter', key: 'ip', name: 'IP' } as ComponentModelConfig;
+ const legacy = {
+ ip_adapter_model: ip,
+ image: [{ image_name: 'legacy.png', width: 200, height: 100 }],
+ weight: 0.5,
+ clip_vision_model: 'ViT-G',
+ method: 'style',
+ begin_step_percent: 0.2,
+ end_step_percent: 0.8,
+ };
+ const modern = {
+ id: 'modern',
+ isEnabled: true,
+ config: {
+ type: 'ip_adapter',
+ model: ip,
+ image: { image_name: 'modern.png', width: 400, height: 200 },
+ weight: 0.4,
+ clipVisionModel: 'ViT-H',
+ method: 'full',
+ beginEndStepPct: [0, 1],
+ },
+ };
+ const input = {
+ currentValues: createValues({ referenceImages: normalizeReferenceImages([modern]) }),
+ image,
+ kind: 'all' as const,
+ models: [sdxlModel, ip],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ };
+ const result = buildImageRecallSettings({
+ ...input,
+ metadata: { ref_images: empty ? [] : [modern], ipAdapters: [legacy] },
+ });
+ expect(result?.values.referenceImages.map(({ id }) => id)).toEqual(empty ? [] : ['modern']);
+ const legacyResult = buildImageRecallSettings({ ...input, metadata: { ipAdapters: [legacy] } });
+ expect(legacyResult?.values.referenceImages).toEqual([
+ expect.objectContaining({
+ config: expect.objectContaining({
+ model: ip,
+ image: { original: { image: { image_name: 'legacy.png', width: 200, height: 100 } } },
+ clipVisionModel: 'ViT-G',
+ method: 'style',
+ weight: 0.5,
+ beginEndStepPct: [0.2, 0.8],
+ }),
+ }),
+ ]);
+});
+
+it('preserves a valid zero-width legacy IP step window instead of inventing a wider schedule', () => {
+ const adapter = { base: 'sdxl', key: 'ip', name: 'IP', type: 'ip_adapter' } as ComponentModelConfig;
+ const result = buildImageRecallSettings({
+ currentValues: createValues(),
+ image,
+ kind: 'all',
+ metadata: {
+ ipAdapters: [
+ {
+ ip_adapter_model: adapter,
+ image: { image_name: 'portrait.png', width: 100, height: 100 },
+ weight: -0.5,
+ clip_vision_model: 'ViT-H',
+ method: 'full',
+ begin_step_percent: 0.2,
+ end_step_percent: 0.2,
+ },
+ ],
+ },
+ models: [sdxlModel, adapter],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ });
+ expect(result?.values.referenceImages[0]?.config).toMatchObject({
+ model: adapter,
+ weight: -0.5,
+ beginEndStepPct: [0.2, 0.2],
+ });
+});
+
+it.each(['array', 'entities'] as const)(
+ 'reports refused historical %s references after fallback selection, preserving existing references',
+ (shape) => {
+ const adapter = { base: 'sdxl', key: 'ip', name: 'IP', type: 'ip_adapter' } as ComponentModelConfig;
+ const current = normalizeReferenceImages([
+ {
+ id: 'current',
+ config: {
+ type: 'ip_adapter',
+ model: adapter,
+ image: { image_name: 'current.png', width: 100, height: 100 },
+ weight: 0.5,
+ },
+ },
+ ]);
+ const reference = { id: 'old', ipAdapter: { type: 'ip_adapter', image: null } };
+ const metadata = {
+ positive_prompt: 'still recallable',
+ canvas_v2_metadata: {
+ rasterLayers: [],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ referenceImages: shape === 'array' ? [reference] : { entities: [reference] },
+ },
+ };
+ const input = {
+ currentValues: createValues({ referenceImages: current }),
+ image,
+ kind: 'all' as const,
+ models: [sdxlModel, adapter],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ };
+ expect(readMetadataReferenceImages(metadata)).toEqual({ images: null, names: [], partial: true });
+ const refused = buildImageRecallSettings({ ...input, metadata });
+ expect(refused?.values.referenceImages).toEqual(current);
+ expect(refused?.fields).not.toContain('referenceImages');
+ const fallback = {
+ ip_adapter_model: adapter,
+ image: { image_name: 'fallback.png', width: 100, height: 100 },
+ weight: 0.4,
+ clip_vision_model: 'ViT-H',
+ method: 'full',
+ begin_step_percent: 0,
+ end_step_percent: 1,
+ };
+ const recovered = { ...metadata, ipAdapters: [fallback] };
+ expect(readMetadataReferenceImages(recovered).partial).toBe(false);
+ expect(
+ buildImageRecallSettings({ ...input, metadata: recovered })?.values.referenceImages[0]?.config.image
+ ).toEqual({ original: { image: fallback.image } });
+ expect(readMetadataReferenceImages({ ...recovered, ref_images: [] })).toEqual({
+ images: [],
+ names: [],
+ partial: false,
+ });
+ expect(
+ buildImageRecallSettings({ ...input, metadata: { ...recovered, ref_images: [] } })?.values.referenceImages
+ ).toEqual([]);
+ }
+);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index 4616814f8b..b209bdf1c1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -14,6 +14,7 @@ import {
clampAnimaInpaintAdapterWeight,
clampDimension,
cloneGenerateWidgetValues,
+ isIdeogram4SamplerPreset,
deriveAspectRatioId,
getCompatibleReferenceImages,
getDimensionGrid,
@@ -65,6 +66,15 @@ import { SEED_MAX } from '@platform/core/seed';
import { resolveRecordedModel, toRecordedModelRef, type RecordedModelPolicy } from './recordedModel';
+const hasCanvasRecall = (metadata: unknown): boolean =>
+ isRecord(metadata) &&
+ ('canvas_v3_metadata' in metadata ||
+ 'canvas_v2_metadata' in metadata ||
+ 'control_layers' in metadata ||
+ 'controlnets' in metadata ||
+ 't2iAdapters' in metadata ||
+ typeof (metadata.strength ?? metadata.denoise_strength) === 'number');
+
export type ImageRecallKind = 'all' | 'remix' | 'prompts' | 'seed' | 'dimensions' | 'clipSkip';
export interface ImageRecallCapabilities {
@@ -388,6 +398,13 @@ const getMetadataVae = (
model: GenerateModelConfig,
vaeModels: VaeModelConfig[]
): VaeModelConfig | null | undefined => {
+ if (!isRecord(metadata)) {
+ return undefined;
+ }
+ const legacyKey = ({ 'qwen-image': 'qwen_image_vae', wan: 'wan_vae_model' } as Record<string, string>)[model.base];
+ if (!('vae' in metadata) && legacyKey && legacyKey in metadata) {
+ metadata = { ...metadata, vae: metadata[legacyKey] };
+ }
if (!isRecord(metadata) || !('vae' in metadata)) {
return undefined;
}
@@ -610,6 +627,46 @@ const getMetadataModelTuning = (
};
}
+ if (model.base === 'wan') {
+ const raw = metadata.wan_guidance_scale_low_noise;
+ const parsed = raw === null || (typeof raw === 'number' && Number.isFinite(raw) && raw >= 1) ? raw : undefined;
+ const guidance = recordedOrDefault('wan_guidance_scale_low_noise', parsed, null);
+ return guidance === undefined ? {} : { wanGuidanceScaleLowNoise: guidance };
+ }
+ if (model.base === 'ideogram-4') {
+ const preset = isIdeogram4SamplerPreset(metadata.ideogram4_sampler_preset)
+ ? metadata.ideogram4_sampler_preset
+ : undefined;
+ const steps = getBoundedNumber(metadata, 'ideogram4_steps', 2, 100);
+ const overrides = {
+ ideogram4Steps: recordedOrDefault(
+ 'ideogram4_steps',
+ metadata.ideogram4_steps === null ? null : steps !== null && Number.isInteger(steps) ? steps : undefined,
+ null
+ ),
+ ideogram4GuidanceScale: recordedOrDefault(
+ 'ideogram4_guidance_scale',
+ metadata.ideogram4_guidance_scale === null
+ ? null
+ : (getBoundedNumber(metadata, 'ideogram4_guidance_scale', 1, 20) ?? undefined),
+ null
+ ),
+ ideogram4Mu: recordedOrDefault(
+ 'ideogram4_mu',
+ metadata.ideogram4_mu === null ? null : (getBoundedNumber(metadata, 'ideogram4_mu', -4, 4) ?? undefined),
+ null
+ ),
+ };
+ const palette = metadata.ideogram4_color_palette;
+ return {
+ ...(preset === undefined ? {} : { ideogram4SamplerPreset: preset }),
+ ...Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined)),
+ ...(Array.isArray(palette) && palette.length <= 256 && palette.every((term) => typeof term === 'string')
+ ? { ideogram4ColorPalette: palette }
+ : {}),
+ };
+ }
+
if (model.base === 'krea-2') {
// Recorded only when the switch was sent: with edit references and a LoRA. A record without it says nothing
// about the switch, so the user's setting stays.
@@ -1049,51 +1106,184 @@ const getMetadataConcepts = (
skipped.push({ name: installed.name, reason: 'duplicate', subject: 'concept' });
} else {
// Kept exactly: graphs and model defaults accept weights beyond the panel's typed range, which bounds only edits.
- loras.push({ isEnabled: true, model: installed, weight });
+ loras.push({
+ isEnabled:
+ getString(metadata, 'metadata_source') === 'canvas_save' ? (getBoolean(entry, 'isEnabled') ?? true) : true,
+ model: installed,
+ weight,
+ });
}
}
return { loras, skipped };
};
-/**
- * The references the image was generated with, or null when the record says nothing about them. An explicitly
- * empty modern list means it used none; only a list with no usable entry falls back to the pre-v6 canvas slot.
- */
-export const getMetadataReferenceImages = (metadata: unknown): GenerateReferenceImage[] | null => {
- if (!isRecord(metadata)) {
- return null;
- }
+// A refused sentinel makes truncation partial without inspecting entries beyond the recall limit.
+const boundReferenceEntries = (entries: unknown[]): unknown[] =>
+ entries.length > 10000 ? [...entries.slice(0, 10000), null] : entries;
- if (Array.isArray(metadata.ref_images) && metadata.ref_images.length === 0) {
- return [];
- }
-
- const direct = normalizeReferenceImages(metadata.ref_images).filter(
- (referenceImage) => referenceImage.config.image !== null
- );
- if (direct.length > 0) {
- return direct;
- }
+/** Historical Canvas global references were serialized both as an array and as an entity container. */
+export const getLegacyCanvasReferenceEntries = (metadata: unknown): unknown[] | null => {
+ const references = getRecord(metadata, 'canvas_v2_metadata')?.referenceImages;
+ const entries = Array.isArray(references) ? references : isRecord(references) ? references.entities : null;
+ return Array.isArray(entries) ? entries : null;
+};
- const canvasMetadata = getRecord(metadata, 'canvas_v2_metadata');
- const referenceImages = getRecord(canvasMetadata, 'referenceImages');
- const legacyEntities = referenceImages?.entities;
- if (!Array.isArray(legacyEntities)) {
+/** A bounded projection of supported reference records, before asset dimensions are available. */
+const getMetadataReferenceEntries = (metadata: unknown): unknown[] | null => {
+ if (!isRecord(metadata)) {
return null;
}
-
- const legacy = normalizeReferenceImages(
- legacyEntities.map((entry) =>
+ if (
+ Array.isArray(metadata.ref_images) &&
+ (metadata.ref_images.length === 0 ||
+ normalizeReferenceImages(metadata.ref_images.slice(0, 10000)).some((ref) => ref.config.image))
+ ) {
+ return boundReferenceEntries(metadata.ref_images);
+ }
+ const legacyEntities = getLegacyCanvasReferenceEntries(metadata);
+ let rejectedHistoricalReferences = false;
+ if (Array.isArray(legacyEntities) && legacyEntities.length > 0) {
+ const entries = boundReferenceEntries(legacyEntities).map((entry) =>
isRecord(entry) && isRecord(entry.ipAdapter)
? { config: entry.ipAdapter, id: entry.id, isEnabled: entry.isEnabled }
: entry
- )
- ).filter((referenceImage) => referenceImage.config.image !== null);
+ );
+ if (normalizeReferenceImages(entries).some((ref) => ref.config.image)) {
+ return entries;
+ }
+ rejectedHistoricalReferences = true;
+ }
+ if (!('ipAdapters' in metadata)) {
+ return rejectedHistoricalReferences ? [null] : null;
+ }
+ if (!Array.isArray(metadata.ipAdapters) || metadata.ipAdapters.length === 0) {
+ return [null];
+ }
+ return boundReferenceEntries(metadata.ipAdapters).map((entry, index) => {
+ if (!isRecord(entry)) {
+ return null;
+ }
+ // The modern slot holds one image. Splitting a multi-image embedding changes what the adapter computes.
+ const image = Array.isArray(entry.image) && entry.image.length === 1 ? entry.image[0] : entry.image;
+ const model = toRecordedModelRef(entry.ip_adapter_model);
+ const begin = entry.begin_step_percent ?? 0,
+ end = entry.end_step_percent ?? 1;
+ if (
+ !isRecord(image) ||
+ typeof image.image_name !== 'string' ||
+ !image.image_name ||
+ !model ||
+ typeof entry.weight !== 'number' ||
+ !Number.isFinite(entry.weight) ||
+ entry.weight < -1 ||
+ entry.weight > 2 ||
+ typeof begin !== 'number' ||
+ typeof end !== 'number' ||
+ !Number.isFinite(begin) ||
+ !Number.isFinite(end) ||
+ begin < 0 ||
+ end > 1 ||
+ begin > end ||
+ !['full', 'style', 'composition', 'style_strong', 'style_precise'].includes(String(entry.method)) ||
+ !['ViT-L', 'ViT-H', 'ViT-G'].includes(String(entry.clip_vision_model))
+ ) {
+ return null;
+ }
+ return {
+ legacyIPAdapter: true,
+ id: `legacy-ip-adapter-${index}`,
+ isEnabled: true,
+ config: {
+ type: 'ip_adapter',
+ image,
+ weight: entry.weight,
+ beginEndStepPct: [begin, end],
+ method: entry.method,
+ clipVisionModel: entry.clip_vision_model,
+ model: {
+ key: model.key ?? '',
+ hash: model.hash ?? undefined,
+ name: model.name ?? '',
+ base: model.base ?? '',
+ type: model.type ?? 'ip_adapter',
+ },
+ },
+ };
+ });
+};
- return legacy.length > 0 ? legacy : null;
+/** Reads references without transport; name-only v4 assets wait for their actual Gallery dimensions. */
+export const readMetadataReferenceImages = (
+ metadata: unknown,
+ assets?: ReadonlyMap<string, Pick<GalleryImage, 'width' | 'height'>>,
+ models?: readonly ComponentModelConfig[],
+ mainModel?: GenerateModelConfig
+): { images: GenerateReferenceImage[] | null; names: string[]; partial: boolean } => {
+ const entries = getMetadataReferenceEntries(metadata);
+ if (entries === null) {
+ return { images: null, names: [], partial: false };
+ }
+ const names = new Set<string>();
+ const ipAdapterModels = models?.filter((model) => model.type === 'ip_adapter');
+ const hydrated = entries.map((entry) => {
+ if (!isRecord(entry) || !isRecord(entry.config)) {
+ return entry;
+ }
+ const rawEntry = entry;
+ let config = entry.config;
+ if (config.type === 'ip_adapter' && Array.isArray(config.weight)) {
+ return null;
+ }
+ if (entry.legacyIPAdapter && models) {
+ const ref = toRecordedModelRef(config.model);
+ const installed = ref
+ ? resolveRecordedModel(ref, ipAdapterModels ?? [], { ...IMAGE_RECORDED_MODEL_POLICY, hashMiss: 'matchName' })
+ : null;
+ if (
+ !installed ||
+ installed === 'ambiguous' ||
+ (ref?.base && ref.base !== installed.base) ||
+ (ref?.type && ref.type !== installed.type) ||
+ (mainModel && installed.base !== mainModel.base)
+ ) {
+ return null;
+ }
+ config = { ...config, model: installed };
+ entry = { ...entry, config };
+ }
+ const asset = config.image;
+ const effective =
+ isRecord(asset) && isRecord(asset.crop)
+ ? asset.crop.image
+ : isRecord(asset) && isRecord(asset.original)
+ ? asset.original.image
+ : asset;
+ const name = isRecord(effective) ? (effective.image_name ?? effective.imageName) : null;
+ if (typeof name === 'string' && name.length > 0) {
+ names.add(name);
+ const resolved = assets?.get(name);
+ if (resolved && isRecord(asset) && !('original' in asset)) {
+ return {
+ ...rawEntry,
+ config: { ...config, image: { image_name: name, width: resolved.width, height: resolved.height } },
+ };
+ }
+ }
+ return entry;
+ });
+ const images = normalizeReferenceImages(hydrated).filter((ref) => ref.config.image !== null);
+ return {
+ images: images.length > 0 || entries.length === 0 ? images : null,
+ names: [...names],
+ partial: images.length < entries.length,
+ };
};
+/** Existing pure callers can read dimensioned references; transport recall hydrates name-only records first. */
+export const getMetadataReferenceImages = (metadata: unknown): GenerateReferenceImage[] | null =>
+ readMetadataReferenceImages(metadata).images;
+
/**
* Point each recorded adapter at the installed model it names, or clear it so Generate asks for one: a reinstall gives
* the adapter a new key, and a stale key would pass validation and fail only on the server.
@@ -1176,10 +1366,12 @@ export const getImageRecallCapabilities = ({
const hasSize = hasMetadataSize(metadata, currentValues.model);
const hasSettings = hasGenerationSettings(metadata, clipSkipModel);
const hasComponents = hasComponentModels(metadata, models);
- const recordedReferenceImages = getMetadataReferenceImages(metadata);
+ const referenceRecord = readMetadataReferenceImages(metadata);
+ const recordedReferenceImages = referenceRecord.images;
const hasReferenceImages =
- recordedReferenceImages !== null &&
- (recordedReferenceImages.length > 0 || currentValues.referenceImages.length > 0);
+ referenceRecord.names.length > 0 ||
+ (recordedReferenceImages !== null &&
+ (recordedReferenceImages.length > 0 || currentValues.referenceImages.length > 0));
const hasModel = supportedMetadataModel !== null;
const hasProviderOptions = hasExternalProvider(metadata, clipSkipModel);
const hasRebalance = hasKrea2Rebalance(metadata, clipSkipModel) || hasKrea2SeedVariance(metadata, clipSkipModel);
@@ -1207,7 +1399,8 @@ export const getImageRecallCapabilities = ({
hasRefiner ||
hasSkipLayers ||
hasTuning ||
- hasAdapterSettings;
+ hasAdapterSettings ||
+ hasCanvasRecall(metadata);
const hasNonSeedMetadata =
hasModel ||
hasVae ||
@@ -1224,7 +1417,8 @@ export const getImageRecallCapabilities = ({
hasRefiner ||
hasSkipLayers ||
hasTuning ||
- hasAdapterSettings;
+ hasAdapterSettings ||
+ hasCanvasRecall(metadata);
return {
all: hasAnyMetadata && isImageRecallKindAvailable('all'),
@@ -1243,6 +1437,7 @@ export const buildImageRecallSettings = ({
isCanvasFrame = false,
kind,
metadata,
+ referenceAssets,
supportedModels,
models,
vaeModels,
@@ -1253,6 +1448,7 @@ export const buildImageRecallSettings = ({
isCanvasFrame?: boolean;
kind: ImageRecallKind;
metadata: unknown;
+ referenceAssets?: ReadonlyMap<string, Pick<GalleryImage, 'width' | 'height'>>;
supportedModels: GenerateModelConfig[];
models: ComponentModelConfig[];
vaeModels: VaeModelConfig[];
@@ -1266,6 +1462,7 @@ export const buildImageRecallSettings = ({
let values: GenerateWidgetValues = cloneGenerateWidgetValues(currentValues);
// A restored provider size is what the provider was asked for; the recorded size may be a Canvas frame instead.
let restoredProviderSize = false;
+ let referenceRecall: ReturnType<typeof readMetadataReferenceImages> | null = null;
if (kind === 'all' || kind === 'remix') {
const model = getSupportedMetadataModel(metadata, supportedModels);
@@ -1372,7 +1569,8 @@ export const buildImageRecallSettings = ({
// Recalled reference images must fit the effective model — when the
// metadata model was not recalled (e.g. uninstalled), `values.model` is
// still the current one and incompatible configs are re-targeted or dropped.
- const recordedReferenceImages = getMetadataReferenceImages(metadata);
+ referenceRecall = readMetadataReferenceImages(metadata, referenceAssets, models, values.model);
+ const recordedReferenceImages = referenceRecall.images;
const referenceImages = getCompatibleReferenceImages(
resolveReferenceImageModels(recordedReferenceImages ?? [], models),
values.model,
@@ -1497,7 +1695,12 @@ export const buildImageRecallSettings = ({
}
}
- return fields.length > 0 || skipped.length > 0 ? { fields, skipped, values } : null;
+ return fields.length > 0 ||
+ skipped.length > 0 ||
+ ((kind === 'all' || kind === 'remix') &&
+ (hasCanvasRecall(metadata) || referenceRecall?.partial || (referenceRecall?.names.length ?? 0) > 0))
+ ? { fields, skipped, values }
+ : null;
};
export const getImageRecallTitle = (kind: ImageRecallKind, t: TFunction): string =>
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
index 031c599b1a..cef424f2e0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts
@@ -586,7 +586,7 @@ describe('buildRecallParametersSettings', () => {
expect(result.skipped).toEqual([{ detail: sd3.name, key: 'reference_images', reason: 'incompatible' }]);
});
- it('reports parameters the Generate panel has no home for, ignoring empty lists', () => {
+ it('leaves canvas parameters to the canvas owner, ignoring empty lists', () => {
const result = build(currentFor(sdxl), {
control_layers: [{ model_key: 'controlnet' }],
denoise_strength: 0.5,
@@ -594,7 +594,7 @@ describe('buildRecallParametersSettings', () => {
});
expect(result.fields).toEqual(['prompts']);
- expect(result.skipped.map((skip) => skip.key).sort()).toEqual(['control_layers', 'denoise_strength']);
+ expect(result.skipped).toEqual([]);
expect(result.skipped.every((skip) => skip.reason === 'unsupported')).toBe(true);
expect(build(currentFor(sdxl), { control_layers: [] }).skipped).toEqual([]);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
index 4e78cb2a3d..f36429caf5 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts
@@ -80,7 +80,8 @@ export type RecallParameterField =
| 'clipSkip'
| 'loras'
| 'referenceImages'
- | 'refiner';
+ | 'refiner'
+ | 'canvas';
export type RecallParameterSkipReason = 'unsupported' | 'unresolved' | 'incompatible' | 'invalid' | 'limit';
@@ -128,6 +129,8 @@ export const isRecallParametersAvailable = (parameters: Record<string, unknown>)
const HANDLED_KEYS = new Set([
'append',
+ 'control_layers',
+ 'denoise_strength',
'cfg_rescale_multiplier',
'cfg_scale',
'clip_skip',
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
index 5ea9f3d098..3c8048c0e0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
@@ -49,6 +49,7 @@ const createDeps = () => {
return {
active,
commands: {
+ canvas: {} as WorkbenchCommands['canvas'],
generation: {} as WorkbenchCommands['generation'],
notifications: { reportError } as unknown as WorkbenchCommands['notifications'],
widgets: {} as WorkbenchCommands['widgets'],
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
index c29bb8090a..23a48d90bb 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
@@ -101,7 +101,7 @@ export const attachRecallParametersRuntime = ({
reveal,
t,
}: {
- commands: Pick<WorkbenchCommands, 'generation' | 'notifications' | 'widgets'>;
+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications' | 'widgets' | 'canvas'>;
getSessionUserId?: () => string | null;
hub: Pick<SocketHub, 'on'>;
load?: () => Promise<RecallParametersRuntimeModule>;
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
index 98b92f152f..a07687a891 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
@@ -20,7 +20,7 @@ export const createRecallParametersRuntime = ({
reveal,
t,
}: {
- commands: Pick<WorkbenchCommands, 'generation' | 'notifications' | 'widgets'>;
+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications' | 'widgets' | 'canvas'>;
getSessionUserId?: () => string | null;
hub: Pick<SocketHub, 'on'>;
queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
@@ -33,6 +33,7 @@ export const createRecallParametersRuntime = ({
apply: async ({ parameters }, { models, owner, projectId }) => {
const applied = await executeRecallParameters({
commands,
+ canvasTarget: { commands, projectId, getProject: () => queries.getProject(projectId) ?? null },
t,
getGenerateValues: () => {
const project = queries.getProject(projectId);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index acccf65c41..032b58d1c9 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -1203,6 +1203,13 @@ export const useImageActions = ({
const owner = captureAccountScope();
const didRecall = await executeImageRecall({
commands,
+ canvasTarget: projectId
+ ? {
+ commands,
+ projectId,
+ getProject: () => (queries.isActiveProject(projectId) ? (getLatestProject() ?? null) : null),
+ }
+ : undefined,
getGenerateValues: getLatestGenerateValues,
image,
isCanvasFrame: getLatestProject()?.invocation.sourceId === 'canvas',
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
index e8e6318d68..a5dc738ee7 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
@@ -1725,3 +1725,68 @@ describe('recall of what the video graphs record', () => {
expect(result?.mediaNames.conditioningClip).toEqual({ name: 'song.mp4', role: 'audio' });
});
});
+
+it('reads the legacy Wan VAE slot', () => {
+ const vae = { key: 'legacy-vae', base: 'wan', name: 'Wan VAE', type: 'vae' };
+ expect(parseVideoRecallRecord({ generation_mode: 'wan_t2v', wan_vae_model: vae })?.components).toContainEqual({
+ modelType: 'vae',
+ valuesKey: 'vae',
+ ref: { key: vae.key, base: vae.base, name: vae.name, type: vae.type, hash: null },
+ });
+});
+
+describe('legacy H3 duration recall', () => {
+ const model = h3Model();
+ const currentValues = { ...createDefaultVideoWidgetValues([model]), numFrames: 175 };
+ const metadata = (duration: unknown, extra: Record<string, unknown> = {}) => ({
+ generation_mode: 'minimax_h3_t2v',
+ model: { key: model.key },
+ minimax_h3_duration_seconds: duration,
+ ...extra,
+ });
+
+ it.each([
+ [5, 124],
+ [6, 141],
+ [7, 175],
+ [8, 192],
+ [9, 209],
+ [10, 243],
+ [11, 260],
+ [12, 294],
+ [13, 311],
+ [14, 345],
+ ])('restores the emitted frame count for the legacy %is duration', (duration, expectedFrames) => {
+ const result = buildVideoRecallSettings({
+ currentValues,
+ kind: 'all',
+ metadata: metadata(duration),
+ models: [model],
+ });
+ expect(result?.fields).toContain('frames');
+ expect(result?.values).toMatchObject({ numFrames: expectedFrames, fps: 24 });
+ });
+
+ it('prefers an explicit frame count and keeps H3 at its fixed fps', () => {
+ const record = metadata(14, { num_frames: 260, fps: 12 });
+ const result = buildVideoRecallSettings({ currentValues, kind: 'remix', metadata: record, models: [model] });
+ expect(parseVideoRecallRecord(record)?.numFrames).toBe(260);
+ expect(result?.values).toMatchObject({ numFrames: 260, fps: 24 });
+ expect(parseVideoRecallRecord(metadata(11, { fps: 12 }))?.numFrames).toBe(260);
+ });
+
+ it.each([4, 15, 5.5, '11', null, NaN, Infinity])('ignores a malformed or unsupported duration: %s', (duration) => {
+ const record = metadata(duration);
+ const result = buildVideoRecallSettings({ currentValues, kind: 'all', metadata: record, models: [model] });
+ expect(parseVideoRecallRecord(record)?.numFrames).toBeNull();
+ expect(result?.fields).not.toContain('frames');
+ expect(result?.values.numFrames).toBe(175);
+ });
+
+ it.each([undefined, 'wan_t2v', 'sdxl_txt2img', 'minimax_h3_txt2img', 'minimax_h3_unknown'])(
+ 'does not interpret duration as H3 video frames for mode %s',
+ (generation_mode) => {
+ expect(parseVideoRecallRecord(metadata(14, { generation_mode }))?.numFrames).toBeNull();
+ }
+ );
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
index 9d2a4fe236..3369ecf17d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
@@ -27,6 +27,7 @@ import {
isSupportedVideoModel,
isValidVideoNumFrames,
LTX2_NUM_FRAMES_STEP,
+ MINIMAX_H3_FPS,
MINIMAX_H3_HYBRID_BLOCK_RANGE,
snapLtx2FramesDown,
snapVideoNumFrames,
@@ -51,6 +52,7 @@ import {
* aliases for pre-1.0 records and are never written again.
*/
const METADATA_KEY_ALIASES: Readonly<Record<string, readonly string[]>> = {
+ vae: ['wan_vae_model'],
wan_guidance_scale_low_noise: ['guidance_scale_low_noise'],
wan_t5_encoder_model: ['wan_t5_encoder'],
wan_transformer_low_noise: ['transformer_low_noise'],
@@ -357,6 +359,17 @@ export const parseVideoRecallRecord = (metadata: unknown): VideoRecallRecord | n
const sourceVideoName = getVideoName(metadata, 'source_video');
const sourceStartFrame = getInteger(metadata, 'source_video_start_frame');
const sourceEndFrame = getInteger(metadata, 'source_video_end_frame');
+ const oldH3Duration =
+ mode?.startsWith('minimax_h3_') && VIDEO_GENERATION_MODE_IDS.has(mode)
+ ? getIntegerIn(metadata, 'minimax_h3_duration_seconds', 5, 14)
+ : null;
+ // The legacy 24 fps slider's 14-second stop explicitly selected 345 frames, beyond nearest-grid rounding.
+ const legacyH3Frames =
+ oldH3Duration === null
+ ? null
+ : oldH3Duration === 14
+ ? 345
+ : Math.round((oldH3Duration * MINIMAX_H3_FPS - 5) / 17) * 17 + 5;
const recordedReferences = Array.isArray(metadata.minimax_h3_references) ? metadata.minimax_h3_references : null;
return {
@@ -389,7 +402,7 @@ export const parseVideoRecallRecord = (metadata: unknown): VideoRecallRecord | n
modalityScale: getNumberFrom(metadata, 'ltx2_modality_scale', 1),
model: toRecordedModelRef(getRecord(metadata, 'model')),
negativePrompt: getNullableString(metadata, 'negative_prompt'),
- numFrames: getIntegerIn(metadata, 'num_frames', 1),
+ numFrames: getIntegerIn(metadata, 'num_frames', 1) ?? legacyH3Frames,
positivePrompt: getString(metadata, 'positive_prompt'),
referenceList: recordedReferences === null ? 'absent' : recordedReferences.length === 0 ? 'empty' : 'entries',
references: recordedReferences ? getReferences(recordedReferences) : [],
diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.md
index f512b69375..54b60e71d2 100644
--- a/invokeai/frontend/webv2/src/workbench/projects/README.md
+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md
@@ -104,3 +104,15 @@ A build that predates these fields would strip them on load and lose the origina
## Verification
Run `pnpm lint`, `pnpm test`, `pnpm test:browser`, and `pnpm run test:performance:build` from webv2. Queue receipt tests also cover backend admission, account isolation, project deletion, partial acceptance, idempotent retries. Browser tests exercise real IndexedDB transactions and Web Locks.
+
+## Image and queue metadata recall
+
+Canvas generation captures its document after paint persistence, together with its detached generation composites. Image `canvas_v3_metadata` version 1 holds that authored document, portable control-model identities and Canvas settings, without project identity, staging, undo history or stored media URLs. Controls that ran are pinned to the resolved model, kind, weight and schedule; the core metadata's `control_layers`, `controlnets` and `t2iAdapters` describe the executed composites. The queue recall cache keeps the same canvas record beside Generate values under its existing account and byte limits. Manual Save Canvas records the exported document and authored Canvas and common Generate settings, model, prompts, concepts and reference images, labelled `metadata_source: canvas_save`; it records neither an executed seed nor a generation mode. Its destination follows the Gallery settings at click time. After paint persistence and export, metadata is captured synchronously from the originating project only if its document is still the one exported, so settings edits during the save are recorded with the unchanged document. A changed document, a closed project or an expired account prevents upload.
+
+All/Remix share one recall path across Gallery, Preview, staging and local queue snapshots. Current canvas records pass the project canvas loader, then referenced assets are checked in sequential bulk reads of at most 1,000 distinct images (the Gallery API limit) and models resolved by installed identity. Account expiry, a closed/different originating project, a Canvas edit during lookup, or failed paint persistence prevents that canvas commit. A complete recall replaces the canvas and keeps the old document and staging candidates as a History restore point. Partial recall and API append add usable layers with new ids and preserve existing work; staged candidates or running Canvas results also force this merge, so a recall cannot silently discard a generation session. API replacement of `control_layers` replaces only that stack; an explicit empty list clears it, absence changes nothing. Invalid or unavailable nonempty records never mean Clear Canvas. Generate/settings recalls remain independent of unavailable canvas content and report partial results.
+
+Standalone legacy `controlnets` and `t2iAdapters` records restore executed maps only when no modern Canvas or `control_layers` record is present. Name-only image fields are hydrated from Gallery DTOs, preferring recorded processed maps; those reads are deduplicated and reused by Canvas validation. Resolved installed models determine the adapter kind, including Control LoRA, LLLite and Fun models. These generation-wide maps fit the current Canvas frame, including its origin, because they carry no authored world position; modern `control_layers` keep their recorded geometry. Old empty, invalid or unavailable adapter lists preserve existing work. Unsupported per-step weight lists and crop/fill resize modes report partial recall rather than replacing them with scalar weights or stretched maps.
+
+Legacy `ipAdapters` records restore global Generate reference images with their model, image, weight, CLIP Vision encoder, method and step window. Modern `ref_images` take precedence, including explicit empty lists; historical Canvas reference-image arrays and entity containers are also accepted. Name-only images use actual Gallery dimensions, and asset lookup failures leave independent Generate fields recallable. Single-image lists are equivalent to one image; multi-image embeddings and per-step weight lists are unsupported and report partial recall. Reference projection examines at most 10,000 entries and reports truncation; image reads use sequential batches of at most 1,000 distinct names and stop when the account or originating project expires.
+
+Legacy `canvas_v2_metadata` is an image-metadata adapter, separate from project schema migration. Its image-backed layers are projected directly; ordered paint, masks, gradients, erasure and layer adjustments are flattened into intermediate paint bitmaps, retaining local offsets, layer position, opacity, stack order, prompts and adapters. Preparation uploads stay intermediate, including unanswered uploads and results abandoned by account, project or document changes. After synchronous Canvas and Generate commits, only images produced by that preparation and retained in the committed Canvas are promoted to durable Canvas assets. Adoption captures its names once, continues for the originating project across navigation, and stops scheduling requests when its account expires. Rejected layers and failed commits never promote their uploads; borrowed Gallery assets are untouched. Promotion failure preserves the applied recall and reports that pixels remain temporary: recent-upload grace, open-project and undo holds, and saved references protect them under the existing intermediates policy. Decoding and uploads are sequential and account-fenced; each raster conversion is limited to 16,777,216 pixels and 16,384 pixels per side, with 64 megapixels and 128 raster uploads per recall; pressure opacity strokes also preflight a shared limit of 67,108,864 work units per recall: layer surfaces, full-output buffers/copies and stamp sampling retain their pixel charges, with 20 preparation units reserved per raw `(x, y, pressure)` point before smoothing and one per planned stamp. Reservations and attempted preparation remain charged when a layer is refused, so later layers cannot repeat expensive work after the limit is exhausted. An over-budget layer is reported and skipped before raster allocation; usable layers remain available for partial recall. Unsupported legacy vector layers force partial recall; their paths are not silently discarded during a complete replacement. Unsupported layer composite operations are reported and skipped because the current canvas blend contract has no Porter-Duff layer modes. A legacy record with no layers retains legacy's no-op behavior. Current records retain groups, original/derived control sources and transforms through the ordinary canvas contract. Details displays recorded settings, layer/control summaries, components, concepts and references without model or asset lookups; the complete raw JSON remains available.
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.ts
index d33814ddff..286228c9a9 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecallCache.ts
@@ -20,6 +20,7 @@ export const QUEUE_RECALL_CACHE_MAX_BYTES = 32 * 1024 * 1024;
export const QUEUE_RECALL_CACHE_MAX_ENTRIES = 500;
export interface QueueRecallSnapshotInput {
+ canvasMetadata?: Record<string, unknown>;
generateValues?: GenerateWidgetValues;
projectId: string;
queueItemId: string;
@@ -30,6 +31,7 @@ export interface QueueRecallSnapshotInput {
/** Values crossing the persistence boundary stay untrusted until their feature owner normalizes them. */
export interface QueueRecallSnapshot {
+ canvasMetadata?: unknown;
generateValues?: unknown;
projectId: string;
queueItemId: string;
@@ -80,6 +82,7 @@ const isQueueRecallSnapshot = (value: unknown): value is QueueRecallSnapshot =>
isQueueSourceId(value.sourceId) &&
isNonEmptyString(value.submittedAt) &&
(isRecord(value.generateValues) || isRecord(value.videoValues)) &&
+ (value.canvasMetadata === undefined || isRecord(value.canvasMetadata)) &&
(value.generateValues === undefined || isRecord(value.generateValues)) &&
(value.videoValues === undefined || isRecord(value.videoValues))
);
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
index 0a62eeb742..3491a15bba 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunRestoration.ts
@@ -151,7 +151,10 @@ export const normalizeRestoredQueueItem = (value: unknown): WorkbenchQueueItem |
if ((snapshot.sourceId === 'canvas' || snapshot.sourceId === 'generate') && isRecord(rawRecall?.generateValues)) {
const values = normalizeGenerateWidgetValues(rawRecall.generateValues);
if (values) {
- recall = { generateValues: cloneGenerateWidgetValues(values) };
+ recall = {
+ generateValues: cloneGenerateWidgetValues(values),
+ ...(isRecord(rawRecall?.canvasMetadata) ? { canvasMetadata: rawRecall.canvasMetadata } : {}),
+ };
}
} else if (snapshot.sourceId === 'video' && isRecord(rawRecall?.videoValues)) {
const values = normalizeVideoWidgetValues(rawRecall.videoValues);
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts
index 07f5c0fe02..0c68bc2897 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts
@@ -7,11 +7,13 @@ import { parseQueueItemOrigin, parseQueueItemOriginProjectId } from '@features/q
import { normalizeVideoWidgetValues, type VideoWidgetValues } from '@features/video';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { useQuery } from '@tanstack/react-query';
+import { isRecord } from '@workbench/canvasMigration';
import { useWorkbenchSelector } from '@workbench/WorkbenchContext';
import { createAccountOwnedQueueRecallCache } from './queueRecallCache';
export interface LocalRecallSnapshot {
+ canvasMetadata?: Record<string, unknown>;
generateValues?: GenerateWidgetValues;
sourceId: InvocationSourceId;
videoValues?: VideoWidgetValues;
@@ -65,6 +67,7 @@ export const useLocalRecallSnapshot = (origin?: string | null): LocalRecallSnaps
const snapshot = result.snapshot;
return {
sourceId: snapshot.sourceId,
+ ...(isRecord(snapshot.canvasMetadata) ? { canvasMetadata: snapshot.canvasMetadata } : {}),
generateValues: snapshot.generateValues
? (normalizeGenerateWidgetValues(snapshot.generateValues) ?? undefined)
: undefined,
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
index cd23d34760..22c0f9a837 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx
@@ -1,9 +1,11 @@
-import type { GenerateWidgetValues } from '@features/generation/contracts';
+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';
import type * as ModelsModule from '@features/models';
import type { QueueGenerationMeta } from '@features/queue/contracts';
+import type * as CanvasOperationsModule from '@workbench/canvas-operations/api';
import type { ImageRecallKind } from '@workbench/image-actions';
import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+import { galleryDurability, galleryImages } from '@features/gallery';
import {
resetArchitectureCapabilities,
setArchitectureCapabilities,
@@ -12,7 +14,13 @@ import {
architectureCapabilitiesFixture,
seedArchitectureCapabilities,
} from '@features/generation/core/architectureCapabilities.testing';
+import { getDefaultGenerateSettings } from '@features/generation/settings';
import { createDefaultVideoWidgetValues } from '@features/video';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { recordCanvasMetadata } from '@workbench/canvas-operations/saveCanvasToGallery';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
import { act, createRef, type Ref, useImperativeHandle } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -27,22 +35,35 @@ const mocks = vi.hoisted(() => ({
openWidget: vi.fn(),
patchValues: vi.fn(),
setSettings: vi.fn(),
+ prepareLegacy: vi.fn(),
+ models: [] as ModelsModule.ModelConfig[],
+ store: null as ReturnType<typeof createWorkbenchStore> | null,
snapshot: undefined as LocalRecallSnapshot | null | undefined,
}));
+vi.mock('@workbench/canvas-operations/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof CanvasOperationsModule>()),
+ prepareLegacyCanvasMetadata: mocks.prepareLegacy,
+}));
vi.mock('./useLocalRecallSnapshot', () => ({ useLocalRecallSnapshot: () => mocks.snapshot }));
vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
...(await importOriginal<typeof WorkbenchContextModule>()),
- useWidgetValuesSelector: () => ({}),
- useWorkbenchCommands: () => ({
- generation: { setSettings: mocks.setSettings },
- widgets: { patchValues: mocks.patchValues },
- }),
+ useWorkbenchQueries: () =>
+ mocks.store?.queries ?? {
+ getSnapshot: () => ({ activeProject: { id: 'active-project' }, scopedDefaults: {} }),
+ getProject: () => ({ id: 'active-project', widgetInstances: {} }),
+ isActiveProject: () => true,
+ },
+ useWorkbenchCommands: () =>
+ mocks.store?.commands ?? {
+ generation: { setSettings: mocks.setSettings },
+ widgets: { patchValues: mocks.patchValues },
+ },
}));
vi.mock('@features/models', async (importOriginal) => ({
...(await importOriginal<typeof ModelsModule>()),
ensureModelsLoaded: () => Promise.resolve(),
- useModelsSelector: () => [],
+ useModelsSelector: () => mocks.models,
}));
vi.mock('@workbench/useNotify', () => ({
useNotify: () => ({ error: vi.fn(), info: mocks.notifyInfo, success: mocks.notifySuccess }),
@@ -62,6 +83,24 @@ const generateSnapshot = {
seedMode: 'fixed',
} as GenerateWidgetValues;
+const makeCanvasMetadata = () => {
+ const document = createEmptyCanvasDocument();
+ document.stacks.raster = [
+ {
+ id: 'recorded-image',
+ name: 'Recorded image',
+ type: 'raster',
+ isEnabled: true,
+ isLocked: false,
+ opacity: 1,
+ blendMode: 'normal',
+ transform: { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 },
+ source: { type: 'image', image: { imageName: 'recorded.png', width: 640, height: 480 } },
+ },
+ ];
+ return { canvas_v3_metadata: recordCanvasMetadata(document, { models: [] }) };
+};
+
type Handle = ReturnType<typeof useQueueItemRecall>;
const handle = createRef<Handle>();
const Probe = ({ meta, ref }: { meta: QueueGenerationMeta; ref: Ref<Handle> }) => {
@@ -83,12 +122,17 @@ const render = async (snapshot: LocalRecallSnapshot | null | undefined, meta: Qu
};
const recall = (kind: ImageRecallKind) => act(() => handle.current!.recall(kind));
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.store = null;
+ mocks.models = [];
+});
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
+ vi.restoreAllMocks();
});
describe('useQueueItemRecall', () => {
@@ -106,7 +150,7 @@ describe('useQueueItemRecall', () => {
await recall('all');
- expect(mocks.setSettings).toHaveBeenCalledWith(generateSnapshot);
+ expect(mocks.setSettings).toHaveBeenCalledWith(generateSnapshot, 'active-project');
expect(mocks.openWidget).toHaveBeenCalledWith('generate', { preferredRegions: ['left'] });
expect(mocks.notifySuccess).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.settingsRecalledDescription');
});
@@ -147,3 +191,302 @@ describe('useQueueItemRecall', () => {
expect(mocks.notifyInfo).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.recallUnavailableCapabilities');
});
});
+
+it('recalls a canvas queue snapshot through the real document owner and keeps its authored controls', async () => {
+ accountLifecycle.activate('queue-canvas-recall');
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &
+ ModelsModule.ModelConfig;
+ const controlModel = {
+ base: 'sdxl',
+ key: 'queue-control',
+ name: 'Edges',
+ type: 'controlnet',
+ } as ModelsModule.ModelConfig;
+ mocks.models = [main, controlModel];
+ mocks.store = createWorkbenchStore();
+ const document = createEmptyCanvasDocument();
+ document.stacks.control = [
+ {
+ id: 'submitted-control',
+ name: 'Recorded edges',
+ type: 'control',
+ isEnabled: true,
+ isLocked: false,
+ opacity: 1,
+ blendMode: 'normal',
+ transform: { x: -20, y: 40, rotation: 0, scaleX: 1, scaleY: 1 },
+ source: { type: 'image', image: { imageName: 'edges.png', width: 640, height: 480 } },
+ withTransparencyEffect: false,
+ adapter: {
+ kind: 'controlnet',
+ model: controlModel.key,
+ weight: 0.65,
+ beginEndStepPct: [0.1, 0.9],
+ controlMode: 'balanced',
+ },
+ },
+ ];
+ vi.spyOn(galleryImages, 'resolveMany').mockResolvedValue([{ imageName: 'edges.png' }] as Awaited<
+ ReturnType<typeof galleryImages.resolveMany>
+ >);
+ await render({
+ sourceId: 'canvas',
+ generateValues: { ...getDefaultGenerateSettings(main), model: main, modelKey: main.key },
+ canvasMetadata: {
+ canvas_v3_metadata: recordCanvasMetadata(document, { models: [controlModel], settings: { strength: 0.4 } }),
+ },
+ });
+ await recall('all');
+ expect(mocks.store.queries.getSnapshot().activeProject.canvas.document.stacks.control[0]).toMatchObject({
+ name: 'Recorded edges',
+ transform: { x: -20, y: 40 },
+ adapter: { model: 'queue-control', weight: 0.65 },
+ });
+ expect(mocks.store.queries.getSnapshot().activeProject.canvas.snapshots).toHaveLength(1);
+});
+
+it('retains prompt tool edits made while canvas assets load and recalls the snapshot model', async () => {
+ accountLifecycle.activate('queue-canvas-concurrent-recall');
+ const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &
+ ModelsModule.ModelConfig;
+ const other = { base: 'sd-1', key: 'other-main', name: 'Other', type: 'main' } as MainModelConfig &
+ ModelsModule.ModelConfig;
+ mocks.models = [main, other];
+ const store = (mocks.store = createWorkbenchStore());
+ const projectId = store.queries.getSnapshot().activeProject.id;
+ store.commands.generation.setSettings(
+ { ...getDefaultGenerateSettings(main), model: main, modelKey: main.key },
+ projectId
+ );
+ let resolveAssets!: (images: Awaited<ReturnType<typeof galleryImages.resolveMany>>) => void;
+ const assets = new Promise<Awaited<ReturnType<typeof galleryImages.resolveMany>>>((resolve) => {
+ resolveAssets = resolve;
+ });
+ const resolveMany = vi.spyOn(galleryImages, 'resolveMany').mockReturnValue(assets);
+ await render({
+ sourceId: 'canvas',
+ generateValues: {
+ ...getDefaultGenerateSettings(main),
+ model: main,
+ modelKey: main.key,
+ positivePrompt: 'Recalled',
+ },
+ canvasMetadata: makeCanvasMetadata(),
+ });
+ let pending!: Promise<void>;
+ await act(() => {
+ pending = Promise.resolve(handle.current!.recall('remix'));
+ });
+ await vi.waitFor(() => expect(resolveMany).toHaveBeenCalled());
+ store.commands.generation.patchSettings(
+ {
+ expandPromptModelKey: 'new-prompt-tool',
+ imageToPromptModelKey: 'new-vision-tool',
+ model: other,
+ modelKey: other.key,
+ },
+ projectId
+ );
+ await act(async () => {
+ resolveAssets([{ imageName: 'recorded.png' }] as Awaited<ReturnType<typeof galleryImages.resolveMany>>);
+ await pending;
+ });
+ const snapshot = store.queries.getSnapshot();
+ expect(getResolvedProjectWidgetValues(snapshot.activeProject, 'generate', snapshot.scopedDefaults)).toMatchObject({
+ expandPromptModelKey: 'new-prompt-tool',
+ imageToPromptModelKey: 'new-vision-tool',
+ modelKey: main.key,
+ positivePrompt: 'Recalled',
+ seedMode: 'random',
+ });
+ expect(snapshot.activeProject.canvas.document.stacks.raster[0]).toMatchObject({ name: 'Recorded image' });
+});
+
+it('recalls Generate settings and reports a partial result when canvas assets cannot load', async () => {
+ accountLifecycle.activate('queue-canvas-failed-recall');
+ const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &
+ ModelsModule.ModelConfig;
+ mocks.models = [main];
+ const store = (mocks.store = createWorkbenchStore());
+ const original = store.queries.getSnapshot().activeProject.canvas.document;
+ vi.spyOn(galleryImages, 'resolveMany').mockRejectedValue(new Error('Asset lookup unavailable'));
+ await render({
+ sourceId: 'canvas',
+ generateValues: {
+ ...getDefaultGenerateSettings(main),
+ model: main,
+ modelKey: main.key,
+ positivePrompt: 'Recalled',
+ },
+ canvasMetadata: makeCanvasMetadata(),
+ });
+ await recall('all');
+ const snapshot = store.queries.getSnapshot();
+ expect(
+ getResolvedProjectWidgetValues(snapshot.activeProject, 'generate', snapshot.scopedDefaults).positivePrompt
+ ).toBe('Recalled');
+ expect(snapshot.activeProject.canvas.document).toBe(original);
+ expect(mocks.notifyInfo).toHaveBeenCalledWith(expect.any(String), 'widgets.gallery.itemActions.recall.canvasPartial');
+ expect(mocks.notifySuccess).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.settingsRecalledDescription');
+});
+
+it.each(['account', 'project', 'canvas'] as const)(
+ 'fences a canvas queue recall after its %s changes during asset lookup',
+ async (change) => {
+ accountLifecycle.activate('queue-canvas-fenced-recall');
+ const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &
+ ModelsModule.ModelConfig;
+ mocks.models = [main];
+ const store = (mocks.store = createWorkbenchStore());
+ const projectId = store.queries.getSnapshot().activeProject.id;
+ let resolveAssets!: (images: Awaited<ReturnType<typeof galleryImages.resolveMany>>) => void;
+ const assets = new Promise<Awaited<ReturnType<typeof galleryImages.resolveMany>>>((resolve) => {
+ resolveAssets = resolve;
+ });
+ const resolveMany = vi.spyOn(galleryImages, 'resolveMany').mockReturnValue(assets);
+ await render({
+ sourceId: 'canvas',
+ generateValues: {
+ ...getDefaultGenerateSettings(main),
+ model: main,
+ modelKey: main.key,
+ positivePrompt: 'Recalled',
+ },
+ canvasMetadata: makeCanvasMetadata(),
+ });
+ let pending!: Promise<void>;
+ await act(() => {
+ pending = Promise.resolve(handle.current!.recall('all'));
+ });
+ await vi.waitFor(() => expect(resolveMany).toHaveBeenCalled());
+ if (change === 'account') {
+ accountLifecycle.activate('next-account');
+ } else if (change === 'project') {
+ store.commands.projects.create();
+ } else {
+ store.commands.canvas.apply(projectId, {
+ type: 'setCanvasBbox',
+ bbox: { x: 100, y: 200, width: 512, height: 512 },
+ });
+ }
+ const original = store.queries.getProject(projectId)!;
+ await act(async () => {
+ resolveAssets([{ imageName: 'recorded.png' }] as Awaited<ReturnType<typeof galleryImages.resolveMany>>);
+ await pending;
+ });
+ const project = store.queries.getProject(projectId)!;
+ expect(project.canvas.document).toBe(original.canvas.document);
+ expect(project.canvas.snapshots).toHaveLength(0);
+ if (change === 'canvas') {
+ expect(
+ getResolvedProjectWidgetValues(project, 'generate', store.queries.getSnapshot().scopedDefaults).positivePrompt
+ ).toBe('Recalled');
+ expect(mocks.notifyInfo).toHaveBeenCalledWith(
+ expect.any(String),
+ 'widgets.gallery.itemActions.recall.canvasPartial'
+ );
+ } else {
+ expect(project).toBe(original);
+ expect(mocks.notifyInfo).not.toHaveBeenCalled();
+ expect(mocks.notifySuccess).not.toHaveBeenCalled();
+ expect(mocks.openWidget).not.toHaveBeenCalled();
+ }
+ }
+);
+
+it.each(['project', 'account', 'promotion-failure', 'project-promotion-failure'] as const)(
+ 'finishes Queue recall writes and navigation before adoption when %s changes during promotion',
+ async (change) => {
+ accountLifecycle.activate('queue-paint-adoption');
+ const main = { base: 'sdxl', key: 'main', name: 'SDXL', type: 'main' } as MainModelConfig;
+ mocks.models = [main as ModelsModule.ModelConfig];
+ mocks.store = createWorkbenchStore();
+ const projectId = mocks.store.queries.getSnapshot().activeProject.id;
+ const document = createEmptyCanvasDocument();
+ document.stacks.raster = ['created-a.png', 'created-b.png'].map((imageName, index) => ({
+ id: `paint-${index}`,
+ name: 'Paint',
+ type: 'raster',
+ isEnabled: true,
+ isLocked: false,
+ opacity: 1,
+ blendMode: 'normal',
+ transform: { x: 0, y: 0, scaleX: 1, scaleY: 1, rotation: 0 },
+ source: { type: 'paint', bitmap: { imageName, width: 64, height: 64 } },
+ }));
+ mocks.prepareLegacy.mockResolvedValue({
+ record: { version: 1, document },
+ problems: [],
+ createdImageNames: ['created-a.png', 'created-b.png'],
+ });
+ vi.spyOn(galleryImages, 'resolveMany').mockResolvedValue(
+ ['created-a.png', 'created-b.png'].map((imageName) => ({ imageName })) as Awaited<
+ ReturnType<typeof galleryImages.resolveMany>
+ >
+ );
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ const promote = vi
+ .spyOn(galleryDurability, 'makeCanvasAsset')
+ .mockResolvedValue(undefined)
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ })
+ );
+ await render({
+ sourceId: 'canvas',
+ generateValues: {
+ ...getDefaultGenerateSettings(main),
+ positivePrompt: 'Queue recall',
+ model: main,
+ modelKey: main.key,
+ },
+ canvasMetadata: { canvas_v2_metadata: {} },
+ });
+ await act(async () => {
+ const pending = handle.current!.recall('all');
+ await vi.waitFor(() => expect(promote).toHaveBeenCalledExactlyOnceWith('created-a.png'));
+ expect(getResolvedProjectWidgetValues(mocks.store!.queries.getProject(projectId)!, 'generate', {})).toMatchObject(
+ { positivePrompt: 'Queue recall' }
+ );
+ expect(mocks.openWidget).toHaveBeenCalledOnce();
+ expect(mocks.notifySuccess).toHaveBeenCalledOnce();
+ mocks.store!.commands.generation.setSettings(
+ { ...getDefaultGenerateSettings(main), model: main, steps: 47 },
+ projectId
+ );
+ const infosBefore = mocks.notifyInfo.mock.calls.length;
+ if (change === 'project' || change === 'project-promotion-failure') {
+ mocks.store!.commands.projects.create();
+ } else if (change === 'account') {
+ accountLifecycle.activate('other-account');
+ }
+ if (change === 'promotion-failure' || change === 'project-promotion-failure') {
+ reject(new Error('Promotion unavailable'));
+ } else {
+ resolve();
+ }
+ await pending;
+ await vi.waitFor(() => expect(promote).toHaveBeenCalledTimes(change === 'account' ? 1 : 2));
+ expect(mocks.openWidget).toHaveBeenCalledOnce();
+ expect(mocks.notifySuccess).toHaveBeenCalledOnce();
+ expect(getResolvedProjectWidgetValues(mocks.store!.queries.getProject(projectId)!, 'generate', {})).toMatchObject(
+ { steps: 47 }
+ );
+ if (change === 'promotion-failure') {
+ await vi.waitFor(() =>
+ expect(mocks.notifyInfo).toHaveBeenCalledWith(
+ expect.any(String),
+ 'widgets.gallery.itemActions.recall.canvasImagesTemporary'
+ )
+ );
+ } else {
+ expect(mocks.notifyInfo.mock.calls).toHaveLength(infosBefore);
+ }
+ });
+ }
+);
diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts
index e53b8fd1b9..5ef6d841c9 100644
--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts
@@ -1,10 +1,11 @@
import type { QueueGenerationMeta } from '@features/queue/contracts';
import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';
+import type * as CanvasRecallModule from '@workbench/image-actions/canvasRecall';
-import { createGenerateFormValuesSelector } from '@features/generation/react';
import { hasArchitectureCapabilities, isSupportedGenerateModel } from '@features/generation/settings';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import {
EMPTY_IMAGE_RECALL_CAPABILITIES,
getCurrentGenerateValues,
@@ -12,15 +13,14 @@ import {
} from '@workbench/image-actions';
import { useNotify } from '@workbench/useNotify';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
-import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';
+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { getQueueRecallCapabilities, getVideoQueueRecallCapabilities, planQueueRecall } from './queueRecall';
import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';
-const selectGenerateRecallValues = createGenerateFormValuesSelector();
-
/**
* Recall local submission snapshots or foreign session prompts/seed into the active project, then reveal the
* destination panel.
@@ -30,7 +30,9 @@ export const useQueueItemRecall = (
meta: QueueGenerationMeta
): { capabilities: ImageRecallCapabilities; isPending: boolean; recall: (kind: ImageRecallKind) => void } => {
const { t } = useTranslation();
- const { generation, widgets } = useWorkbenchCommands();
+ const commands = useWorkbenchCommands();
+ const { generation, widgets } = commands;
+ const queries = useWorkbenchQueries();
const openWidget = useOpenWorkbenchWidget();
const notify = useNotify();
const snapshot = useLocalRecallSnapshot(origin);
@@ -38,7 +40,6 @@ export const useQueueItemRecall = (
const localGenerateValues = snapshot?.generateValues ?? null;
const videoSnapshot = snapshot?.videoValues ?? null;
const isVideoItem = snapshot?.sourceId === 'video';
- const generateValues = useWidgetValuesSelector('generate', selectGenerateRecallValues);
const models = useModelsSelector((state) => state.models);
const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);
const capabilities = useMemo(
@@ -56,12 +57,23 @@ export const useQueueItemRecall = (
});
const recall = useCallback(
- (kind: ImageRecallKind) => {
+ async (kind: ImageRecallKind) => {
+ const owner = captureAccountScope();
+ const originalProject = queries.getSnapshot().activeProject;
if (isPending) {
return;
}
- const current = getCurrentGenerateValues({ generateValues, supportedModels });
- const plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });
+ const readCurrentValues = () => {
+ const project = queries.getProject(originalProject.id);
+ return project
+ ? getCurrentGenerateValues({
+ generateValues: getResolvedProjectWidgetValues(project, 'generate', queries.getSnapshot().scopedDefaults),
+ supportedModels,
+ })
+ : null;
+ };
+ const current = readCurrentValues();
+ let plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });
if (!plan) {
// Use a generic unavailable reason: Video and missing capabilities are not missing Generate models.
@@ -81,12 +93,104 @@ export const useQueueItemRecall = (
return;
}
- generation.setSettings(plan.values);
+ let canvasRecall: typeof CanvasRecallModule | null = null;
+ let canvasPlan: CanvasRecallModule.CanvasRecallPlan | null = null;
+ let canvasProblem: string | null = null;
+ let canvasApplied = false;
+ const preparedModelKey = plan.values.model?.key;
+ if ((kind === 'all' || kind === 'remix') && snapshot?.canvasMetadata) {
+ try {
+ canvasRecall = await import('@workbench/image-actions/canvasRecall');
+ canvasPlan = await canvasRecall.prepareCanvasRecall({
+ metadata: snapshot.canvasMetadata,
+ model: plan.values.model,
+ models,
+ owner,
+ isCurrent: () =>
+ queries.isActiveProject(originalProject.id) &&
+ queries.getProject(originalProject.id)?.canvas.document === originalProject.canvas.document,
+ });
+ await canvasRecall.settleCanvasRecall(
+ canvasPlan,
+ {
+ commands,
+ projectId: originalProject.id,
+ getProject: () => queries.getProject(originalProject.id) ?? null,
+ },
+ owner
+ );
+ } catch (error) {
+ canvasPlan = null;
+ canvasProblem = error instanceof Error ? error.message : 'unavailable';
+ }
+ }
+ if (!isAccountScopeCurrent(owner) || !queries.isActiveProject(originalProject.id)) {
+ return;
+ }
+ // Asset reads and paint persistence may yield; retain edits made while the canvas was loading.
+ plan = planQueueRecall(kind, {
+ current: readCurrentValues(),
+ isVideoItem,
+ meta,
+ snapshot: localGenerateValues,
+ videoSnapshot,
+ });
+ if (!plan || plan.target !== 'generate') {
+ return;
+ }
+ if (canvasPlan && canvasRecall) {
+ try {
+ if (preparedModelKey !== plan.values.model?.key) {
+ canvasPlan.problems.push('model-changed');
+ } else {
+ canvasApplied = canvasRecall.commitCanvasRecall({
+ plan: canvasPlan,
+ expectedDocument: originalProject.canvas.document,
+ target: {
+ commands,
+ projectId: originalProject.id,
+ getProject: () =>
+ queries.isActiveProject(originalProject.id) ? (queries.getProject(originalProject.id) ?? null) : null,
+ },
+ restorePointName: t('widgets.gallery.itemActions.recall.beforeCanvasRecall'),
+ });
+ }
+ if (canvasPlan.problems.length) {
+ canvasProblem = canvasRecall.getCanvasRecallProblemsMessage(canvasPlan.problems, t);
+ }
+ } catch (error) {
+ canvasProblem = error instanceof Error ? error.message : 'unavailable';
+ }
+ }
+ if (canvasProblem) {
+ notify.info(
+ getImageRecallTitle(kind, t),
+ t('widgets.gallery.itemActions.recall.canvasPartial', { items: canvasProblem })
+ );
+ }
+ generation.setSettings(plan.values, originalProject.id);
openWidget('generate', { preferredRegions: ['left'] });
notify.success(getImageRecallTitle(kind, t), t('widgets.queue.settingsRecalledDescription'));
+ if (canvasApplied && canvasPlan && canvasRecall) {
+ const durable = await canvasRecall.finalizeCanvasRecallAssets(
+ canvasPlan,
+ {
+ commands,
+ projectId: originalProject.id,
+ getProject: () => queries.getProject(originalProject.id) ?? null,
+ },
+ owner
+ );
+ if (!durable && isAccountScopeCurrent(owner) && queries.isActiveProject(originalProject.id)) {
+ notify.info(getImageRecallTitle(kind, t), t('widgets.gallery.itemActions.recall.canvasImagesTemporary'));
+ }
+ }
},
[
- generateValues,
+ commands,
+ queries,
+ snapshot,
+ models,
generation,
isPending,
isVideoItem,
diff --git a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
index 826ef3ea2b..178700c385 100644
--- a/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueHistoryContracts.ts
@@ -10,6 +10,7 @@ export interface QueueCanvasSessionRef {
}
export interface WorkbenchQueueRecallValues {
+ canvasMetadata?: Record<string, unknown>;
generateValues?: GenerateWidgetValues;
videoValues?: VideoWidgetValues;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
index b1eee77510..992fd22e81 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts
@@ -1095,6 +1095,17 @@ describe('runCanvasInvocation', () => {
expect(
remembered.submittedGraphs()[0]?.graph.backendGraph?.nodes['control_net_depth-layer']?.control_model
).toMatchObject({ key: 'depth-b' });
+ const outputMetadata = Object.values(remembered.submittedGraphs()[0]!.graph.backendGraph!.nodes).find(
+ (node) => node.type === 'core_metadata'
+ );
+ expect(outputMetadata?.canvas_v3_metadata).toMatchObject({
+ controlModels: { 'depth-layer': { key: 'depth-b', name: 'depth b', hash: 'depth-b-hash' } },
+ document: { stacks: { control: [{ id: 'depth-layer', adapter: { model: 'depth-b', kind: 'controlnet' } }] } },
+ settings: { strength: 0.75 },
+ });
+ expect(outputMetadata?.control_layers).toMatchObject([
+ { layer_id: 'depth-layer', model: { key: 'depth-b' }, type: 'controlnet' },
+ ]);
});
it('gives a FLUX union model the InstantX mode of the layer type', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 887a71c4c7..c923bc0f2a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -44,7 +44,7 @@ import {
registerAccountOwnedResource,
type AccountScope,
} from '@platform/state/accountLifecycle';
-import { getCanvasEngine, getCanvasOperations } from '@workbench/canvas-operations/api';
+import { getCanvasEngine, getCanvasOperations, recordCanvasMetadata } from '@workbench/canvas-operations/api';
import { createControlLayerCheckContext, createControlLayerSequence } from '@workbench/controlLayerChecks';
import { getWorkbenchPreferences } from '@workbench/settings/store';
import {
@@ -384,11 +384,17 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promis
// The other half of the mode-union drift guard (see `detectMode` above).
const mode: CanvasCompileMode = composites.mode;
+ const controlLayers = controls.toGraphInputs(composites.controlImages);
const compiled = compileCanvasGraph({
+ canvasMetadata: recordCanvasMetadata(composites.canvas.document, {
+ controls: controlLayers,
+ models: deps.models,
+ settings: { strength: deps.strength, compositing: deps.compositing, scaling: deps.scaling },
+ }),
bbox: composites.bbox,
compositeImageName: composites.baseImageName,
compositing: deps.compositing,
- controlLayers: controls.toGraphInputs(composites.controlImages),
+ controlLayers,
destination: deps.destination,
maskImageName: composites.maskImageName,
mode,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
index b7f3203abc..f3da3570bb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts
@@ -60,7 +60,13 @@ export const useCanvasGallerySave = (
savingProjects.set(project.id, true);
try {
- const result = await saveCanvasToGallery({ engine: matchedEngine, project, region, scopedDefaults });
+ const result = await saveCanvasToGallery({
+ engine: matchedEngine,
+ getProject: queries.getProject,
+ project,
+ region,
+ scopedDefaults,
+ });
assertAccountScopeCurrent(owner);
if (result.status === 'saved') {
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 994ecc9253..bf0d2d3764 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
@@ -6,6 +6,7 @@ import type * as GalleryQueriesModule from '@features/gallery/queries';
import type * as IdentityModule from '@features/identity';
import type * as ClipboardModule from '@platform/browser/clipboard';
import type { ImageActions, ImageRecallCapabilities } from '@workbench/image-actions';
+import type { ReadCallback } from 'i18next';
import { ChakraProvider } from '@chakra-ui/react';
import { galleryKeys } from '@features/gallery/queries';
@@ -140,6 +141,7 @@ void i18n.use(initReactI18next).init({
lng: 'en',
resources: {
en: {
+ metadata: { widgets: { preview: { metadataLabels: { generation_mode: 'Generation path' } } } },
translation: {
common: { countOfTotal: '{{count}} of {{total}}', copy: 'Copy', retry: 'Retry' },
widgets: {
@@ -214,14 +216,16 @@ const POSITION = { boardItemCount: 2, isLoadingBoard: false, selectedIndex: 0 };
const renderDetails = async ({
isOpen,
item,
+ localization = i18n,
}: {
isOpen: boolean;
item: GalleryImageItem | GalleryVideoItem;
+ localization?: typeof i18n;
}): Promise<void> => {
await interact(() => {
root?.render(
<QueryClientProvider client={queryClient}>
- <I18nextProvider i18n={i18n}>
+ <I18nextProvider i18n={localization}>
<ChakraProvider value={system}>
<PreviewDetailsPanel
actions={actions}
@@ -286,6 +290,165 @@ describe('Preview query-driven Details', () => {
],
};
+ it.each([
+ {
+ label: 'Executed controls',
+ expected: 'Depth model',
+ metadata: { control_layers: [{ model: { name: 'Depth model' }, type: 'controlnet', weight: 0.75 }] },
+ },
+ {
+ label: 'IP-Adapters',
+ expected: 'Portrait model',
+ metadata: {
+ ipAdapters: [
+ {
+ ip_adapter_model: { name: 'Portrait model' },
+ image: { image_name: 'portrait.png' },
+ clip_vision_model: 'ViT-G',
+ method: 'style_precise',
+ weight: 0.75,
+ begin_step_percent: 0.2,
+ end_step_percent: 0.9,
+ },
+ ],
+ },
+ },
+ ...(['array', 'entities'] as const).map((shape) => {
+ const reference = {
+ id: 'global-style',
+ type: 'reference_image',
+ name: 'Global style',
+ ipAdapter: {
+ type: 'ip_adapter',
+ model: { name: 'Historical portrait' },
+ image: { image_name: 'portrait.png', width: 320, height: 200 },
+ clipVisionModel: 'ViT-G',
+ method: 'style_precise',
+ weight: 0.75,
+ beginEndStepPct: [0.2, 0.9],
+ },
+ };
+ return {
+ label: 'Reference images',
+ expected: 'Historical portrait',
+ metadata: {
+ canvas_v2_metadata: {
+ rasterLayers: [],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ referenceImages: shape === 'array' ? [reference] : { entities: [reference] },
+ },
+ },
+ };
+ }),
+ ])(
+ 'shows readable $label metadata from the emitted English namespace beside root actions',
+ async ({ label, expected, metadata }) => {
+ const localization = createInstance().use(initReactI18next);
+ await localization.init({
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: await fetch('/locales/en.json').then((response) => response.json()),
+ metadata: await fetch('/locales/en.metadata.json').then((response) => response.json()),
+ },
+ },
+ });
+ galleryMocks.imageMetadata.mockResolvedValueOnce(metadata);
+ await renderDetails({ isOpen: true, item: imageItem, localization });
+ await act(async () => {
+ await vi.waitFor(() => expect(document.body.textContent).toContain(expected));
+ });
+ const controlRow = [...document.querySelectorAll('.chakra-data-list__item')].find((row) =>
+ row.textContent?.includes(expected)
+ );
+ expect(controlRow?.querySelector('dt')?.textContent).toBe(label);
+ if (label !== 'Executed controls') {
+ expect(controlRow?.textContent).toContain('portrait.png · ViT-G · style_precise · Weight 0.75 · Steps 0.2–0.9');
+ }
+ expect(controlRow?.textContent).toContain('Weight 0.75');
+ expect(controlRow?.querySelector('button[aria-label="Copy"]')).not.toBeNull();
+ if (label === 'Reference images') {
+ expect(document.body.textContent).toContain('0 layers');
+ expect(document.body.textContent).not.toContain('Global style');
+ }
+ }
+ );
+
+ it.each([imageItem, videoItem])(
+ 'loads $kind metadata labels on opening, preserving rows and raw tabs while pending',
+ async (item) => {
+ let complete!: ReadCallback;
+ const read = vi.fn((_language: string, _namespace: string, callback: ReadCallback) => {
+ complete = callback;
+ });
+ const localization = createInstance()
+ .use(initReactI18next)
+ .use({ type: 'backend' as const, init: () => undefined, read });
+ await localization.init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ partialBundledLanguages: true,
+ resources: { en: { translation: i18n.getResourceBundle('en', 'translation') } },
+ });
+ const metadata = { positive_prompt: 'available prompt', generation_mode: 'recorded mode' };
+ galleryMocks.imageMetadata.mockResolvedValueOnce(metadata);
+ galleryMocks.videoMetadata.mockResolvedValueOnce(metadata);
+
+ await renderDetails({ isOpen: false, item, localization });
+ expect(read).not.toHaveBeenCalled();
+ await renderDetails({ isOpen: true, item, localization });
+ await act(async () => {
+ await vi.waitFor(() => expect(document.body.textContent).toContain('available prompt'));
+ });
+ expect(read).toHaveBeenCalledWith('en', 'metadata', expect.any(Function));
+ expect(document.body.textContent).not.toContain('widgets.preview.metadataLabels.');
+ await interact(() => getButton('Metadata').click());
+ expect(document.body.textContent).toContain('"generation_mode": "recorded mode"');
+ await interact(() =>
+ complete(null, { widgets: { preview: { metadataLabels: { generation_mode: 'Recorded workflow' } } } })
+ );
+ await interact(() => getButton('Details').click());
+ expect(document.body.textContent).toContain('Recorded workflow');
+ expect(document.body.textContent).toContain('recorded mode');
+ }
+ );
+
+ it.each([imageItem, videoItem])(
+ 'keeps $kind basic rows and raw metadata usable when the label namespace fails',
+ async (item) => {
+ let fail!: ReadCallback;
+ const localization = createInstance()
+ .use(initReactI18next)
+ .use({
+ type: 'backend' as const,
+ init: () => undefined,
+ read: (_language: string, _namespace: string, callback: ReadCallback) => {
+ fail = callback;
+ },
+ });
+ await localization.init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ partialBundledLanguages: true,
+ resources: { en: { translation: i18n.getResourceBundle('en', 'translation') } },
+ });
+ const metadata = { positive_prompt: 'available prompt', generation_mode: 'recorded mode' };
+ galleryMocks.imageMetadata.mockResolvedValueOnce(metadata);
+ galleryMocks.videoMetadata.mockResolvedValueOnce(metadata);
+ await renderDetails({ isOpen: true, item, localization });
+ await interact(() => fail(new Error('labels unavailable'), false));
+ expect(document.body.textContent).toContain('available prompt');
+ expect(document.body.textContent).not.toContain('widgets.preview.metadataLabels.');
+ await interact(() => getButton('Metadata').click());
+ expect(document.body.textContent).toContain('"generation_mode": "recorded mode"');
+ }
+ );
+
it("shows this image's resolved Noise and math inputs in the Graph tab", async () => {
galleryMocks.imageWorkflow.mockResolvedValueOnce({
graph: JSON.stringify(sourceGraph),
@@ -481,7 +644,7 @@ describe('Preview query-driven Details', () => {
});
it('renders raw Metadata, Workflow, and Graph JSON tabs without image recall controls', async () => {
- galleryMocks.videoMetadata.mockResolvedValueOnce({ codec: 'h264', duration: 15 });
+ galleryMocks.videoMetadata.mockResolvedValueOnce({ codec: 'h264' });
galleryMocks.videoWorkflow.mockResolvedValueOnce({
graph: '{"nodes":[{"id":"video"}]}',
workflow: '{"name":"Video workflow"}',
@@ -536,9 +699,17 @@ describe('Preview query-driven Details', () => {
row,
])
);
- expect(Object.keys(rows)).toEqual(['Prompt text', 'Checkpoint', 'Seed value', 'Frame count', 'Frame rate']);
+ expect(Object.keys(rows)).toEqual([
+ 'Prompt text',
+ 'Checkpoint',
+ 'Seed value',
+ 'Frame count',
+ 'Frame rate',
+ 'Generation path',
+ ]);
expect(rows['Checkpoint']?.textContent).toContain('Wan 2.2 T2V');
expect(rows['Frame count']?.textContent).toContain('81');
+ expect(rows['Generation path']?.textContent).toContain('wan_t2v');
// Copy is each row's only action; video recall lives in its menu.
expect(document.querySelector('[aria-label="Use prompt"]')).toBeNull();
expect(rows['Frame rate']?.querySelectorAll('button')).toHaveLength(1);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
index 4eaa1b91a3..1779132fb9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx
@@ -32,6 +32,7 @@ import { parsePreviewMetadata, type PreviewMetadataEntry } from './previewMetada
*/
const GROUP_HOVER_VISIBLE = { opacity: 1 };
+const METADATA_NAMESPACES = ['metadata', 'translation'] as const;
const TAB_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'End', 'Home']);
@@ -124,7 +125,7 @@ const VideoDetailsQuery = ({
itemKey: GalleryItemKey;
videoName: string;
}) => {
- const { t } = useTranslation();
+ const { t } = useTranslation(METADATA_NAMESPACES, { nsMode: 'fallback', useSuspense: false });
const metadataQuery = useQuery(galleryVideoMetadataOptions(captureAccountScope(), videoName));
const workflowQuery = useQuery({
queryFn: ({ signal }) => galleryVideos.workflow(videoName, signal),
@@ -249,7 +250,7 @@ const ImageDetails = ({
isLoading: boolean;
metadata: GalleryImageMetadata | null;
}) => {
- const { t } = useTranslation();
+ const { t } = useTranslation(METADATA_NAMESPACES, { nsMode: 'fallback', useSuspense: false });
const entries = [
...parsePreviewMetadata(metadata, { kind: 'image', t }),
...(image
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts
index 071444f12f..aa742b4117 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts
@@ -9,7 +9,7 @@ const englishCatalog = Object.values(
import.meta.glob('../../../../public/locales/en.json', { eager: true, import: 'default' })
)[0] as Record<string, unknown>;
const instance = i18n.createInstance();
-const t = ((key: string) => instance.t(key)) as TFunction;
+const t = instance.t.bind(instance) as TFunction;
beforeAll(async () => {
await instance.init({
@@ -141,4 +141,136 @@ describe('parsePreviewMetadata', () => {
expect(parsePreviewMetadata(null, image)).toEqual([]);
expect(parsePreviewMetadata(null, video)).toEqual([]);
});
+
+ it('keeps basic rows while omitting extra rows whose labels have not loaded', () => {
+ const unavailableLabels = ((key: string) =>
+ key.startsWith('widgets.preview.metadataLabels.') ? key : t(key)) as TFunction;
+ expect(
+ parsePreviewMetadata(
+ {
+ seed: 17,
+ strength: 0.4,
+ vae: { name: 'VAE' },
+ ideogram4_color_palette: ['green'],
+ control_layers: [{ model: { name: 'Depth model' } }],
+ canvas_v3_metadata: { document: { stacks: { control: [{ id: 'control', name: 'Depth map' }] } } },
+ },
+ { kind: 'image', t: unavailableLabels }
+ )
+ ).toEqual([{ key: 'seed', label: 'Seed', value: '17' }]);
+ });
+});
+
+it('shows useful controls, authored layers, adapters and family settings with raw records left intact', () => {
+ const metadata = {
+ strength: 0.4,
+ refiner_scheduler: 'euler',
+ wan_guidance_scale_low_noise: 2.5,
+ ideogram4_color_palette: ['green', 'gold'],
+ ref_images: [
+ { config: { type: 'ip_adapter', model: { name: 'Style' }, image: { image_name: 'style.png' }, weight: 0.6 } },
+ ],
+ control_layers: [
+ { model: { name: 'Edges' }, image: { image_name: 'edges.png' }, type: 'controlnet', weight: 0.75 },
+ ],
+ canvas_v3_metadata: {
+ document: {
+ stacks: {
+ control: [{ id: 'c', type: 'control', name: 'My edges', adapter: { model: 'control-key', weight: 0.75 } }],
+ },
+ },
+ controlModels: { c: { name: 'Edges' } },
+ },
+ };
+ const entries = parsePreviewMetadata(metadata, image);
+ expect(values(entries)).toMatchObject({
+ strength: '0.4',
+ refiner_scheduler: 'euler',
+ wan_guidance_scale_low_noise: '2.5',
+ ideogram4_color_palette: 'green, gold',
+ 'control_layers-0': 'Edges · controlnet · edges.png · Weight 0.75',
+ 'ref_images-0': 'Style · ip_adapter · style.png · Weight 0.6',
+ canvasLayerCount: '1 layer',
+ });
+ expect(entries.some((entry) => entry.value.includes('My edges') && entry.value.includes('Edges'))).toBe(true);
+ expect(metadata.canvas_v3_metadata.document.stacks.control[0]?.id).toBe('c');
});
+
+it('describes v4 IP-Adapters including model, image, vision, method, weight and schedule', () => {
+ const entry = {
+ ip_adapter_model: { model_name: 'Portrait', base_model: 'sdxl' },
+ image: { image_name: 'portrait.png' },
+ clip_vision_model: 'ViT-G',
+ method: 'style_precise',
+ weight: 0.65,
+ begin_step_percent: 0.2,
+ end_step_percent: 0.9,
+ };
+ const parsed = parsePreviewMetadata({ ipAdapters: [entry] }, image);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0]?.value).toBe('Portrait · portrait.png · ViT-G · style_precise · Weight 0.65 · Steps 0.2–0.9');
+ expect(parsePreviewMetadata({ ref_images: [], ipAdapters: [entry] }, image)).toEqual([]);
+});
+
+it.each(['array', 'entities'] as const)(
+ 'summarizes historical global references in a %s without counting them as Canvas layers',
+ (shape) => {
+ const reference = {
+ id: 'global-style',
+ type: 'reference_image',
+ name: 'Global style',
+ isEnabled: true,
+ ipAdapter: {
+ type: 'ip_adapter',
+ model: { key: 'style', name: 'Historical style', base: 'sdxl', type: 'ip_adapter' },
+ image: { image_name: 'style.png', width: 320, height: 200 },
+ weight: 0.6,
+ method: 'composition',
+ clipVisionModel: 'ViT-L',
+ beginEndStepPct: [0.1, 0.8],
+ },
+ };
+ const canvas = {
+ rasterLayers: [{ id: 'raster', type: 'raster_layer', name: 'Authored raster' }],
+ controlLayers: [],
+ inpaintMasks: [],
+ regionalGuidance: [],
+ referenceImages: shape === 'array' ? [reference] : { entities: [reference] },
+ };
+ const metadata = {
+ canvas_v2_metadata: canvas,
+ ipAdapters: [{ ip_adapter_model: { name: 'Duplicate alias' }, image: { image_name: 'style.png' }, weight: 0.6 }],
+ };
+ const parsed = parsePreviewMetadata(metadata, image);
+ expect(values(parsed)).toMatchObject({
+ 'ref_images-0': 'Historical style · ip_adapter · style.png · ViT-L · composition · Weight 0.6 · Steps 0.1–0.8',
+ canvasLayerCount: '1 layer',
+ });
+ expect(parsed.find((entry) => entry.key === 'ref_images-0')?.label).toBe('Reference images');
+ expect(parsed.filter((entry) => entry.value.includes('Historical style'))).toHaveLength(1);
+ expect(
+ parsed.some((entry) => entry.value.includes('Duplicate alias') || entry.value.includes('Global style'))
+ ).toBe(false);
+ for (const ref_images of [
+ [],
+ [
+ {
+ id: 'modern',
+ config: {
+ type: 'ip_adapter',
+ model: { name: 'Modern style' },
+ image: { image_name: 'modern.png' },
+ weight: 0.4,
+ },
+ },
+ ],
+ ]) {
+ const modern = parsePreviewMetadata({ ...metadata, ref_images }, image);
+ expect(
+ modern.some((entry) => entry.value.includes('Historical style') || entry.value.includes('Duplicate alias'))
+ ).toBe(false);
+ expect(modern.filter((entry) => entry.key.startsWith('ref_images-'))).toHaveLength(ref_images.length);
+ expect(values(modern).canvasLayerCount).toBe('1 layer');
+ }
+ }
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts
index e346dae9fb..e22e01e0f8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts
@@ -1,6 +1,7 @@
import type { TFunction } from 'i18next';
import { readRecordedModelRef } from '@workbench/image-actions';
+import { getLegacyCanvasReferenceEntries } from '@workbench/image-actions/imageRecall';
/**
* Parse variable untyped generation metadata tolerantly into display rows; skip unknown or malformed fields while the
@@ -46,11 +47,17 @@ export const parsePreviewMetadata = (
}
const entries: PreviewMetadataEntry[] = [];
- const push = (key: string, label: string, value: string | number | null, isMultiline = false): void => {
- if (value !== null) {
+ const push = (key: string, label: string | null, value: string | number | null, isMultiline = false): void => {
+ if (value !== null && label !== null) {
entries.push({ key, label, value: String(value), ...(isMultiline ? { isMultiline } : {}) });
}
};
+ // Extra labels load on demand; keep basic rows and raw metadata usable if their namespace is unavailable.
+ const metadataLabel = (key: string): string | null => {
+ const lookup = `widgets.preview.metadataLabels.${key}`;
+ const label = t(lookup);
+ return label === lookup ? null : label;
+ };
const cfgScale = getFiniteNumber(metadata, 'cfg_scale');
push('positivePrompt', t('widgets.preview.fields.prompt'), getString(metadata, 'positive_prompt'), true);
@@ -82,5 +89,269 @@ export const parsePreviewMetadata = (
push('size', t('widgets.preview.fields.size'), `${width} x ${height}`);
}
+ const modelName = (value: unknown): string | null => {
+ const ref = readRecordedModelRef(value);
+ return ref?.name || ref?.key || null;
+ };
+ const primitiveFields = [
+ 'metadata_source',
+ 'app_version',
+ 'generation_mode',
+ 'rand_device',
+ 'cfg_rescale_multiplier',
+ 'strength',
+ 'seamless_x',
+ 'seamless_y',
+ 'dype_preset',
+ 'dype_scale',
+ 'dype_exponent',
+ 'hidiffusion',
+ 'hidiffusion_raunet',
+ 'hidiffusion_window_attn',
+ 'hidiffusion_t1_ratio',
+ 'hidiffusion_t2_ratio',
+ 'refiner_steps',
+ 'refiner_cfg_scale',
+ 'refiner_scheduler',
+ 'refiner_positive_aesthetic_score',
+ 'refiner_negative_aesthetic_score',
+ 'refiner_start',
+ 'refiner_denoising_start',
+ 'z_image_seed_variance_enabled',
+ 'z_image_seed_variance_strength',
+ 'z_image_seed_variance_randomize_percent',
+ 'z_image_shift',
+ 'qwen_image_quantization',
+ 'qwen_image_shift',
+ 'wan_guidance_scale_low_noise',
+ 'krea2_seed_variance_enabled',
+ 'krea2_seed_variance_strength',
+ 'krea2_seed_variance_randomize_percent',
+ 'krea2_rebalance_enabled',
+ 'krea2_rebalance_multiplier',
+ 'krea2_rebalance_weights',
+ 'krea2_reference_kv_cache',
+ 'anima_inpaint_adapter_weight',
+ 'ideogram4_sampler_preset',
+ 'ideogram4_steps',
+ 'ideogram4_guidance_scale',
+ 'ideogram4_mu',
+ 'ideogram4_caption',
+ 'image_size',
+ 'gemini_temperature',
+ 'gemini_thinking_level',
+ 'openai_quality',
+ 'openai_background',
+ 'openai_input_fidelity',
+ 'seedream_watermark',
+ 'seedream_optimize_prompt',
+ 'minimax_h3_duration_seconds',
+ 'minimax_h3_output_mode',
+ 'duration',
+ 'duration_seconds',
+ 'resolution',
+ 'aspect_ratio',
+ 'cfg_scale_low_noise',
+ 'motion_bucket_id',
+ 'noise_aug_strength',
+ 'num_inference_steps',
+ 'ltx2_scheduler',
+ 'ltx2_distilled',
+ 'ltx2_audio_enabled',
+ ];
+ const automaticFields = new Set([
+ 'z_image_shift',
+ 'qwen_image_shift',
+ 'wan_guidance_scale_low_noise',
+ 'ideogram4_steps',
+ 'ideogram4_guidance_scale',
+ 'ideogram4_mu',
+ 'gemini_temperature',
+ 'gemini_thinking_level',
+ 'openai_input_fidelity',
+ ]);
+ for (const key of primitiveFields) {
+ const value = metadata[key];
+ if (value === null && automaticFields.has(key)) {
+ push(key, metadataLabel(key), t('common.auto'));
+ }
+ if (
+ typeof value === 'string' ||
+ (typeof value === 'number' && Number.isFinite(value)) ||
+ typeof value === 'boolean'
+ ) {
+ push(
+ key,
+ metadataLabel(key),
+ key === 'metadata_source' && value === 'canvas_save'
+ ? t('widgets.preview.canvasSaveSource')
+ : typeof value === 'boolean'
+ ? t(value ? 'common.on' : 'common.off')
+ : value,
+ typeof value === 'string' && value.length > 100
+ );
+ }
+ }
+ const componentFields = [
+ 'vae',
+ 'refiner_model',
+ 't5_encoder',
+ 'clip_embed_model',
+ 'gemma2_encoder',
+ 'qwen3_encoder',
+ 'qwen3_source',
+ 'anima_inpaint_adapter',
+ 'qwen3_vl_encoder',
+ 'qwen3_5_encoder',
+ 'mistral_encoder',
+ 'qwen_image_component_source',
+ 'qwen_image_vae',
+ 'qwen_image_qwen_vl_encoder',
+ 'wan_component_source',
+ 'wan_transformer_low_noise',
+ 'wan_vae_model',
+ 'wan_t5_encoder_model',
+ 'minimax_h3_transformer_model',
+ 'minimax_h3_text_encoder_model',
+ 'ideogram4_unconditional_model',
+ ];
+ for (const key of componentFields) {
+ push(key, metadataLabel(key), metadata[key] === null ? t('common.auto') : modelName(metadata[key]));
+ }
+ if (Array.isArray(metadata.ideogram4_color_palette)) {
+ push(
+ 'ideogram4_color_palette',
+ metadataLabel('ideogram4_color_palette'),
+ metadata.ideogram4_color_palette.filter((term) => typeof term === 'string').join(', ')
+ );
+ }
+ const legacyReferences = getLegacyCanvasReferenceEntries(metadata);
+ const showLegacyReferences = !Array.isArray(metadata.ref_images) && Boolean(legacyReferences?.length);
+ for (const key of [
+ 'loras',
+ 'ref_images',
+ 'control_layers',
+ 'controlnets',
+ 't2iAdapters',
+ 'ipAdapters',
+ 'regions',
+ ] as const) {
+ const values = key === 'ref_images' && showLegacyReferences ? legacyReferences : metadata[key];
+ if (!Array.isArray(values) || values.length === 0) {
+ continue;
+ }
+ // New records also carry legacy controlnets/t2iAdapters aliases; display each executed control just once.
+ if ((key === 'controlnets' || key === 't2iAdapters') && Array.isArray(metadata.control_layers)) {
+ continue;
+ }
+ if (key === 'ipAdapters' && (Array.isArray(metadata.ref_images) || showLegacyReferences)) {
+ continue;
+ }
+ values.slice(0, 100).forEach((entry, index) => {
+ if (!isRecord(entry)) {
+ return;
+ }
+ const config = isRecord(entry.config) ? entry.config : isRecord(entry.ipAdapter) ? entry.ipAdapter : entry;
+ const model = modelName(
+ config.model ?? config.lora ?? config.control_model ?? config.t2i_adapter_model ?? config.ip_adapter_model
+ );
+ const image = Array.isArray(config.image) && config.image.length === 1 ? config.image[0] : config.image;
+ const asset = isRecord(image) ? image : null;
+ const original =
+ asset && isRecord(asset.original) && isRecord(asset.original.image) ? asset.original.image : asset;
+ const parts = [
+ model,
+ getString(config, 'type'),
+ getString(config, 'imageName') ??
+ getString(original ?? {}, 'image_name') ??
+ (Array.isArray(config.image)
+ ? config.image
+ .slice(0, 100)
+ .flatMap((image) => (isRecord(image) ? (getString(image, 'image_name') ?? []) : []))
+ .join(', ')
+ : null),
+ getString(config, 'positivePrompt'),
+ getString(config, 'clip_vision_model') ?? getString(config, 'clipVisionModel'),
+ getString(config, 'method'),
+ ];
+ const weight = config.weight ?? config.control_weight;
+ if (typeof weight === 'number' && Number.isFinite(weight)) {
+ parts.push(t('widgets.preview.metadataWeight', { weight }));
+ }
+ const [begin, end] = Array.isArray(config.beginEndStepPct)
+ ? config.beginEndStepPct
+ : [config.begin_step_percent, config.end_step_percent];
+ if (typeof begin === 'number' && Number.isFinite(begin) && typeof end === 'number' && Number.isFinite(end)) {
+ parts.push(t('widgets.preview.metadataSchedule', { begin, end }));
+ }
+ if (parts.some(Boolean)) {
+ push(`${key}-${index}`, metadataLabel(key), parts.filter(Boolean).join(' · '), true);
+ }
+ });
+ if (values.length > 100) {
+ push(`${key}-count`, metadataLabel(key), t('widgets.preview.metadataMore', { count: values.length - 100 }));
+ }
+ }
+ const canvas = isRecord(metadata.canvas_v3_metadata) ? metadata.canvas_v3_metadata : null;
+ const document = canvas && isRecord(canvas.document) ? canvas.document : null;
+ const stacks = document && isRecord(document.stacks) ? document.stacks : null;
+ const legacyCanvas = isRecord(metadata.canvas_v2_metadata) ? metadata.canvas_v2_metadata : null;
+ if (stacks || legacyCanvas) {
+ const controlModels = canvas && isRecord(canvas.controlModels) ? canvas.controlModels : {};
+ let shown = 0;
+ let visited = 0;
+ const visit = (nodes: unknown[], depth: number): number => {
+ if (depth > 10) {
+ return 0;
+ }
+ let count = 0;
+ for (const raw of nodes) {
+ if (visited >= 10000) {
+ break;
+ }
+ visited += 1;
+ if (!isRecord(raw)) {
+ continue;
+ }
+ count += 1;
+ if (raw.type === 'group' && Array.isArray(raw.children)) {
+ count += visit(raw.children, depth + 1);
+ } else if (shown < 100) {
+ shown += 1;
+ const adapter = isRecord(raw.adapter)
+ ? raw.adapter
+ : isRecord(raw.controlAdapter)
+ ? raw.controlAdapter
+ : null;
+ const parts = [
+ getString(raw, 'name'),
+ getString(raw, 'type'),
+ adapter ? (modelName(controlModels[String(raw.id)] ?? adapter.model) ?? getString(adapter, 'model')) : null,
+ getString(raw, 'positivePrompt'),
+ getString(raw, 'negativePrompt'),
+ ];
+ if (adapter && typeof adapter.weight === 'number') {
+ parts.push(t('widgets.preview.metadataWeight', { weight: adapter.weight }));
+ }
+ push(
+ `canvas-${String(raw.id)}-${entries.length}`,
+ metadataLabel('canvas_layers'),
+ parts.filter(Boolean).join(' · '),
+ true
+ );
+ }
+ }
+ return count;
+ };
+ const counts = Object.entries(stacks ?? legacyCanvas!).flatMap(([key, nodes]) =>
+ key !== 'referenceImages' && Array.isArray(nodes) ? [visit(nodes, 0)] : []
+ );
+ push(
+ 'canvasLayerCount',
+ metadataLabel('canvas_layers'),
+ t('widgets.preview.metadataLayerCount', { count: counts.reduce((sum, count) => sum + count, 0) })
+ );
+ }
+
return entries;
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index bcb5daeea5..fbc14f112d 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -9798,9 +9798,22 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
expect(getActiveProject(state).queue.items[0]?.status).toBe('completed');
});
- it('submitCanvasInvocationSnapshot enqueues a pre-compiled graph bound for the canvas', () => {
+ it('enqueues a Canvas expansion with detached authored metadata and the actual sample seed for recall', () => {
+ const initial = createInitialWorkbenchState();
+ const canvas = structuredClone(getCanvas(initial));
+ canvas.document.bbox = { height: 48, width: 32, x: 17, y: 23 };
+ const recordedCanvas = {
+ controlModels: {},
+ document: canvas.document,
+ settings: { strength: 0.75 },
+ version: 1,
+ };
const graph: GraphContract = {
- backendGraph: { edges: [], id: 'canvas-backend-graph', nodes: {} },
+ backendGraph: {
+ edges: [],
+ id: 'canvas-backend-graph',
+ nodes: { metadata: { canvas_v3_metadata: recordedCanvas, id: 'metadata', type: 'core_metadata' } },
+ },
edges: [],
id: 'canvas-graph',
label: 'Canvas',
@@ -9809,23 +9822,27 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
version: 1,
};
- const initial = createInitialWorkbenchState();
+ const values = createGenerateValues({
+ dynamicPromptsCombinatorial: false,
+ dynamicPromptsSampleSeed: 99,
+ negativePrompt: 'avoid blur',
+ positivePrompt: 'inpaint {red|green} cat',
+ seed: 42,
+ seedMode: 'fixed',
+ });
const state = workbenchReducer(initial, {
backendSupportsCancellation: true,
- canvas: structuredClone(getCanvas(initial)),
+ canvas,
destination: 'canvas',
generate: {
negativePromptNodeId: 'negative_prompt',
positivePromptNodeId: 'positive_prompt',
seedNodeId: 'seed',
- values: createGenerateValues({
- negativePrompt: 'avoid blur',
- positivePrompt: 'inpaint prompt',
- seed: 42,
- seedMode: 'fixed',
- }),
+ values,
},
graph,
+ positivePrompts: ['inpaint green cat'],
+ positivePromptsSampleSeed: 7,
projectId: initial.activeProjectId,
type: 'submitCanvasInvocationSnapshot',
});
@@ -9835,9 +9852,12 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
expect(queueItem?.snapshot.sourceId).toBe('canvas');
expect(queueItem?.snapshot.destination).toBe('canvas');
expect(queueItem?.snapshot.graph).toEqual({ id: 'canvas-graph', label: 'Canvas' });
+ expect(queueItem?.snapshot.recall?.canvasMetadata).toEqual({ canvas_v3_metadata: recordedCanvas });
+ expect(queueItem?.snapshot.recall?.canvasMetadata?.canvas_v3_metadata).not.toBe(recordedCanvas);
expect(queueItem?.snapshot.recall?.generateValues).toMatchObject({
+ dynamicPromptsSampleSeed: 7,
negativePrompt: 'avoid blur',
- positivePrompt: 'inpaint prompt',
+ positivePrompt: 'inpaint {red|green} cat',
seed: 42,
seedMode: 'fixed',
});
@@ -9849,14 +9869,30 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =
kind: 'generate',
negativePrompt: 'avoid blur',
negativePromptNodeId: 'negative_prompt',
- positivePrompt: 'inpaint prompt',
+ positivePrompt: 'inpaint {red|green} cat',
positivePromptNodeId: 'positive_prompt',
+ positivePrompts: ['inpaint green cat'],
seed: 42,
seedNodeId: 'seed',
seedStep: 0,
});
expect(queueItem?.snapshot.resultNodeIds).toEqual(['canvas_output']);
expect(getActiveProject(state).invocation.sourceId).toBe('canvas');
+
+ canvas.document.bbox.x = 999;
+ recordedCanvas.settings.strength = 0.1;
+ values.positivePrompt = 'later prompt';
+ values.dynamicPromptsSampleSeed = 101;
+
+ expect(queueItem?.snapshot.recall?.canvasMetadata?.canvas_v3_metadata).toMatchObject({
+ document: { bbox: { height: 48, width: 32, x: 17, y: 23 } },
+ settings: { strength: 0.75 },
+ version: 1,
+ });
+ expect(queueItem?.snapshot.recall?.generateValues).toMatchObject({
+ dynamicPromptsSampleSeed: 7,
+ positivePrompt: 'inpaint {red|green} cat',
+ });
});
it('queues the frozen canvas supplied by an immutable canvas invocation instead of cloning live state', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 6be32dd9c8..eb8a1254c8 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -4084,9 +4084,21 @@ const enqueueCompiledSnapshot = (
: route.sourceId === 'generate'
? normalizeGenerateWidgetValues(widgetStates.generate?.values)
: null;
+ const recordedCanvas =
+ route.sourceId === 'canvas'
+ ? Object.values(backendGraph?.nodes ?? {}).find((node) => node.type === 'core_metadata')?.canvas_v3_metadata
+ : undefined;
const recalledSampleSeed = expansionSampleSeed === null ? {} : { dynamicPromptsSampleSeed: expansionSampleSeed };
const recall = generateRecallValues
- ? { generateValues: { ...cloneGenerateWidgetValues(generateRecallValues), ...recalledSampleSeed } }
+ ? {
+ ...(recordedCanvas && typeof recordedCanvas === 'object' && !Array.isArray(recordedCanvas)
+ ? { canvasMetadata: { canvas_v3_metadata: structuredClone(recordedCanvas) } }
+ : {}),
+ generateValues: {
+ ...cloneGenerateWidgetValues(generateRecallValues),
+ ...recalledSampleSeed,
+ },
+ }
: videoSettings
? { videoValues: { ...cloneVideoWidgetValues(videoSettings), ...recalledSampleSeed } }
: undefined;
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 72ca9e845f..aa4f1e16cd 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -193,6 +193,8 @@ const EDITOR_BOOT_SHARED_MODULES = [
'/workbench/shell/topbar/ProjectSwitcher.tsx',
// The canvas dims sync reads the render-size keys at boot; the lazy canvas slots and compiler share them.
'/workbench/widgets/canvas/invoke/canvasScaling.ts',
+ // API recall (editor boot) and the lazy Canvas controls share strength defaults; avoid a standalone boot request.
+ '/workbench/widgets/canvas/invoke/canvasStrength.ts',
// The canvas dims sync and the lazy Canvas widget and Frame tool share the model grid and the centred resize.
'/workbench/widgets/canvas/bboxGrid.ts',
// Generate's UI adapter (editor boot) and the lazy canvas Frame tool share the saved aspect ratios; alone they cost a