Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix: upgrade safety, install retries, and LAN project access (#9960)
Josh Corbetta84b639eb4ae
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdxindex 4e599833db..e355fb6b83 100644--- a/docs/src/content/docs/development/Architecture/model-manager.mdx+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx@@ -555,7 +555,7 @@ Startup serializes stale-claim scans in-process and across processes with the pe| Path | Meaning || --- | --- || `tmpinstall_*/` | A remote install's staging directory. Downloads land here before the install moves them. |-| `tmpinstall_*/.invokeai_install.json` | The staging marker, format version 1: `version`, `source`, `access_token` (Hugging Face and URL sources only), `config_in`, `status`, `updated_at`, per-file resume metadata in `files`, and `recovery_required: true` once a transfer failed in a way that needs manual recovery. |+| `tmpinstall_*/.invokeai_install.json` | The staging marker, format version 1: `version`, `source`, `access_token` (Hugging Face and URL sources only), `config_in`, `status`, `updated_at`, per-file resume metadata in `files` (see below), and `recovery_required: true` once a transfer failed in a way that needs manual recovery. || `.<name>.invokeai_install_active` | An active claim on the sibling `<name>`, held by a live install or orphan deletion. || `.<name>.invokeai_install_recovery_required` | A recovery sentinel: `<name>` holds data a failed transfer could not roll back. || `.invokeai_install_claims.lock` | Serializes the startup sweep of stale claims. |@@ -570,6 +570,8 @@ Marker writes replace the marker atomically: the new content goes to a temporaryAt startup the installer sweeps stale claims, then removes staging directories that no install can resume: those without a marker and those whose marker has a terminal status. It keeps claimed directories, directories holding a registered model, and recovery data. A staging directory whose marker exists but is unusable (torn, not JSON, or a format version this release does not know, for example after a downgrade) may hold the only copy of a download, so startup keeps it, logs a warning naming it, and never restores or reuses it. Orphaned model cleanup lists such a directory, unless it is claimed, holds recovery data, or holds a registered model, so it can be deleted once it is not needed.+Each `files` entry records one download part: its `url`, `canonical_url` and `final_url`, the validators `etag` and `last_modified`, `expected_total_bytes`, the `download_path` it writes, and `resume_required`, `resume_refused` and `resume_message`. The installer rewrites the marker as each part starts, once its response headers arrived, so a crash leaves the running part's validator and file name on disk. On a resume or a restore, the download queue's `DownloadJob` names the partial file a part would continue (`resumable_partial()`) and whether it may (`may_resume_partial()`): only with a recorded validator, sent as If-Range, and only if the server has not already refused to continue it. A server whose file changed answers with the whole file, and the part pauses as restart-required instead of splicing two revisions. Any other partial is deleted and its part reported with `resume_from_scratch`, as is a part that had started but whose partial and finished file are both gone. A recorded `download_path` outside the staging directory is ignored. Entries written before `resume_refused` existed count as refused when `resume_required` is set and the message is the queue's refusal message. When a partial that must restart cannot be deleted (on Windows, while another process holds it open), the resume or restart fails with a conflict rather than continue it without a validator; during startup restore the job stays paused.+Startup restores nonterminal install markers automatically, except markers with `PAUSED` status. If shutdown interrupts restoration of a marker already visited, that job is saved as `PAUSED`; markers later in the scan remain unchanged. On the next service startup, non-paused markers resume automatically, while both user-paused and shutdown-paused jobs stay paused until `resume_job()` is called. Partial files and resume metadata remain in their staging directories across this cycle.Before a transfer, the installer flushes the recovery-sentinel file and, on non-Windows platforms, its containing directory. A file or directory `fsync` error aborts the install before source files move; unsupported directory `fsync` is treated as a failure, not as best-effort durability. Sentinel cleanup unlinks the file before syncing the containing directory. If that final sync fails, the installer logs a warning and continues cleanup; the unlink may not survive a crash, so a stale sentinel can reappear and require manual inspection. These steps do not promise crash durability on every filesystem or storage device.diff --git a/docs/src/content/docs/development/Guides/sqlite-migrations.mdx b/docs/src/content/docs/development/Guides/sqlite-migrations.mdxindex 4e5c671cc9..b65e01e970 100644--- a/docs/src/content/docs/development/Guides/sqlite-migrations.mdx+++ b/docs/src/content/docs/development/Guides/sqlite-migrations.mdx@@ -1,6 +1,6 @@---title: Database Migrations-lastUpdated: 2026-10-04+lastUpdated: 2026-10-19---InvokeAI migrates its database with its own migrator. Migrations live in `invokeai/app/services/shared/sqlite_migrator/migrations/` and are discovered automatically when the database is initialized.@@ -128,12 +128,14 @@ Existing SQLite databases are bootstrapped from legacy numeric rows:- legacy version `2` maps to `migration_2`- and so on-If a database contains an applied migration ID or legacy numeric version unknown to the current code, startup fails before running migrations. This prevents older code from running against a newer schema. Downgrading to an InvokeAI version that does not know about migrations already applied by a newer version is not supported.+If a database contains an applied migration ID or legacy numeric version unknown to the current code, startup fails before running migrations or changing the database. This prevents older code from running against a newer schema. Downgrading to an InvokeAI version that does not know about migrations already applied by a newer version is not supported. The error keeps its first clause and the unknown IDs, then says that a newer version updated the database and how to go back: for a SQLite file, the backup directory and the backup file pattern, never a specific backup; for a server database, the backup the user made. It ends with `UPGRADE_DOCS_URL` (in `sqlite_migrator_impl.py`), the URL of the [Upgrading to v7](/start-here/upgrading/) page; keep the page at that URL.For legacy migrations, the two metadata tables must agree. For example, `applied_migrations` may only record `migration_2` with `legacy_version = 2` if the legacy `migrations` table also contains version `2`. If these records are inconsistent, startup fails before user migration callbacks run.When opening a file-backed legacy SQLite database for the first time after this migration system change, the migrator may need to create and populate `applied_migrations` even if no user migration callbacks need to run. This metadata bootstrap is backed up before the new metadata table is written. The migrator backs up a SQLite database file before it migrates it; it makes no backups of a server database.+Before the first migration of a database that already had migrations, the migrator logs one WARNING with `UPGRADE_DOCS_URL`, after the backup and before any migration, so a crash mid-migration still leaves it. For a SQLite file it names the database and the backup; for a server database it names the URL without its password and says that no backup was made. A database created in this run, and an in-memory one, get no warning.+## TestsAdd focused tests for each migration under:diff --git a/docs/src/content/docs/start-here/installation.mdx b/docs/src/content/docs/start-here/installation.mdxindex 02e2680db6..5cd3555a94 100644--- a/docs/src/content/docs/start-here/installation.mdx+++ b/docs/src/content/docs/start-here/installation.mdx@@ -1,6 +1,6 @@---title: Simple Installation-lastUpdated: 2026-02-18+lastUpdated: 2026-10-20---import { LinkCard, Tabs, TabItem, Steps } from '@astrojs/starlight/components'@@ -60,7 +60,7 @@ The Launcher manages your Invoke install. Follow these instructions to downloadRun the Launcher you just set up if you haven't already. Click **Install** and follow the instructions to install (or update) Invoke.-If you have an existing Invoke installation, you can select it and let the launcher manage the install. You'll be able to update or launch the installation.+If you have an existing Invoke installation, you can select it and let the launcher manage the install. You'll be able to update or launch the installation. Installing v7 into an existing installation upgrades it in place, and older versions cannot use its database afterwards: read [Upgrading to v7](/start-here/upgrading/) first. To try a pre-release, install it into a new, empty folder instead, which leaves your current installation as it is.### Updatingdiff --git a/docs/src/content/docs/start-here/manual.mdx b/docs/src/content/docs/start-here/manual.mdxindex 6e7c7f3cca..bb05daa709 100644--- a/docs/src/content/docs/start-here/manual.mdx+++ b/docs/src/content/docs/start-here/manual.mdx@@ -1,6 +1,6 @@---title: Manual Installation-lastUpdated: 2026-07-14+lastUpdated: 2026-10-19---import { LinkCard, Tabs, TabItem, Steps, LinkButton } from '@astrojs/starlight/components'@@ -240,6 +240,8 @@ The following commands vary depending on the version of Invoke being installed a```</TabItem></Tabs>++ To keep an existing install as it is, give v7 a directory of its own: see [Run v7 alongside v6](/start-here/upgrading/#run-v7-alongside-v6).</Steps>If you run Invoke on a headless server, you might want to install and run Invoke on the command line.diff --git a/docs/src/content/docs/start-here/upgrading.mdx b/docs/src/content/docs/start-here/upgrading.mdxnew file mode 100644index 0000000000..79ea10c249--- /dev/null+++ b/docs/src/content/docs/start-here/upgrading.mdx@@ -0,0 +1,155 @@+---+title: Upgrading to v7+lastUpdated: 2026-10-20+---++import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'++Upgrading an existing install to v7 is one-way. This page covers what the upgrade changes, where the backup of your database is, how to go back to an older version and return to v7, and how to try v7 without touching your current install.++## The upgrade is one-way++The first time v7 starts on an existing install, it updates the database at `<root>/databases/invokeai.db` in place. After that, older versions cannot use it:++- v6.14 and later, and earlier v7 builds, stop at startup with an error that begins `Database contains unknown applied migration IDs`.+- v6.13 and earlier do not recognize the update. They start, log `Database update needed`, write a backup, and log `Database updated successfully`, though they changed nothing. They then run on a database they were not written for, where they can misbehave or damage it. They do this on every start, and each of these backups holds the v7 database, not a v6 one.++Restore a backup before you run any older version on this install.++The update changes the database only. Your images in `outputs/` and your models are left as they are.++## Backups++Before every update of the database, Invoke copies it to a backup in the same folder, `<root>/databases/`:++```text+invokeai_backup_<YYYYMMDD>-<HHMMSS>.db+```++When two backups are made in the same second, the later one gets a number, e.g. `invokeai_backup_20261019-093000-1.db`. Before the update, the startup log shows a warning that names the backup:++```text+Updating the database at <root>/databases/invokeai.db. Older versions of InvokeAI cannot use it after this update. Its current state is backed up to <root>/databases/invokeai_backup_20261019-093000.db; ...+```++Invoke never deletes backups. Delete old ones yourself once you no longer need them.++### Which backup to restore++To go back to v6, restore the backup written when you **first started v7**. It holds your database as v6 left it. Its name carries the date and time of that first start, in your computer's local time, and the names sort by time: it is the first backup at or after that start.++- **Not an older backup.** v6 writes backups with the same name when it updates the database itself, so older files are earlier v6 states, without your work since then.+- **Not a newer backup.** Each holds a database v6 cannot use: v7 writes one each time it updates the database, and v6.13 and earlier write one each time they start on it, as described above. If you already started an older version on the v7 database, the newest backup is one of these.++The log of that first v7 start names the file in the line `Backing up database to <root>/databases/invokeai_backup_<YYYYMMDD>-<HHMMSS>.db`. v7.0.0-alpha.1 to alpha.3 log only that line; later versions also name it in the warning shown above. Without that log, go by the time of the first start.++Nothing you did in v7 after that start is in the backup. Images you generated in v7 stay in `outputs/`, but v6's gallery does not show them. Models you installed in v7 stay in the models folder, but v6's model list does not have them.++:::caution[Models installed in v7]+v6 lists the models you installed in v7 as orphaned, and its **Sync Models** in the Model Manager offers to delete them. Keep them if you may go back to v7: the v7 database you set aside, `invokeai.db.v7`, still uses them.+:::++### MySQL and MariaDB++Invoke makes no backup of a server database. Back it up yourself before upgrading, as [MySQL and MariaDB](/configuration/external-database/) describes. To go back, restore that backup.++## Restore a backup++<Steps>++1. Stop Invoke.++2. Open the `databases` folder in your root directory.++3. Move the current database aside: rename `invokeai.db` to `invokeai.db.v7`.++4. **Required:** if `invokeai.db-wal` or `invokeai.db-shm` exist, rename them to `invokeai.db.v7-wal` and `invokeai.db.v7-shm`. Left in place, the v7 database's write-ahead log would be applied to the restored file and could corrupt it. Renamed this way, the three files stay a complete copy of your v7 database.++5. Copy the backup you chose to `invokeai.db`. Copy it rather than rename it, so the backup stays as it is.++6. Start the older version.++</Steps>++Steps 3 to 5 as commands, with your root directory and the backup's name filled in:++<Tabs syncKey="operatingSystem">+ <TabItem label="Windows" icon="seti:windows">+ ```ps+ cd <root>\databases+ Rename-Item invokeai.db invokeai.db.v7+ if (Test-Path invokeai.db-wal) { Rename-Item invokeai.db-wal invokeai.db.v7-wal }+ if (Test-Path invokeai.db-shm) { Rename-Item invokeai.db-shm invokeai.db.v7-shm }+ Copy-Item invokeai_backup_<YYYYMMDD>-<HHMMSS>.db invokeai.db+ ```+ </TabItem>+ <TabItem label="Linux/MacOS" icon="linux">+ ```bash+ cd <root>/databases+ mv invokeai.db invokeai.db.v7+ if [ -e invokeai.db-wal ]; then mv invokeai.db-wal invokeai.db.v7-wal; fi+ if [ -e invokeai.db-shm ]; then mv invokeai.db-shm invokeai.db.v7-shm; fi+ cp invokeai_backup_<YYYYMMDD>-<HHMMSS>.db invokeai.db+ ```+ </TabItem>+</Tabs>++Starting v7 on the restored database updates it again, as your first v7 start did: v7 writes another backup and logs the warning. The updated database has none of your earlier v7 work; that is in `invokeai.db.v7`. To continue with it, switch back to it instead.++## Switch back to the v7 database++To return to v7 after restoring a backup, put the v7 database you set aside back in place. What you did in v6 since the restore is not in it. Models you installed in v6 since then are missing from v7's model list, and v7 lists them as orphaned.++<Steps>++1. Stop Invoke.++2. Open the `databases` folder in your root directory.++3. Move the restored database aside: rename `invokeai.db` to `invokeai.db.v6`, and, if they exist, `invokeai.db-wal` and `invokeai.db-shm` to `invokeai.db.v6-wal` and `invokeai.db.v6-shm`.++4. Rename `invokeai.db.v7` to `invokeai.db`.++5. **Required:** if `invokeai.db.v7-wal` or `invokeai.db.v7-shm` exist, rename them to `invokeai.db-wal` and `invokeai.db-shm`. The write-ahead log can hold changes not yet written to the database file, and SQLite finds it only under the database's name.++6. Start v7.++</Steps>++Steps 3 to 5 as commands:++<Tabs syncKey="operatingSystem">+ <TabItem label="Windows" icon="seti:windows">+ ```ps+ cd <root>\databases+ Rename-Item invokeai.db invokeai.db.v6+ if (Test-Path invokeai.db-wal) { Rename-Item invokeai.db-wal invokeai.db.v6-wal }+ if (Test-Path invokeai.db-shm) { Rename-Item invokeai.db-shm invokeai.db.v6-shm }+ Rename-Item invokeai.db.v7 invokeai.db+ if (Test-Path invokeai.db.v7-wal) { Rename-Item invokeai.db.v7-wal invokeai.db-wal }+ if (Test-Path invokeai.db.v7-shm) { Rename-Item invokeai.db.v7-shm invokeai.db-shm }+ ```+ </TabItem>+ <TabItem label="Linux/MacOS" icon="linux">+ ```bash+ cd <root>/databases+ mv invokeai.db invokeai.db.v6+ if [ -e invokeai.db-wal ]; then mv invokeai.db-wal invokeai.db.v6-wal; fi+ if [ -e invokeai.db-shm ]; then mv invokeai.db-shm invokeai.db.v6-shm; fi+ mv invokeai.db.v7 invokeai.db+ if [ -e invokeai.db.v7-wal ]; then mv invokeai.db.v7-wal invokeai.db-wal; fi+ if [ -e invokeai.db.v7-shm ]; then mv invokeai.db.v7-shm invokeai.db-shm; fi+ ```+ </TabItem>+</Tabs>++## Run v7 alongside v6++Each install's root directory holds its own database, images and models. Give v7 a root of its own, and your v6 install stays as it is. The v7 install starts with an empty gallery and no models.++- **Launcher:** install v7 into a new, empty folder. Do not select your existing install: that upgrades it in place. The folder you install into is v7's root directory.+- **Manual install:** install v7 into a new directory, as [Manual Installation](/start-here/manual/) describes, and start it with `--root` set to that directory, or set the `INVOKEAI_ROOT` environment variable. `--root` takes precedence over `INVOKEAI_ROOT`, which takes precedence over the directory of the active virtual environment; see [InvokeAI Root Directory](/configuration/invokeai-yaml/#invokeai-root-directory).++:::caution[Keep the models folders apart]+Do not point both installs' `models_dir` at the same folder. Each install knows only the models it installed itself, so **Clean up orphaned models** in one install's Model Manager lists the other install's models as orphaned and offers to delete them.+:::diff --git a/docs/src/content/docs/troubleshooting/faq.mdx b/docs/src/content/docs/troubleshooting/faq.mdxindex 1cef603655..b41f042642 100644--- a/docs/src/content/docs/troubleshooting/faq.mdx+++ b/docs/src/content/docs/troubleshooting/faq.mdx@@ -1,6 +1,6 @@---title: FAQ-lastUpdated: 2026-02-19+lastUpdated: 2026-10-20---import { LinkCard } from '@astrojs/starlight/components';@@ -35,6 +35,10 @@ Next, find and copy your install's `models` folder path (this could be your custFollow the same steps to scan and import the missing models.+## v6 won't start after trying v7++Once v7 has run on an install, it has updated the database, and older versions cannot use it. v6.14 and later stop at startup with `Database contains unknown applied migration IDs`. v6.13 and earlier may start, but on a database they were not written for, where they can misbehave or damage it: stop them. Keep using v7, or restore the backup v7 made of your v6 database before you run any older version. [Upgrading to v7](/start-here/upgrading/) explains which backup to restore and how.+## Slow generation- Check the [system requirements] to ensure that your system is capable of generating images.diff --git a/docs/src/content/docs/troubleshooting/known-bugs.mdx b/docs/src/content/docs/troubleshooting/known-bugs.mdxindex eef59317ac..cc0a8b0850 100644--- a/docs/src/content/docs/troubleshooting/known-bugs.mdx+++ b/docs/src/content/docs/troubleshooting/known-bugs.mdx@@ -1,7 +1,7 @@---title: Known Bugsdescription: Places where the current release does not yet behave as the documentation describes, with workarounds.-lastUpdated: 2026-10-10+lastUpdated: 2026-10-19---This page lists known cases where InvokeAI does not yet behave as this documentation describes, or no longer behaves as v6 did. Each entry explains what happens instead and how to work around it. Entries are removed once the fix is released.@@ -22,6 +22,19 @@ This page lists known cases where InvokeAI does not yet behave as this documenta**Documented behavior:** If a change cannot be saved yet, your browser keeps it and the tab that made it keeps retrying until the save goes through. See [Saving and syncing](/users-guide/projects/introduction/#saving-and-syncing).-**Current behavior:** When Invoke is opened over plain HTTP from another computer (for example `http://192.168.1.20:9090` on your local network), the browser turns off a feature Invoke uses to tell open tabs apart (Web Locks), so Invoke cannot tell whether another tab is still open. Opening Invoke in another tab, or reloading another tab, then takes over the unsaved changes a still-open tab is holding: an edit whose save had not finished when the tab was hidden, or one kept while the server was unreachable. The second tab saves them, and undoing the edit in the first tab no longer removes it.+**Current behavior:** When Invoke is opened over plain HTTP from a network address (for example `http://192.168.1.20:9090`, from another computer or from the one running Invoke), the browser turns off a feature Invoke uses to tell open tabs apart (Web Locks), so Invoke cannot tell whether another tab is still open. Opening Invoke in another tab, or reloading another tab, then takes over the unsaved changes a still-open tab is holding: an edit whose save had not finished when the tab was hidden, or one kept while the server was unreachable. The second tab saves them, and undoing the edit in the first tab no longer removes it.**Workaround:** Open Invoke over HTTPS, or at `localhost` on the computer running it, where browsers provide Web Locks.++### Plain-HTTP access: copying is off and some project actions work in one tab only++**Documented behavior:** Copy buttons put text and images on your clipboard. Deleting a project, resolving a save conflict, and discarding queue recovery data each wait until no other open tab is still running that project's queue.++**Current behavior:** Over plain HTTP from a network address, the browser turns off clipboard access as well as Web Locks. The Launchpad shows a notice saying so, which you can dismiss for that address. Then:++- Copy buttons and copy menu items stay visible but disabled, and say that copying needs HTTPS or localhost.+- On the canvas, the copy, cut and paste shortcuts show a message that they need HTTPS or localhost.+- Deleting a project, and **Discard** or **Save as new** in a save conflict, work in the current tab only. Invoke still refuses while it knows of queue runs for the project, but it cannot see runs in another open tab that it has not recorded yet. Keep Invoke open in one tab while you do these.+- Discarding queue recovery data is refused, because Invoke cannot confirm that no other tab is still running those runs. You can still export it.++**Workaround:** Open Invoke over HTTPS, or at `localhost` on the computer running it, where browsers provide both.diff --git a/invokeai/app/services/download/__init__.py b/invokeai/app/services/download/__init__.pyindex 48ded7d549..8590948826 100644--- a/invokeai/app/services/download/__init__.py+++ b/invokeai/app/services/download/__init__.py@@ -1,15 +1,18 @@"""Init file for download queue."""from invokeai.app.services.download.download_base import (+ RESUME_REFUSED_MESSAGE,DownloadJob,DownloadJobStatus,DownloadQueueServiceBase,MultiFileDownloadJob,UnknownJobIDException,+ in_progress_path,)from invokeai.app.services.download.download_default import DownloadQueueService, TqdmProgress__all__ = [+ "RESUME_REFUSED_MESSAGE","DownloadJob","MultiFileDownloadJob","DownloadQueueServiceBase",@@ -17,4 +20,5 @@ __all__ = ["TqdmProgress","DownloadJobStatus","UnknownJobIDException",+ "in_progress_path",]diff --git a/invokeai/app/services/download/download_base.py b/invokeai/app/services/download/download_base.pyindex 56f79b3953..4bc0f9075c 100644--- a/invokeai/app/services/download/download_base.py+++ b/invokeai/app/services/download/download_base.py@@ -35,6 +35,14 @@ class ServiceInactiveException(Exception):"""This exception is raised when user attempts to initiate a download before the service is started."""+RESUME_REFUSED_MESSAGE = "Resume refused by server. Restart required."+++def in_progress_path(path: Path) -> Path:+ """Where a download writes `path` until it is complete."""+ return path.with_name(path.name + ".downloading")++SingleFileDownloadEventHandler = Callable[["DownloadJob"], None]SingleFileDownloadExceptionHandler = Callable[["DownloadJob", Optional[Exception]], None]MultiFileDownloadEventHandler = Callable[["MultiFileDownloadJob"], None]@@ -191,11 +199,64 @@ class DownloadJob(DownloadJobBase):expected_total_bytes: Optional[int] = Field(default=None, description="Expected total size of the download")resume_required: bool = Field(default=False, description="True if server refused resume; restart required")resume_message: Optional[str] = Field(default=None, description="Message explaining why resume is required")+ resume_refused: bool = Field(+ default=False,+ description="True if the server refused to continue the partial file, so it must restart from the beginning",+ )resume_from_scratch: bool = Field(default=False,- description="True if resume metadata existed but the partial file was missing and the download restarted from the beginning",+ description="True if the download restarted from the beginning instead of resuming: its partial file was missing, or could not be checked against the server's current file (no recorded validator, or the server had refused to resume it) and was discarded",)+ @property+ def resume_validator(self) -> Optional[str]:+ """The If-Range value a resumed request sends: the ETag, else the Last-Modified date, of the revision the+ partial file holds. With it, a server whose file has changed sends the whole new revision instead of a range."""+ return self.etag or self.last_modified++ def expected_download_path(self) -> Optional[Path]:+ """The file this job writes, as far as it is known before a response names it.++ A file destination is that file. A directory destination takes the file name from the response, so this is+ the recorded `download_path`, else the name of the directory's only partial file; with none or several, it is+ unknown. A caller that sets `download_path` from untrusted data must keep it inside `dest`.+ """+ if not self.dest.is_dir():+ return self.dest+ if self.download_path is not None:+ return self.download_path+ try:+ partials = list(self.dest.glob("*.downloading"))+ except OSError:+ return None+ if len(partials) != 1:+ return None+ return partials[0].with_name(partials[0].name.removesuffix(".downloading"))++ def may_resume_partial(self) -> bool:+ """Whether this job's partial file may continue rather than start over.++ A recorded validator lets the server refuse a file that changed since the partial was written. A partial the+ server already refused holds a revision it no longer continues. A part only interrupted mid-transfer keeps a+ partial that may resume.+ """+ return self.resume_validator is not None and not self.resume_refused++ def resumable_partial(self) -> Optional[Path]:+ """The partial file this job would continue with a Range request, if one is on disk.++ The request sends `resume_validator` as If-Range when there is one. Without one, nothing stops the server+ from appending a newer revision of the file to it.+ """+ path = self.expected_download_path()+ if path is None:+ return None+ partial = in_progress_path(path)+ try:+ return partial if partial.stat().st_size > 0 else None+ except OSError:+ return None+def __hash__(self) -> int:"""Return hash of the string representation of this object, for indexing."""return hash(str(self))@@ -287,7 +348,8 @@ class DownloadQueueServiceBase(ABC):The `dest` argument is a Path object pointing to a directory. All downloadswith be placed inside this directory. The callbacks will receive the- MultiFileDownloadJob.+ MultiFileDownloadJob. `on_start` runs as each part starts, once its response+ headers have arrived; the first call is the job's start."""passdiff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.pyindex 4848f1935a..750f7fcbcc 100644--- a/invokeai/app/services/download/download_default.py+++ b/invokeai/app/services/download/download_default.py@@ -8,7 +8,7 @@ import tracebackfrom pathlib import Path, PurePosixPath, PureWindowsPathfrom queue import Empty, PriorityQueuefrom shutil import disk_usage-from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Set+from typing import TYPE_CHECKING, Any, Dict, List, Literal, NoReturn, Optional, Setfrom urllib.parse import urljoin, urlparseimport requests@@ -18,6 +18,7 @@ from tqdm import tqdmfrom invokeai.app.services.config import InvokeAIAppConfig, get_configfrom invokeai.app.services.download.download_base import (+ RESUME_REFUSED_MESSAGE,DownloadEventHandler,DownloadExceptionHandler,DownloadJob,@@ -28,6 +29,7 @@ from invokeai.app.services.download.download_base import (MultiFileDownloadJob,ServiceInactiveException,UnknownJobIDException,+ in_progress_path,)from invokeai.app.util.misc import get_iso_timestampfrom invokeai.app.util.ssrf import (@@ -425,81 +427,27 @@ class DownloadQueueService(DownloadQueueServiceBase):url = job.canonical_url or str(job.source)header = {"Authorization": f"Bearer {job.access_token}"} if job.access_token else {}- had_resume_metadata = bool(job.etag or job.last_modified)open_mode = "wb"resume_from = 0- if not job.dest.is_dir():- job.download_path = job.dest- in_progress_path = self._in_progress_path(job.download_path)- if in_progress_path.exists():- resume_from = in_progress_path.stat().st_size- job.bytes = resume_from- self._logger.debug(- f"Resume check: in-progress file found at {in_progress_path} size={resume_from} bytes"- )- if resume_from > 0:- if job.etag:- header["If-Range"] = job.etag- elif job.last_modified:- header["If-Range"] = job.last_modified- header["Range"] = f"bytes={resume_from}-"- open_mode = "ab"- else:- self._logger.debug(f"Resume check: no in-progress file at {in_progress_path}")- elif job.download_path:- # Resume for directory downloads when we already know the filename.- in_progress_path = self._in_progress_path(job.download_path)- if in_progress_path.exists():- resume_from = in_progress_path.stat().st_size- job.bytes = resume_from- self._logger.debug(- f"Resume check (dir): in-progress file found at {in_progress_path} size={resume_from} bytes"- )- if resume_from > 0:- if job.etag:- header["If-Range"] = job.etag- elif job.last_modified:- header["If-Range"] = job.last_modified- header["Range"] = f"bytes={resume_from}-"- open_mode = "ab"- else:- self._logger.debug(f"Resume check (dir): no in-progress file at {in_progress_path}")- elif job.dest.is_dir():- # Attempt to infer a single in-progress file from disk for directory downloads.+ if (expected_path := job.expected_download_path()) is not None:+ job.download_path = expected_pathtry:- candidates = sorted(job.dest.glob("*.downloading"))- except OSError:- candidates = []- if len(candidates) == 1:- inferred = candidates[0].with_name(candidates[0].name.removesuffix(".downloading"))- job.download_path = inferred- try:- resume_from = candidates[0].stat().st_size- except FileNotFoundError:- # The .downloading file was renamed/deleted between glob and stat (race condition); skip resume.- job.download_path = None- else:- job.bytes = resume_from- self._logger.debug(- f"Resume check (dir): inferred in-progress file path={candidates[0]} size={resume_from} bytes"- )- if resume_from > 0:- if job.etag:- header["If-Range"] = job.etag- elif job.last_modified:- header["If-Range"] = job.last_modified- header["Range"] = f"bytes={resume_from}-"- open_mode = "ab"- else:- self._logger.debug(- "Resume check (dir): no prior download_path available; cannot resume from disk "- f"(candidates={len(candidates)})"- )-- if resume_from == 0:+ resume_from = in_progress_path(expected_path).stat().st_size+ except FileNotFoundError:+ pass+ if resume_from > 0:+ job.bytes = resume_from+ self._logger.debug(f"Resume check: in-progress file for {job.download_path} has {resume_from} bytes")+ if validator := job.resume_validator:+ header["If-Range"] = validator+ header["Range"] = f"bytes={resume_from}-"+ open_mode = "ab"+ else:+ self._logger.debug(f"Resume check: no in-progress file for {job.dest}")job.bytes = 0- if had_resume_metadata:+ job.resume_refused = False+ if job.resume_validator:job.resume_from_scratch = Truejob.resume_message = "Partial file missing. Restarted download from the beginning."@@ -537,14 +485,11 @@ class DownloadQueueService(DownloadQueueServiceBase):job.expected_total_bytes = expectedjob.bytes = resume_fromjob.download_path = job.download_path or job.dest- self._in_progress_path(job.download_path).rename(job.download_path)+ in_progress_path(job.download_path).rename(job.download_path)self._signal_job_started(job)self._signal_job_complete(job)return- job.resume_required = True- job.resume_message = "Resume refused by server. Restart required."- job.pause()- raise DownloadJobCancelledException("Resume refused by server. Restart required.")+ self._refuse_resume(job)if not resp.ok:host = urlparse(str(resp.url or url)).netlocstatus = resp.status_code@@ -555,10 +500,10 @@ class DownloadQueueService(DownloadQueueServiceBase):self._logger.error(f"Download failed from {host}: HTTP {status} {reason}")raise HTTPError(reason)- job.content_type = resp.headers.get("Content-Type")- job.etag = resp.headers.get("ETag") or job.etag- job.last_modified = resp.headers.get("Last-Modified") or job.last_modified- content_length = int(resp.headers.get("content-length", 0))+ if resume_from > 0 and resp.status_code == 200:+ # The server ignored Range, or If-Range found the file changed. This response's validators describe the+ # whole file it sends, not the partial on disk, so they must not be recorded for a later resume.+ self._refuse_resume(job)if job.dest.is_dir():parsed_url = urlparse(str(url))@@ -575,6 +520,11 @@ class DownloadQueueService(DownloadQueueServiceBase):raise ValueError(f"Cannot derive a safe filename for {url} from '{file_name}'")job.download_path = job.dest / file_name+ if resume_from > 0 and job.download_path != expected_path:+ # The range continues the named file, not the partial being resumed. Keep that partial's path so a+ # restart finds and removes it.+ job.download_path = expected_path+ self._refuse_resume(job)else:job.dest.parent.mkdir(parents=True, exist_ok=True)@@ -582,14 +532,12 @@ class DownloadQueueService(DownloadQueueServiceBase):assert job.download_path- in_progress_path = self._in_progress_path(job.download_path)+ job.content_type = resp.headers.get("Content-Type")+ job.etag = resp.headers.get("ETag") or job.etag+ job.last_modified = resp.headers.get("Last-Modified") or job.last_modified+ content_length = int(resp.headers.get("content-length", 0))- if resume_from > 0 and resp.status_code == 200:- # Server ignored Range. Restart download from scratch.- job.resume_required = True- job.resume_message = "Resume refused by server. Restart required."- job.pause()- raise DownloadJobCancelledException("Resume refused by server. Restart required.")+ partial_path = in_progress_path(job.download_path)if resume_from > 0 and resp.status_code == 206:content_range = resp.headers.get("Content-Range", "")@@ -665,7 +613,7 @@ class DownloadQueueService(DownloadQueueServiceBase):last_report_bytes = 0# DOWNLOAD LOOP- with open(in_progress_path, open_mode) as file:+ with open(partial_path, open_mode) as file:for data in resp.iter_content(chunk_size=DOWNLOAD_CHUNK_SIZE):if job.cancelled:raise DownloadJobCancelledException("Job was cancelled at caller's request")@@ -683,7 +631,16 @@ class DownloadQueueService(DownloadQueueServiceBase):# if we get here we are done and can rename the file to the original destself._logger.debug(f"{job.source}: saved to {job.download_path} (bytes={job.bytes})")- in_progress_path.rename(job.download_path)+ partial_path.rename(job.download_path)++ @staticmethod+ def _refuse_resume(job: DownloadJob) -> NoReturn:+ """Pause a job whose partial file the response cannot continue; the next attempt must start it over."""+ job.resume_required = True+ job.resume_refused = True+ job.resume_message = RESUME_REFUSED_MESSAGE+ job.pause()+ raise DownloadJobCancelledException(RESUME_REFUSED_MESSAGE)def _validate_url(self, url: str) -> None:"""Refuse to fetch URLs that point at addresses only the server can reach."""@@ -725,9 +682,6 @@ class DownloadQueueService(DownloadQueueServiceBase):return Falsereturn True- def _in_progress_path(self, path: Path) -> Path:- return path.with_name(path.name + ".downloading")-def _lookup_access_token(self, source: AnyHttpUrl) -> Optional[str]:# Pull the token from config if it exists and matches the URLtoken = None@@ -772,9 +726,9 @@ class DownloadQueueService(DownloadQueueServiceBase):if job.status not in [DownloadJobStatus.RUNNING, DownloadJobStatus.WAITING]:returnif job.download_path:- in_progress_path = self._in_progress_path(job.download_path)- if in_progress_path.exists():- job.bytes = in_progress_path.stat().st_size+ partial_path = in_progress_path(job.download_path)+ if partial_path.exists():+ job.bytes = partial_path.stat().st_sizejob.status = DownloadJobStatus.PAUSEDself._execute_cb(job, "on_cancelled")if self._event_bus:@@ -799,7 +753,7 @@ class DownloadQueueService(DownloadQueueServiceBase):self._logger.debug(f"Cleaning up leftover files from cancelled download job {job.download_path}")try:if job.download_path:- partial_file = self._in_progress_path(job.download_path)+ partial_file = in_progress_path(job.download_path)partial_file.unlink()except OSError as excp:self._logger.warning(excp)@@ -812,13 +766,16 @@ class DownloadQueueService(DownloadQueueServiceBase):with self._lock:mf_job = self._download_part2parent[download_job.id]if mf_job.waiting:- mf_job.total_bytes = sum(x.total_bytes for x in mf_job.download_parts)mf_job.status = DownloadJobStatus.RUNNINGassert download_job.download_path is not Nonepath_relative_to_destdir = download_job.download_path.relative_to(mf_job.dest)mf_job.download_path = (mf_job.dest / path_relative_to_destdir.parts[0]) # keep just the first component of the path+ if mf_job.running:+ # Every part start, not only the first, so the owner can record the part's validators and file name+ # while its partial file grows.+ mf_job.total_bytes = sum(x.total_bytes for x in mf_job.download_parts)self._execute_cb(mf_job, "on_start")def _mfd_progress(self, download_job: DownloadJob) -> None:diff --git a/invokeai/app/services/model_install/install_staging_ledger.py b/invokeai/app/services/model_install/install_staging_ledger.pyindex b9d7e37e7d..b3da969dd9 100644--- a/invokeai/app/services/model_install/install_staging_ledger.py+++ b/invokeai/app/services/model_install/install_staging_ledger.py@@ -39,7 +39,7 @@ from typing import Any, Callable, Iterable, Iterator, Optionalimport psutil-from invokeai.app.services.download import DownloadJob+from invokeai.app.services.download import RESUME_REFUSED_MESSAGE, DownloadJobfrom invokeai.app.services.model_install.model_install_common import (HFModelSource,InstallCancellationConflictError,@@ -204,6 +204,39 @@ def _write_marker(path: Path, marker: dict[str, Any], logger: logging.Logger) ->logger.warning(f"Could not sync install marker directory {path.parent}: {e}")+def part_resume_metadata(part: DownloadJob) -> dict[str, Any]:+ """A download part's marker entry: what a later download needs to find its partial file and validate it."""+ return {+ "url": str(part.source),+ "canonical_url": part.canonical_url,+ "etag": part.etag,+ "last_modified": part.last_modified,+ "expected_total_bytes": part.expected_total_bytes,+ "final_url": part.final_url,+ "download_path": part.download_path.as_posix() if part.download_path else None,+ "resume_required": part.resume_required,+ "resume_refused": part.resume_refused,+ "resume_message": part.resume_message,+ }+++def _restored_file_entry(entry: Any) -> Any:+ """A marker's per-file entry as restore reads it.++ Entries written before ``resume_refused`` existed record a refusal only in the message. Such a partial holds a+ revision the server would not continue, and may carry the refusing response's validator, so it must not resume.+ Every other entry is returned as written; a missing ``resume_refused`` reads as false.+ """+ if (+ isinstance(entry, dict)+ and "resume_refused" not in entry+ and entry.get("resume_required")+ and entry.get("resume_message") == RESUME_REFUSED_MESSAGE+ ):+ return {**entry, "resume_refused": True}+ return entry++def _remove_tree(path: Path, logger: logging.Logger) -> None:"""Remove a staging tree, retrying the file-handle races Windows reports as PermissionError.@@ -412,20 +445,7 @@ class InstallStaging:"""Write the staging directory's marker so a restart can resume the install."""if self._tmpdir is None:return- files: list[dict[str, Any]] = [- {- "url": str(part.source),- "canonical_url": part.canonical_url,- "etag": part.etag,- "last_modified": part.last_modified,- "expected_total_bytes": part.expected_total_bytes,- "final_url": part.final_url,- "download_path": part.download_path.as_posix() if part.download_path else None,- "resume_required": part.resume_required,- "resume_message": part.resume_message,- }- for part in download_parts- ]+ files = [part_resume_metadata(part) for part in download_parts]if not files and resume_files:files.extend(dict(metadata) for metadata in resume_files.values())marker: dict[str, Any] = {@@ -442,6 +462,14 @@ class InstallStaging:self._tmpdir.mkdir(parents=True, exist_ok=True)_write_marker(self._tmpdir / INSTALL_MARKER_FILENAME, marker, self._ledger._logger)+ def contains(self, path: Path) -> bool:+ """Whether path resolves inside the staging directory.++ A download path read back from a marker is untrusted: the models directory may have been moved or copied+ since the marker was written.+ """+ return self._tmpdir is not None and path.resolve().is_relative_to(self._tmpdir.resolve())+def delete_marker(self) -> None:"""Remove the marker once the install no longer needs a restart to resume it.@@ -772,7 +800,7 @@ class InstallStagingLedger:source=marker.get("source"),access_token=marker.get("access_token"),config_in=marker.get("config_in"),- files=marker.get("files") or [],+ files=[_restored_file_entry(entry) for entry in marker.get("files") or []],)def _read_marker(self, tmpdir: Path) -> Optional[dict[str, Any]]:diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.pyindex 038a7e2f14..64a0315d28 100644--- a/invokeai/app/services/model_install/model_install_default.py+++ b/invokeai/app/services/model_install/model_install_default.py@@ -25,9 +25,18 @@ from pydantic_core import Urlfrom requests import Sessionfrom invokeai.app.services.config import InvokeAIAppConfig-from invokeai.app.services.download import DownloadQueueServiceBase, MultiFileDownloadJob+from invokeai.app.services.download import (+ DownloadJob,+ DownloadQueueServiceBase,+ MultiFileDownloadJob,+ in_progress_path,+)from invokeai.app.services.invoker import Invoker-from invokeai.app.services.model_install.install_staging_ledger import InstallStaging, InstallStagingLedger+from invokeai.app.services.model_install.install_staging_ledger import (+ InstallStaging,+ InstallStagingLedger,+ part_resume_metadata,+)from invokeai.app.services.model_install.model_install_base import ModelInstallServiceBasefrom invokeai.app.services.model_install.model_install_common import (MODEL_SOURCE_TO_TYPE_MAP,@@ -101,6 +110,12 @@ _INSTALL_QUEUE_POLL_SECONDS = 1.0# First wait before retrying a move that hit a locked file; each further retry doubles it._MOVE_RETRY_DELAY_SECONDS = 0.5+_UNVALIDATED_PARTIAL_MESSAGE = (+ "The partial file could not be checked against the server's current file. Restarted download from the beginning."+)+_REFUSED_PARTIAL_MESSAGE = "The server refused to continue the partial file. Restarted download from the beginning."+_MISSING_PARTIAL_MESSAGE = "Partial file missing. Restarted download from the beginning."+def _combined_subfolder_name(subfolder_names: List[str]) -> str:combined = "_".join(subfolder_names)@@ -209,6 +224,13 @@ class ModelInstallService(ModelInstallServiceBase):staging.delete_marker()staging.discard()+ def _recorded_resume_metadata(self, job: ModelInstallJob) -> dict[str, dict[str, Any]]:+ """Each file's resume metadata as last recorded: by its part in this process, else by the install marker the+ job was restored from."""+ recorded = dict(job._resume_metadata or {})+ recorded.update((str(part.source), part_resume_metadata(part)) for part in job.download_parts)+ return recorded+def _restore_incomplete_installs(self) -> None:seen_sources: set[str] = set()# Collect sources already tracked by active jobs (including those being downloaded right now).@@ -277,8 +299,9 @@ class ModelInstallService(ModelInstallServiceBase):else:try:self._resume_remote_download(job)- except ModelMetadataUnavailableError as e:- self._logger.warning(f"Could not resume install {source_str} because metadata is unavailable: {e}")+ except (ModelMetadataUnavailableError, InstallDownloadConflictError) as e:+ # Unavailable metadata, or a partial file that must restart but is locked: keep it for a retry.+ self._logger.warning(f"Could not resume install {source_str}: {e}")job.status = InstallStatus.PAUSEDself._write_install_marker(job, status=InstallStatus.PAUSED)if self._stop_event.is_set():@@ -329,22 +352,6 @@ class ModelInstallService(ModelInstallServiceBase):self._begin_remote_download_operation(job)previous_status = job.statustry:- # Sources whose partial file has vanished. _enqueue_remote_download replaces job.download_parts- # with fresh parts, so the flag must be carried onto them or the resume response loses it.- restarted_from_scratch: set[str] = set()- if job.download_parts:- for part in job.download_parts:- if part.complete or part.bytes <= 0:- continue- if not part.download_path:- continue- in_progress_path = part.download_path.with_name(part.download_path.name + ".downloading")- if not in_progress_path.exists():- part.bytes = 0- part.resume_from_scratch = True- part.resume_message = "Partial file missing. Restarted download from the beginning."- restarted_from_scratch.add(str(part.source))- job.bytes = sum(p.bytes for p in job.download_parts)remote_files, metadata = self._remote_files_from_source(job.source)if not remote_files:raise RuntimeError("No remote files are available to download")@@ -359,8 +366,8 @@ class ModelInstallService(ModelInstallServiceBase):if isinstance(job.source, HFModelSource) and len(subfolders) <= 1else None,subfolders=subfolders if len(subfolders) > 1 else None,- resume_metadata=job._resume_metadata,- restarted_from_scratch=restarted_from_scratch,+ resume_metadata=self._recorded_resume_metadata(job),+ report_missing_partials=True,)except BaseException:job.status = previous_status@@ -1002,7 +1009,7 @@ class ModelInstallService(ModelInstallServiceBase):self._end_remote_download_operation(job)def restart_failed(self, job: ModelInstallJob) -> None:- """Restart failed or non-resumable downloads for a job."""+ """Restart failed or non-resumable downloads for a job, with every other file missing from staging."""if self._requires_recovery(job):raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")if not isinstance(job.source, (HFModelSource, URLModelSource)):@@ -1011,60 +1018,69 @@ class ModelInstallService(ModelInstallServiceBase):returnif not any(part.resume_required or part.errored for part in job.download_parts):return- sources_to_restart = {str(part.source) for part in job.download_parts if not part.complete}- if not sources_to_restart:- return- self._begin_remote_download_operation(job)- previous_status = job.status- try:- remote_files, metadata = self._remote_files_from_source(job.source)- remote_files = [rf for rf in remote_files if str(rf.url) in sources_to_restart]- if not remote_files:- raise RuntimeError("No remote files are available to download")- subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []- job.status = InstallStatus.WAITING- self._enqueue_remote_download(- job=job,- source=job.source,- remote_files=remote_files,- metadata=metadata,- subfolder=job.source.subfolder- if isinstance(job.source, HFModelSource) and len(subfolders) <= 1- else None,- subfolders=subfolders if len(subfolders) > 1 else None,- clear_partials=True,- )- except BaseException:- job.status = previous_status- raise- finally:- self._end_remote_download_operation(job)+ self._restart_remote_download(job, job.source)def restart_file(self, job: ModelInstallJob, file_source: str) -> None:- """Restart a specific file download for a job."""+ """Restart a specific file download for a job, with every other file missing from staging."""if self._requires_recovery(job):raise InstallRecoveryRequiredError("Cannot restart an install that requires recovery.")if not isinstance(job.source, (HFModelSource, URLModelSource)):return+ self._restart_remote_download(job, job.source, requested_file=file_source)++ def _restart_remote_download(+ self,+ job: ModelInstallJob,+ source: HFModelSource | URLModelSource,+ requested_file: Optional[str] = None,+ ) -> None:+ """Re-queue `requested_file` and every file of the source whose staged file is not on disk.++ Disk decides, not `job.download_parts`: a failed download deletes the whole staging tree, completed files+ included, and a previous restart leaves `download_parts` holding only the files it re-queued.++ Only the files being restarted lose their partial download: the requested file, or, without one, every part+ the backend could not resume; and any part that errored. Every other missing file resumes from its partial+ as `_enqueue_remote_download` allows.+ """self._begin_remote_download_operation(job)previous_status = job.statustry:- remote_files, metadata = self._remote_files_from_source(job.source)- remote_files = [rf for rf in remote_files if str(rf.url) == file_source]- if not remote_files:+ remote_files, metadata = self._remote_files_from_source(source)+ if requested_file is not None and all(str(rf.url) != requested_file for rf in remote_files):return- subfolders = job.source.subfolders if isinstance(job.source, HFModelSource) else []+ subfolders = source.subfolders if isinstance(source, HFModelSource) else []+ subfolder = source.subfolder if isinstance(source, HFModelSource) and len(subfolders) <= 1 else None+ subfolders_arg = subfolders if len(subfolders) > 1 else None+ destdir = self._staging_of(job).tmpdir+ assert destdir is not None, "a remote install downloads into its staging directory"+ staged_files = self._staged_remote_files(remote_files, subfolder, subfolders_arg)+ # A file is present only once the download renamed it from `.downloading`. A single-file URL source is+ # staged at "." until the response names its file, so it never counts as present.+ missing = [+ remote_file+ for remote_file, staged_file in zip(remote_files, staged_files, strict=True)+ if str(remote_file.url) == requested_file or not (destdir / staged_file.path).is_file()+ ]+ if not missing:+ raise RuntimeError("No remote files are available to download")+ restart_from_zero = {+ str(part.source)+ for part in job.download_parts+ if part.errored or (requested_file is None and part.resume_required)+ }+ if requested_file is not None:+ restart_from_zero.add(requested_file)job.status = InstallStatus.WAITINGself._enqueue_remote_download(job=job,- source=job.source,- remote_files=remote_files,+ source=source,+ remote_files=missing,metadata=metadata,- subfolder=job.source.subfolder- if isinstance(job.source, HFModelSource) and len(subfolders) <= 1- else None,- subfolders=subfolders if len(subfolders) > 1 else None,- clear_partials=True,+ subfolder=subfolder,+ subfolders=subfolders_arg,+ resume_metadata=self._recorded_resume_metadata(job),+ restart_from_zero=restart_from_zero,)except BaseException:job.status = previous_status@@ -1768,10 +1784,22 @@ class ModelInstallService(ModelInstallServiceBase):metadata: Optional[AnyModelRepoMetadata],subfolder: Optional[Path] = None,subfolders: Optional[List[Path]] = None,- resume_metadata: Optional[dict] = None,- clear_partials: bool = False,- restarted_from_scratch: Optional[set[str]] = None,+ resume_metadata: Optional[dict[str, dict[str, Any]]] = None,+ restart_from_zero: Optional[set[str]] = None,+ report_missing_partials: bool = False,) -> ModelInstallJob:+ """Queue the download of `remote_files` into `destdir` for `job`.++ `resume_metadata` maps each URL to what a previous download recorded for it (see `part_resume_metadata`).+ A part resumes its partial file only with a recorded validator, sent as If-Range: a server whose file changed+ sends the whole new revision instead, and the part pauses as restart-required rather than splicing the two.+ A partial without a validator, or one whose resume the server already refused, is deleted and its part+ reported as restarted from scratch. The URLs in `restart_from_zero` start over at the caller's request.++ With `report_missing_partials`, a part that had started (its recorded download path is set) but has neither a+ partial nor a finished file is reported as restarted from scratch too. A resume sets it; a restart after an+ error does not, as the error deleted the staging folder.+ """previous_source_metadata = job.source_metadataprevious_status = job.statusprevious_local_path = job.local_path@@ -1797,23 +1825,22 @@ class ModelInstallService(ModelInstallServiceBase):access_token=source.access_token or (hf_get_token() if isinstance(source, HFModelSource) else None),submit_job=False, # Important! Don't submit the job until we have set our _download_cache dict)- if resume_metadata:- for part in multifile_job.download_parts:- meta = resume_metadata.get(str(part.source))- if not meta:- continue- part.canonical_url = meta.get("canonical_url") or part.canonical_url- part.etag = meta.get("etag") or part.etag- part.last_modified = meta.get("last_modified") or part.last_modified- part.expected_total_bytes = meta.get("expected_total_bytes") or part.expected_total_bytes- part.final_url = meta.get("final_url") or part.final_url- if meta.get("download_path"):- part.download_path = Path(meta.get("download_path"))- if restarted_from_scratch:- for part in multifile_job.download_parts:- if str(part.source) in restarted_from_scratch:- part.resume_from_scratch = True- part.resume_message = "Partial file missing. Restarted download from the beginning."+ resume_metadata = resume_metadata or {}+ restart_from_zero = restart_from_zero or set()+ for part in multifile_job.download_parts:+ meta = resume_metadata.get(str(part.source))+ if not meta:+ continue+ part.canonical_url = meta.get("canonical_url") or part.canonical_url+ part.expected_total_bytes = meta.get("expected_total_bytes") or part.expected_total_bytes+ part.final_url = meta.get("final_url") or part.final_url+ if recorded_path := meta.get("download_path"):+ if staging.contains(Path(recorded_path)):+ part.download_path = Path(recorded_path)+ else:+ self._logger.warning(+ f"Ignoring recorded download path {recorded_path} outside the staging folder {destdir}"+ )with self._lock:if self._stop_event.is_set():raise InstallDownloadConflictError(@@ -1823,22 +1850,31 @@ class ModelInstallService(ModelInstallServiceBase):raise InstallDownloadConflictError("The install changed state before the download could be submitted; retry the operation.")- if clear_partials:- for part in multifile_job.download_parts:- target_path = part.dest- if target_path.exists():- try:- self._logger.info(f"Deleting partial file before restart: {target_path}")- target_path.unlink()- except Exception:- pass- in_progress_path = target_path.with_name(target_path.name + ".downloading")- if in_progress_path.exists():- try:- self._logger.info(f"Deleting partial file before restart: {in_progress_path}")- in_progress_path.unlink()- except Exception:- pass+ for part in multifile_job.download_parts:+ url = str(part.source)+ if url in restart_from_zero:+ self._discard_download(part)+ continue+ meta = resume_metadata.get(url) or {}+ if part.resumable_partial() is None:+ if report_missing_partials and meta.get("download_path") and self._download_vanished(part):+ part.resume_from_scratch = True+ part.resume_message = _MISSING_PARTIAL_MESSAGE+ continue+ part.etag = meta.get("etag")+ part.last_modified = meta.get("last_modified")+ part.resume_refused = bool(meta.get("resume_refused"))+ if part.may_resume_partial():+ continue+ self._discard_download(part)+ part.resume_from_scratch = True+ part.resume_message = (+ _REFUSED_PARTIAL_MESSAGE if part.resume_refused else _UNVALIDATED_PARTIAL_MESSAGE+ )+ # The partial is gone (a failed delete raised). A validator left on the part would report it as+ # missing.+ part.etag = part.last_modified = None+ part.resume_refused = Falsejob.source_metadata = metadatajob.local_path = destdirjob.total_bytes = sum((x.size or 0) for x in remote_files)@@ -1882,6 +1918,34 @@ class ModelInstallService(ModelInstallServiceBase):raisereturn job+ @staticmethod+ def _download_vanished(part: DownloadJob) -> bool:+ """Whether neither the finished file nor the partial file of a part is on disk."""+ path = part.expected_download_path()+ return path is not None and not path.exists() and not in_progress_path(path).exists()++ def _discard_download(self, part: DownloadJob) -> None:+ """Delete the final and partial file of a part that must start over, so its download finds neither.++ Raises `InstallDownloadConflictError` when one cannot be deleted (on Windows, while another process holds it+ open). The download would otherwise resume a partial meant to be dropped, with a Range request that no+ validator guards, and could splice two revisions of the file.+ """+ path = part.expected_download_path()+ if path is None:+ return+ for stale_path in (path, in_progress_path(path)):+ if not stale_path.is_file():+ continue+ self._logger.info(f"Deleting partial file before restart: {stale_path}")+ try:+ stale_path.unlink()+ except OSError as e:+ raise InstallDownloadConflictError(+ f"Could not delete {stale_path.name} to restart its download; retry once no other program is using "+ f"it: {e}"+ ) from e+def _stat_size(self, path: Path) -> int:size = 0if path.is_file():@@ -1900,6 +1964,27 @@ class ModelInstallService(ModelInstallServiceBase):access_token: Optional[str] = None,submit_job: bool = True,) -> MultiFileDownloadJob:+ return self._download_queue.multifile_download(+ parts=self._staged_remote_files(remote_files, subfolder, subfolders),+ dest=dest,+ access_token=access_token,+ submit_job=submit_job,+ on_start=self._download_started_callback,+ on_progress=self._download_progress_callback,+ on_complete=self._download_complete_callback,+ on_error=self._download_error_callback,+ on_cancelled=self._download_cancelled_callback,+ )++ @staticmethod+ def _staged_remote_files(+ remote_files: List[RemoteModelFile],+ subfolder: Optional[Path] = None,+ subfolders: Optional[List[Path]] = None,+ ) -> List[RemoteModelFile]:+ """Map each remote file, in order, to its path relative to the staging directory."""+ if not remote_files:+ return []# HuggingFace repo subfolders are a little tricky. If the name of the model is "sdxl-turbo", and# we are installing the "vae" subfolder, we do not want to create an additional folder level, such# as "sdxl-turbo/vae", nor do we want to put the contents of the vae folder directly into "sdxl-turbo".@@ -1969,18 +2054,7 @@ class ModelInstallService(ModelInstallServiceBase):for model_file in remote_files:assert model_file.size is not Noneparts.append(RemoteModelFile(url=model_file.url, path=model_file.path))-- return self._download_queue.multifile_download(- parts=parts,- dest=dest,- access_token=access_token,- submit_job=submit_job,- on_start=self._download_started_callback,- on_progress=self._download_progress_callback,- on_complete=self._download_complete_callback,- on_error=self._download_error_callback,- on_cancelled=self._download_cancelled_callback,- )+ return parts# ------------------------------------------------------------------# Callbacks are executed by the download queue in a separate thread@@ -1990,6 +2064,7 @@ class ModelInstallService(ModelInstallServiceBase):if install_job := self._download_cache.get(download_job.id, None):if install_job.cancelled or install_job.paused:return+ first_part = install_job.status != InstallStatus.DOWNLOADINGinstall_job.status = InstallStatus.DOWNLOADINGif install_job.local_path == self._staging_of(install_job).tmpdir: # first time@@ -2000,7 +2075,12 @@ class ModelInstallService(ModelInstallServiceBase):total_parts = sum(x.total_bytes for x in download_job.download_parts)if total_parts > 0:install_job.total_bytes = max(install_job.total_bytes or 0, total_parts)- self._signal_job_download_started(install_job)+ if first_part:+ self._signal_job_download_started(install_job)+ else:+ # Record the validators and file name of the part that just started, which a restore after a+ # crash needs to resume its partial file.+ self._write_install_marker(install_job, status=InstallStatus.DOWNLOADING)def _download_progress_callback(self, download_job: MultiFileDownloadJob) -> None:with self._lock:diff --git a/invokeai/app/services/shared/database/database.py b/invokeai/app/services/shared/database/database.pyindex ac75b61965..c43fda2d40 100644--- a/invokeai/app/services/shared/database/database.py+++ b/invokeai/app/services/shared/database/database.py@@ -56,6 +56,21 @@ def parse_database_url(url: str) -> URL:return parsed+# Query parameters PyMySQL takes as the password: SQLAlchemy passes the query on as connection arguments.+_PASSWORD_QUERY_KEYS = ("password", "passwd")+++def redacted_url(url: URL) -> str:+ """The URL as text for logs and the runtime config, with its password masked, also when the query carries it."""+ masked = [key for key in url.query if key in _PASSWORD_QUERY_KEYS]+ rest = url.difference_update_query(masked)+ text = rest.render_as_string(hide_password=True)+ # Appended rather than set in the query, which would percent-encode the mask.+ if masked:+ text += ("&" if rest.query else "?") + "&".join(f"{key}=***" for key in masked)+ return text++@dataclass(frozen=True)class SqliteConnection:"""The single connection of a SQLite database, the lock that serialises all work on it, and its file."""@@ -187,7 +202,7 @@ class Database:f"Unsupported database URL scheme '{parsed.drivername}', expected "f"{' or '.join(f'{backend}+{_SUPPORTED_SERVER_DRIVER}' for backend in SERVER_DIALECTS)}")- logger.info(f"Connecting to database {parsed.render_as_string(hide_password=True)}")+ logger.info(f"Connecting to database {redacted_url(parsed)}")try:engine = create_mysql_engine(parsed)except ModuleNotFoundError as e:diff --git a/invokeai/app/services/shared/database/startup.py b/invokeai/app/services/shared/database/startup.pyindex c724c8e21f..b8809d0e2a 100644--- a/invokeai/app/services/shared/database/startup.py+++ b/invokeai/app/services/shared/database/startup.py@@ -8,7 +8,7 @@ from sqlalchemy import inspectfrom invokeai.app.services.config.config_default import InvokeAIAppConfigfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBase-from invokeai.app.services.shared.database.database import Database, parse_database_url+from invokeai.app.services.shared.database.database import Database, parse_database_url, redacted_urlfrom invokeai.app.services.shared.sqlite_migrator.migration_loader import MigrationBuildContext, build_migrationsfrom invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import Migrator, NoImageFiles@@ -98,7 +98,7 @@ def redacted_database_url(url: Optional[str]) -> Optional[str]:if not url:return urltry:- return parse_database_url(url).render_as_string(hide_password=True)+ return redacted_url(parse_database_url(url))except ValueError:# Not a URL that could be opened either; show none of it.return "***"diff --git a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.pyindex beb9275042..dfbc6700da 100644--- a/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py+++ b/invokeai/app/services/shared/sqlite_migrator/sqlite_migrator_impl.py@@ -16,7 +16,7 @@ from sqlalchemy.exc import DBAPIErrorfrom invokeai.app.services.config.config_default import DefaultInvokeAIAppConfigfrom invokeai.app.services.image_files.image_files_base import ImageFileStorageBasefrom invokeai.app.services.shared.database.copy import copy_rows-from invokeai.app.services.shared.database.database import Database+from invokeai.app.services.shared.database.database import Database, redacted_urlfrom invokeai.app.services.shared.database.schema import metadatafrom invokeai.app.services.shared.database.schema.migrator import applied_migrations, migrationsfrom invokeai.app.services.shared.database.session_lock import SessionLock@@ -32,6 +32,9 @@ from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import# How long the migration of a server database waits for another process's migration of it to finish.MIGRATION_LOCK_TIMEOUT_SECONDS = 600+# How to go back to an older version after an update, and how to restore a backup. Named in the warning before an+# existing database is updated and in the error for a database a newer version updated.+UPGRADE_DOCS_URL = "https://v7.invoke.ai/start-here/upgrading/"class Migrator:@@ -81,7 +84,7 @@ class Migrator:if self._database.dialect_name != "sqlite":return self._run_server_migrations()cursor = self._database.sqlite.conn.cursor()- self._validate_existing_applied_migrations(cursor=cursor)+ self._refuse_unknown_applied_ids(self._get_applied_migration_ids(cursor=cursor))self._create_migrations_table(cursor=cursor)self._validate_existing_legacy_migrations(cursor=cursor)if self._needs_applied_migrations_bootstrap(cursor=cursor):@@ -103,6 +106,14 @@ class Migrator:self._logger.info("Database update needed")self._backup_db()+ # A file database that already had migrations, so not one created just now. Logged before the first+ # migration, so a migration that crashes the process still leaves it.+ if applied_migration_ids and self._backup_path is not None:+ self._logger.warning(+ f"Updating the database at {self._database.sqlite.path}. Older versions of InvokeAI cannot use it "+ f"after this update. Its current state is backed up to {self._backup_path}; to go back to an older "+ f"version, restore that backup (see {UPGRADE_DOCS_URL})."+ )for migration in migration_plan:self._run_migration(migration)@@ -226,7 +237,9 @@ class Migrator:migration_id = f"migration_{legacy_version}"if migration_id not in registered_migration_ids:cursor.connection.rollback()- raise MigrationError(f"Database contains unknown legacy migration version: {legacy_version}")+ raise self._newer_database_error(+ f"Database contains unknown legacy migration version: {legacy_version}"+ )cursor.execute("SELECT legacy_version FROM applied_migrations WHERE migration_id = ?;",(migration_id,),@@ -261,16 +274,30 @@ class Migrator:cursor.connection.rollback()raise MigrationError(msg) from e- def _validate_existing_applied_migrations(self, cursor: sqlite3.Cursor) -> None:- """Validates existing applied migration IDs before creating or mutating migrator metadata."""- applied_migration_ids = self._get_applied_migration_ids(cursor=cursor)- if len(applied_migration_ids) == 0:- return- known_migration_ids = set(self._migration_set.migrations_by_id)- unknown_applied_ids = applied_migration_ids - known_migration_ids+ def _refuse_unknown_applied_ids(self, applied_migration_ids: set[str]) -> None:+ """Refuses a database that has had a migration this version does not know, before anything changes it."""+ unknown_applied_ids = applied_migration_ids - set(self._migration_set.migrations_by_id)if unknown_applied_ids:unknown_ids = ", ".join(sorted(unknown_applied_ids))- raise MigrationError(f"Database contains unknown applied migration IDs: {unknown_ids}")+ raise self._newer_database_error(f"Database contains unknown applied migration IDs: {unknown_ids}")++ def _newer_database_error(self, problem: str) -> MigrationError:+ """The error for a database that a newer version of InvokeAI updated, with the ways back to a version this+ one can run. It names where the backups are, not one of them: the newest is usually not the one to restore+ for an older version, and the restore steps explain which is."""+ if self._database.dialect_name != "sqlite":+ restore = ", or restore the backup you made before upgrading (InvokeAI does not back up server databases)"+ elif (db_path := self._database.sqlite.path) is not None:+ restore = (+ f", or restore a backup made before the update: InvokeAI writes one to {db_path.parent} as "+ f"{db_path.stem}_backup_<date>-<time>.db each time it updates the database"+ )+ else:+ restore = ""+ return MigrationError(+ f"{problem}. This database was updated by a newer version of InvokeAI. Run that version{restore}. "+ f"Restore steps: {UPGRADE_DOCS_URL}"+ )def _validate_existing_legacy_migrations(self, cursor: sqlite3.Cursor) -> None:"""Validates existing legacy migration versions before creating applied migration metadata."""@@ -286,7 +313,9 @@ class Migrator:legacy_version = row[0]migration_id = f"migration_{legacy_version}"if migration_id not in registered_migration_ids:- raise MigrationError(f"Database contains unknown legacy migration version: {legacy_version}")+ raise self._newer_database_error(+ f"Database contains unknown legacy migration version: {legacy_version}"+ )def _validate_existing_applied_legacy_migrations(self, cursor: sqlite3.Cursor) -> None:"""Validates applied IDs for legacy migrations against legacy numeric rows."""@@ -440,12 +469,13 @@ class Migrator:no records, which the app refuses as well."""if self._database.dialect_name != "sqlite" and self._server_has_tables():applied_ids = self._server_applied_migration_ids()- return bool(self._migration_set.get_migration_plan(applied_migration_ids=applied_ids))- with self._database.begin(write=False) as conn:- if not inspect(conn).has_table(applied_migrations.name):- return self._migration_set.count > 0- applied = set(conn.execute(select(applied_migrations.c.migration_id)).scalars())- return bool(self._migration_set.get_migration_plan(applied_migration_ids=applied))+ else:+ with self._database.begin(write=False) as conn:+ if not inspect(conn).has_table(applied_migrations.name):+ return self._migration_set.count > 0+ applied_ids = set(conn.execute(select(applied_migrations.c.migration_id)).scalars())+ self._refuse_unknown_applied_ids(applied_ids)+ return bool(self._migration_set.get_migration_plan(applied_migration_ids=applied_ids))def _run_server_migrations(self) -> bool:with self._server_migration_lock() as lock:@@ -453,7 +483,9 @@ class Migrator:if not self._server_has_tables():self._bootstrap()bootstrapped = True- plan = self._migration_set.get_migration_plan(applied_migration_ids=self._server_applied_migration_ids())+ applied_ids = self._server_applied_migration_ids()+ self._refuse_unknown_applied_ids(applied_ids)+ plan = self._migration_set.get_migration_plan(applied_migration_ids=applied_ids)portable: list[PortableMigration] = []for migration in plan:if not isinstance(migration, PortableMigration):@@ -464,6 +496,13 @@ class Migrator:portable.append(migration)if portable:self._logger.info("Database update needed")+ if not bootstrapped:+ url = redacted_url(self._database.engine.url)+ self._logger.warning(+ f"Updating the database {url}. Older versions of InvokeAI cannot use it after this update, "+ "and InvokeAI makes no backup of a server database: to go back to an older version, restore "+ f"the backup you made before upgrading (see {UPGRADE_DOCS_URL})."+ )for migration in portable:lock.verify()self._run_portable_migration(migration)diff --git a/invokeai/backend/minimax_h3/sampling.py b/invokeai/backend/minimax_h3/sampling.pyindex db6ccbc490..37ea971433 100644--- a/invokeai/backend/minimax_h3/sampling.py+++ b/invokeai/backend/minimax_h3/sampling.py@@ -142,6 +142,8 @@ class MiniMaxH3DenoiseState:audio_rows: torch.Tensor"""Channel-major audio rows. Shape (A, 32), float32."""position_ids: torch.Tensor+ """Rope coordinates `(t, h, w)` per packed row. Shape (L, 3), float32: the layout keeps them in float64 on CPU,+ but MPS has no float64 and the rope casts to float32 first, so casting before the transfer is bit-identical."""token_tags: torch.Tensorvideo_indices: torch.Tensoraudio_indices: torch.Tensor@@ -249,7 +251,7 @@ def build_denoise_state(layout=layout,video_rows=video_rows,audio_rows=audio_rows,- position_ids=layout.position_ids.to(device),+ position_ids=layout.position_ids.to(device=device, dtype=torch.float32),token_tags=layout.token_tags.to(device),video_indices=layout.video_indices.to(device),audio_indices=layout.audio_indices.to(device),@@ -411,7 +413,7 @@ def build_ref2va_denoise_state(layout=layout,video_rows=video_rows,audio_rows=audio_rows,- position_ids=layout.position_ids.to(device),+ position_ids=layout.position_ids.to(device=device, dtype=torch.float32),token_tags=layout.token_tags.to(device),video_indices=layout.video_indices.to(device),audio_indices=layout.audio_indices.to(device),diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex ce2ae1a6bd..24bd51ec87 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -32996,10 +32996,16 @@"title": "Resume Message","description": "Message explaining why resume is required"},+ "resume_refused": {+ "type": "boolean",+ "title": "Resume Refused",+ "description": "True if the server refused to continue the partial file, so it must restart from the beginning",+ "default": false+ },"resume_from_scratch": {"type": "boolean","title": "Resume From Scratch",- "description": "True if resume metadata existed but the partial file was missing and the download restarted from the beginning",+ "description": "True if the download restarted from the beginning instead of resuming: its partial file was missing, or could not be checked against the server's current file (no recorded validator, or the server had refused to resume it) and was discarded","default": false}},diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 7ae04149f3..49c0e64c1e 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -12146,9 +12146,15 @@ export type components = {* @description Message explaining why resume is required*/resume_message?: string | null;+ /**+ * Resume Refused+ * @description True if the server refused to continue the partial file, so it must restart from the beginning+ * @default false+ */+ resume_refused?: boolean;/*** Resume From Scratch- * @description True if resume metadata existed but the partial file was missing and the download restarted from the beginning+ * @description True if the download restarted from the beginning instead of resuming: its partial file was missing, or could not be checked against the server's current file (no recorded validator, or the server had refused to resume it) and was discarded* @default false*/resume_from_scratch?: boolean;diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 9f85084f98..be67df269e 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,15 +2,15 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 800593,+ "brotliBytes": 802380,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 799703,+ "gzipBytes": 801520,"imageRawBytes": 44398,- "initialRawBytes": 2061277,- "largestAssetRawBytes": 752413,+ "initialRawBytes": 2066324,+ "largestAssetRawBytes": 752422,"otherAssetRawBytes": 0,- "ownedRawBytes": 99011,+ "ownedRawBytes": 101787,"requestCount": 35,"scriptRequestCount": 19,"sourceOwners": [@@ -179,6 +179,7 @@"source:src/features/nodes/data/transport.ts","source:src/features/nodes/index.ts","source:src/features/nodes/ui/NodesPage.tsx",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -349,15 +350,15 @@},"editor": {"baseline": {- "brotliBytes": 1197162,+ "brotliBytes": 1201065,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1190526,+ "gzipBytes": 1194189,"imageRawBytes": 44398,- "initialRawBytes": 3293139,- "largestAssetRawBytes": 752413,+ "initialRawBytes": 3306361,+ "largestAssetRawBytes": 752422,"otherAssetRawBytes": 0,- "ownedRawBytes": 155635,+ "ownedRawBytes": 155629,"requestCount": 71,"scriptRequestCount": 55,"sourceOwners": [@@ -714,6 +715,7 @@"source:src/features/workflow/ui/workflowUiStore.ts","source:src/features/workflow/utility.ts","source:src/features/workflow/widget.ts",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -965,6 +967,7 @@"source:src/workbench/projects/projectHydration.ts","source:src/workbench/projects/projectLifecycleLocks.ts","source:src/workbench/projects/projectLoadRefusal.ts",+ "source:src/workbench/projects/projectMediaUrls.ts","source:src/workbench/projects/projectTabsA11y.ts","source:src/workbench/projects/session.ts","source:src/workbench/projects/syncStore.ts",@@ -1105,7 +1108,7 @@"source": "src/app/WorkbenchApp.tsx"}},- "capturedAt": "2026-10-18",+ "capturedAt": "2026-10-20","developmentInvalidation": {"platformUiBarrel": {"specifier": "@platform/ui",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 002ee7bca7..17b61cdd7e 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -162,9 +162,9 @@"largestAssetRawBytes": 305523,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 518622,+ "scriptRawBytes": 524052,"scriptRequestCount": 9,- "totalRawBytes": 518622+ "totalRawBytes": 524052},"domContentLoadedMedianMs": 100.40000009536743,"id": "editor-canvas",@@ -200,9 +200,9 @@"largestAssetRawBytes": 305523,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 518622,+ "scriptRawBytes": 524052,"scriptRequestCount": 9,- "totalRawBytes": 518622+ "totalRawBytes": 524052},"domContentLoadedMedianMs": 97.7000002861023,"id": "editor-canvas",@@ -592,6 +592,7 @@"source:src/features/queue/data/submissionApi.ts","source:src/features/queue/launchpad.ts","source:src/features/queue/ui/launchpad/QueueStatusBand.tsx",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -1255,6 +1256,7 @@"source:src/features/workflow/ui/workflowUiStore.ts","source:src/features/workflow/utility.ts","source:src/features/workflow/widget.ts",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -1674,6 +1676,7 @@"source:src/workbench/projects/projectHydration.ts","source:src/workbench/projects/projectLifecycleLocks.ts","source:src/workbench/projects/projectLoadRefusal.ts",+ "source:src/workbench/projects/projectMediaUrls.ts","source:src/workbench/projects/projectTabsA11y.ts","source:src/workbench/projects/session.ts","source:src/workbench/projects/syncStore.ts",@@ -2356,6 +2359,7 @@"source:src/features/workflow/ui/workflowUiStore.ts","source:src/features/workflow/utility.ts","source:src/features/workflow/widget.ts",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -2784,6 +2788,7 @@"source:src/workbench/projects/projectHydration.ts","source:src/workbench/projects/projectLifecycleLocks.ts","source:src/workbench/projects/projectLoadRefusal.ts",+ "source:src/workbench/projects/projectMediaUrls.ts","source:src/workbench/projects/projectTabsA11y.ts","source:src/workbench/projects/session.ts","source:src/workbench/projects/syncStore.ts",@@ -3687,6 +3692,7 @@"source:src/features/workflow/ui/workflowUiStore.ts","source:src/features/workflow/utility.ts","source:src/features/workflow/widget.ts",+ "source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts",@@ -4107,6 +4113,7 @@"source:src/workbench/projects/projectHydration.ts","source:src/workbench/projects/projectLifecycleLocks.ts","source:src/workbench/projects/projectLoadRefusal.ts",+ "source:src/workbench/projects/projectMediaUrls.ts","source:src/workbench/projects/projectTabsA11y.ts","source:src/workbench/projects/session.ts","source:src/workbench/projects/syncStore.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 9cd223302e..0b3d4377f4 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -206,6 +206,7 @@"crop": "Crop","clipboardBlocked": "Clipboard access was blocked by the browser.","couldNotCopy": "Could not copy",+ "copyUnavailable": "Copying needs HTTPS or localhost","countOfTotal": "{{count}} of {{total}}","created": "Created","delete": "Delete",@@ -236,6 +237,7 @@"open": "Open","pageNumber": "Page {{page}}","pages": "Pages",+ "pasteUnavailable": "Pasting needs HTTPS or localhost","plusMore": " +{{count}} more","previousPage": "Previous page","prompt": "Prompt",@@ -1870,6 +1872,12 @@},"copyFailed": "Could not copy browser setting","copySetting": "Copy browser setting",+ "dismiss": "Dismiss",+ "plainHttpLimits": {+ "description": "Invoke is open over plain HTTP from a network address, so your browser turns off clipboard access and the feature Invoke uses to coordinate open tabs. Deleting a project and resolving a save conflict still work, in this tab only: keep Invoke open in one tab while you do them. Discarding queue recovery data stays off, because Invoke cannot confirm that no other tab is still running those queue runs.",+ "title": "Some features are limited on this address",+ "workaround": "To turn these back on, open Invoke at localhost on the computer running it, or serve it over HTTPS."+ },"settingCopied": "Browser setting copied"},"connection": {@@ -2274,7 +2282,7 @@"export": "Export recovery","loading": "Looking for queue recovery data…","lockContended": "This project's queue recovery is active in another tab. Close that tab or wait for its runs to finish.",- "lockUnavailable": "Queue recovery cannot be discarded because cross-tab coordination is unavailable.",+ "lockUnavailable": "Queue recovery data can't be discarded here: Invoke can't coordinate with other tabs, so it can't confirm that none is still running this project's queue. Export it, or open Invoke at localhost or over HTTPS to discard it.","next": "Next","open": "Open project","openFailed": "The project could not be opened. Its local queue recovery data is still available.",diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex da91af29dd..4da577bc72 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -22,6 +22,11 @@ import { killPreview, spawnPreview } from './preview-server.mjs';const root = resolve(import.meta.dirname, '..');const port = Number(process.env.INVOKEAI_PROJECT_FILE_PORT ?? 4180);const origin = `http://127.0.0.1:${String(port)}`;+/** The same preview at a second origin, as a project saved at `origin` is opened from elsewhere. */+const secondOrigin = `http://localhost:${String(port)}`;+/** A plain-HTTP origin that is not a secure context, as another computer on the LAN reaches Invoke. */+const plainHttpHost = 'lan.test';+const plainHttpOrigin = `http://${plainHttpHost}:${String(port)}`;const backendPort = Number(process.env.INVOKEAI_PROJECT_FILE_BACKEND_PORT ?? 4181);const backendOrigin = `http://127.0.0.1:${String(backendPort)}`;const sourceProjectId = 'fixture-project-002';@@ -252,6 +257,22 @@ const waitForSavedWorkflows = async (projectId, predicate, label) => {throw new Error(`The project record never reached the expected state: ${label}.`);};+/** Rename the active workflow through the Workflows dialog. */+const renameActiveWorkflow = async (page, name) => {+ const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });+ const renameDialog = page.getByRole('dialog', { exact: true, name: 'Rename workflow' });++ await page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / }).click();+ await dialog.locator('[data-library-tab="project"]').waitFor();+ await dialog+ .locator('[data-project-workflow-detail]')+ .getByRole('button', { exact: true, name: 'More actions' })+ .click();+ await page.getByRole('menuitem', { name: /^Rename…/ }).click();+ await renameDialog.getByRole('textbox').fill(name);+ await renameDialog.getByRole('button', { exact: true, name: 'Rename' }).click();+};+/** Import the archive at `archivePath` through the Launchpad, exactly as a person would. */const importArchive = async ({ archivePath, browser, contexts, errors, phase }) => {const context = await browser.newContext();@@ -487,6 +508,8 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectoryawait runDuplication({ browser, contexts, errors, imported, importedBoardNames });await runWorkflowCollection({ browser, contexts, errors, imported });await runUnloadRecovery({ browser, contexts, errors, imported });+ await runSecondOrigin({ browser, contexts, errors, imported, importedBoardNames });+ await runPlainHttp({ browser, contexts, errors });await runMissingBinaryImport({ browser, contexts, entries, errors, tempDirectory });return {@@ -788,17 +811,7 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {await main.waitFor();await selectLayoutPreset(page, 'Automate', 'Workflow');};- const rename = async (name) => {- await workflowName.click();- await dialog.locator('[data-library-tab="project"]').waitFor();- await dialog- .locator('[data-project-workflow-detail]')- .getByRole('button', { exact: true, name: 'More actions' })- .click();- await page.getByRole('menuitem', { name: /^Rename…/ }).click();- await renameDialog.getByRole('textbox').fill(name);- await renameDialog.getByRole('button', { exact: true, name: 'Rename' }).click();- };+ const rename = (name) => renameActiveWorkflow(page, name);// Navigating away: browser recovery holds the edit before any editor loads again. Saves to the server are held,// so it is there only through the journal written while the page unloaded, or through an autosave's local stage.@@ -837,6 +850,238 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {assertNoBrowserErrors(errors);};+const imageUrls = (base, imageName) => ({+ full: `${base}/api/v1/images/i/${encodeURIComponent(imageName)}/full`,+ thumbnail: `${base}/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`,+});++const generatedImage = (base, imageName) => ({+ height: 64,+ imageName,+ imageUrl: imageUrls(base, imageName).full,+ queuedAt: '2026-10-19T00:00:00.000Z',+ sourceQueueItemId: 'journey-queue-item',+ thumbnailUrl: imageUrls(base, imageName).thumbnail,+ width: 64,+});++const regionalLayerWithReference = (image) => ({+ autoNegative: false,+ blendMode: 'normal',+ id: 'journey-regional',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#7c3aed', style: 'solid' } },+ name: 'Journey region',+ negativePrompt: null,+ opacity: 0.5,+ positivePrompt: null,+ referenceImages: [+ {+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image,+ method: 'full',+ model: null,+ type: 'ip_adapter',+ weight: 1,+ },+ id: 'journey-reference',+ isEnabled: true,+ },+ ],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+});++/**+ * Store a media URL everywhere a project keeps one (gallery selection, compare and recents; a staging candidate; a+ * regional reference image), each naming `base`, exactly as a page at `base` saves them.+ */+const seedMediaUrls = async (projectId, base, [selected, compare, recent, staged, reference]) => {+ const record = await getProjectRecord(projectId);+ const data = structuredClone(record.data);+ const workspace = structuredClone(record.workspace.data);+ const gallery = Object.values(workspace.widgetInstances).find((instance) => instance.typeId === 'gallery');++ gallery.state.values = {+ ...gallery.state.values,+ compareImage: generatedImage(base, compare),+ recentImages: [generatedImage(base, recent)],+ selectedImage: {+ boardId: record.board_id,+ category: 'general',+ createdAt: '2026-10-19T00:00:00.000Z',+ fullUrl: imageUrls(base, selected).full,+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name: selected,+ starred: false,+ thumbnailUrl: imageUrls(base, selected).thumbnail,+ width: 64,+ },+ };+ workspace.canvas.stagingArea = {+ ...workspace.canvas.stagingArea,+ isVisible: true,+ pendingImages: [{ ...generatedImage(base, staged), placement: { height: 64, opacity: 1, width: 64, x: 0, y: 0 } }],+ };+ data.canvas.document.stacks.regional_guidance.unshift(regionalLayerWithReference(generatedImage(base, reference)));++ return fetchJson(`/api/v1/projects/${encodeURIComponent(projectId)}`, {+ body: JSON.stringify({+ data,+ expected_revision: record.revision,+ // As the build reads them: the split content needs document schema 4.+ max_document_schema_version: record.minimum_document_schema_version,+ name: record.name,+ workspace: { data: workspace, expected_revision: record.workspace.revision },+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'PUT',+ });+};++/**+ * A project saved at one origin opens at another (another computer, or `localhost` after `127.0.0.1`) with every+ * stored media URL rebuilt for the origin it opens at: nothing is requested from the first, which is out of reach, and+ * opening saves nothing. The next edits save the second origin's URLs.+ */+const runSecondOrigin = async ({ browser, contexts, errors, imported, importedBoardNames }) => {+ const imageNames = importedBoardNames.filter((name) => name.endsWith('.png'));+ const seeded = Array.from({ length: 5 }, (_, index) => imageNames[index % imageNames.length]);++ await seedMediaUrls(imported.project_id, origin, seeded);+ const opened = await getProjectRecord(imported.project_id);+ const context = await browser.newContext();++ contexts.add(context);+ // The origin that saved the project is another machine as far as this page is concerned.+ await context.route(`${origin}/**`, (route) => route.abort());+ const page = await context.newPage();+ const requests = [];++ page.on('request', (request) => requests.push({ method: request.method(), url: request.url() }));+ observeBrowserErrors(page, 'second origin', errors);+ await page.goto(`${secondOrigin}/#/app?project=${encodeURIComponent(imported.project_id)}`, {+ waitUntil: 'domcontentloaded',+ });+ await page.getByRole('main', { exact: true, name: opened.name }).waitFor();+ // Past autosave's debounce: a heal that saved by itself would have sent it by now.+ await delay(2_000);++ const projectWrites = () =>+ requests.filter(({ method, url }) => method !== 'GET' && new URL(url).pathname.startsWith('/api/v1/projects/'));++ assert.deepEqual(projectWrites(), [], 'opening the project at another origin saved it');+ const unchanged = await getProjectRecord(imported.project_id);+ assert.equal(unchanged.revision, opened.revision);+ assert.equal(unchanged.workspace.revision, opened.workspace.revision);++ // One edit in each half: the workflow's name is content, the layout preset is the caller's workspace.+ await selectLayoutPreset(page, 'Automate', 'Workflow');+ await renameActiveWorkflow(page, 'Second origin');+ await page.keyboard.press('Escape');+ await selectLayoutPreset(page, 'Compose', 'Preview');+ // Preview shows the selection, from this origin.+ const selectedUrl = imageUrls(secondOrigin, seeded[0]).full;+ const deadline = Date.now() + 10_000;++ while (!requests.some(({ url }) => url === selectedUrl) && Date.now() < deadline) {+ await delay(100);+ }+ assert.ok(+ requests.some(({ url }) => url === selectedUrl),+ 'Preview did not request the selection from this origin'+ );+ const saved = await waitForSavedWorkflows(+ imported.project_id,+ (record) =>+ record.revision > opened.revision &&+ record.workspace.revision > opened.workspace.revision &&+ getWorkflowDocuments(record).some((document) => document.name === 'Second origin'),+ 'edits saved from the second origin'+ );+ const savedJson = JSON.stringify([saved.data, saved.workspace.data]);++ assert.equal(savedJson.includes(origin), false, 'a saved media URL still names the origin that first saved it');+ for (const name of new Set(seeded)) {+ assert.ok(savedJson.includes(imageUrls(secondOrigin, name).full), `${name} was not saved with this origin's URL`);+ }+ assert.deepEqual(+ requests.filter(({ url }) => url.startsWith(`${origin}/`)),+ [],+ 'the page requested media from the origin that saved the project'+ );++ await context.close();+ contexts.delete(context);+ assertNoBrowserErrors(errors);+};++/**+ * Over plain HTTP from a network address the page is not a secure context: no Web Locks, no clipboard. The Launchpad+ * says so until dismissed, delete still works in this tab, and copy controls stay visible but disabled with a reason.+ */+const runPlainHttp = async ({ browser, contexts, errors }) => {+ const context = await browser.newContext();++ contexts.add(context);+ const page = await context.newPage();++ observeBrowserErrors(page, 'plain HTTP', errors);+ await page.goto(`${plainHttpOrigin}/#/projects`, { waitUntil: 'domcontentloaded' });+ assert.equal(await page.evaluate(() => window.isSecureContext), false);++ const notice = page.getByRole('status').filter({ hasText: 'Some features are limited on this address' });++ await notice.waitFor();++ // Delete runs in this tab alone; the server fences every write that could conflict with it.+ const doomed = `${sourceProjectName} copy`;+ const doomedProject = (await fetchJson('/api/v1/projects/')).find((project) => project.name === doomed);++ assert.ok(doomedProject, `${doomed} must exist before the plain-HTTP delete.`);+ const card = page.getByRole('link', { exact: true, name: `Open ${doomed}` }).first();++ await card.click({ button: 'right' });+ await page.getByRole('menuitem', { exact: true, name: 'Delete…' }).click();+ const deleted = page.waitForRequest((request) => request.method() === 'DELETE');++ await page.getByRole('button', { exact: true, name: 'Delete project' }).click();+ assert.equal(new URL((await deleted).url()).pathname, `/api/v1/projects/${doomedProject.project_id}`);+ await page.getByRole('link', { exact: true, name: `Open ${doomed}` }).waitFor({ state: 'detached' });+ assert.equal(+ (await fetchJson('/api/v1/projects/')).some((project) => project.project_id === doomedProject.project_id),+ false+ );++ // Dismissed, the notice stays dismissed on this origin.+ await notice.getByRole('button', { exact: true, name: 'Dismiss' }).click();+ await notice.waitFor({ state: 'detached' });+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page+ .getByRole('link', { exact: true, name: `Open ${sourceProjectName}` })+ .first()+ .waitFor();+ assert.equal(await notice.count(), 0, 'the dismissed notice came back after a reload');++ // Copy controls stay, disabled, and say why.+ await page.getByRole('link', { exact: true, name: 'Nodes' }).click();+ const copyPath = page.getByRole('button', { exact: true, name: 'Copy path' });++ await copyPath.waitFor();+ assert.equal(await copyPath.getAttribute('aria-disabled'), 'true');+ await copyPath.hover();+ await page.getByRole('tooltip').filter({ hasText: 'Copying needs HTTPS or localhost' }).waitFor();++ await context.close();+ contexts.delete(context);+ assertNoBrowserErrors(errors);+};+/** Count missing board media separately from missing document references. */const runMissingBinaryImport = async ({ browser, contexts, entries, errors, tempDirectory }) => {const damagedPath = await writeArchiveWithout(@@ -884,14 +1129,21 @@ const withTimeout = async (run, durationMs, label) => {const getDefaultDependencies = () => ({createTempDirectory: () => mkdtemp(join(tmpdir(), 'invokeai-project-file-journey-')),killPreview,- launchBrowser: ({ timeoutMs }) => chromium.launch({ headless: true, timeout: timeoutMs }),+ launchBrowser: ({ timeoutMs }) =>+ chromium.launch({+ // `lan.test` reaches the preview without being a secure context; `localhost` is pinned to the address the+ // preview binds, where a runner resolving it to `::1` first would find nothing.+ args: [`--host-resolver-rules=MAP ${plainHttpHost} 127.0.0.1, MAP localhost 127.0.0.1`],+ headless: true,+ timeout: timeoutMs,+ }),now: () => performance.now(),removeTempDirectory: (directory) => rm(directory, { force: true, recursive: true }),runRoundTrip,spawnPreview: () =>spawnPreview({cwd: root,- env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin },+ env: { ...process.env, INVOKEAI_DEV_BACKEND: backendOrigin, INVOKEAI_DEV_HOSTS: plainHttpHost },port,stdio: ['ignore', 'ignore', 'pipe'],}),diff --git a/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts b/invokeai/frontend/webv2/src/architecture/secureContextApis.test.tsindex 52b814e0e6..0e232fe20b 100644--- a/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts+++ b/invokeai/frontend/webv2/src/architecture/secureContextApis.test.ts@@ -1,23 +1,81 @@import { describe, expect, it } from 'vitest';-/** Guard secure-context APIs: randomUUID and subtle are unavailable over insecure HTTP. */+/**+ * Guard secure-context APIs. Browsers expose them only over HTTPS or on localhost, so on a plain-HTTP origin (another+ * computer on the LAN) each is missing; one platform helper per API decides what happens then, and every other+ * production module goes through it.+ */const sources = import.meta.glob('../**/*.{ts,tsx}', {eager: true,import: 'default',query: '?raw',}) as Record<string, string>;-const HELPER_PATHS = new Set(['../platform/browser/randomUuid.ts', '../platform/browser/sha256.ts']);-const SECURE_CONTEXT_ONLY = /\brandomUUID\b|\bcrypto\s*\.\s*subtle\b|\bsubtle\s*\.\s*digest\b/;const isTestFile = (path: string): boolean => /\.(test|spec|stories)\.tsx?$/.test(path);+/** `navigator.x` or `navigator?.x`, whatever the spacing. */+const navigatorMember = (member: string): RegExp => new RegExp(String.raw`\bnavigator\s*\??\.\s*${member}\b`);++const RULES = [+ {+ allowed: ['../platform/browser/randomUuid.ts', '../platform/browser/sha256.ts'],+ name: 'randomUUID and SubtleCrypto',+ pattern: /\brandomUUID\b|\bcrypto\s*\??\.\s*subtle\b|\bsubtle\s*\??\.\s*digest\b/,+ },+ { allowed: ['../platform/browser/webLocks.ts'], name: 'navigator.locks', pattern: navigatorMember('locks') },+ {+ allowed: ['../platform/browser/clipboard.ts'],+ name: 'navigator.clipboard and runtime ClipboardItem',+ // Type-only `ClipboardItem` references stay allowed; constructing or reading the global does not.+ pattern: new RegExp(+ [+ navigatorMember('clipboard').source,+ String.raw`\bnew\s+ClipboardItem\b`,+ String.raw`\b(?:globalThis|window|self)\s*\??\.\s*ClipboardItem\b`,+ String.raw`\bClipboardItem\s*\??\.\s*\w`,+ ].join('|')+ ),+ },+ {+ allowed: ['../platform/pwa/registerServiceWorker.ts'],+ name: 'navigator.serviceWorker',+ pattern: navigatorMember('serviceWorker'),+ },+ // Unused today: a helper that needs it is added here on purpose.+ { allowed: [], name: 'navigator.storage', pattern: navigatorMember('storage') },+] as const satisfies readonly { allowed: readonly string[]; name: string; pattern: RegExp }[];+describe('secure-context web APIs', () => {- it('routes every production UUID mint and SHA-256 digest through the platform helpers', () => {- const offenders = Object.entries(sources)- .filter(([path]) => !HELPER_PATHS.has(path) && !isTestFile(path))- .filter(([, text]) => SECURE_CONTEXT_ONLY.test(text))- .map(([path]) => path.replace(/^\.\.\//, ''));+ it('routes every production use of a secure-context API through its platform helper', () => {+ const offenders = Object.fromEntries(+ RULES.map(({ allowed, name, pattern }) => [+ name,+ Object.entries(sources)+ .filter(+ ([path, text]) => !isTestFile(path) && !(allowed as readonly string[]).includes(path) && pattern.test(text)+ )+ .map(([path]) => path.replace(/^\.\.\//, '')),+ ])+ );++ expect(offenders).toEqual(Object.fromEntries(RULES.map(({ name }) => [name, []])));+ });++ it('recognizes each API however it is spelled, and leaves type-only ClipboardItem references alone', () => {+ const matches = (name: (typeof RULES)[number]['name'], text: string): boolean =>+ RULES.find((rule) => rule.name === name)!.pattern.test(text);- expect(offenders).toEqual([]);+ expect(matches('navigator.locks', 'navigator?.locks.request(name)')).toBe(true);+ expect(matches('navigator.locks', 'navigator . locks')).toBe(true);+ expect(matches('navigator.clipboard and runtime ClipboardItem', 'navigator.clipboard.writeText(x)')).toBe(true);+ expect(matches('navigator.clipboard and runtime ClipboardItem', 'new ClipboardItem({ [type]: blob })')).toBe(true);+ expect(matches('navigator.clipboard and runtime ClipboardItem', 'globalThis?.ClipboardItem')).toBe(true);+ expect(matches('navigator.clipboard and runtime ClipboardItem', "ClipboardItem.supports('image/png')")).toBe(true);+ expect(matches('navigator.clipboard and runtime ClipboardItem', 'let items: readonly ClipboardItem[];')).toBe(+ false+ );+ expect(matches('navigator.serviceWorker', 'navigator.serviceWorker.register(url)')).toBe(true);+ expect(matches('navigator.storage', 'navigator.storage.persist()')).toBe(true);+ expect(matches('randomUUID and SubtleCrypto', 'crypto.subtle.digest(data)')).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex 3ee9c97abb..ddcc5fd681 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -796,7 +796,9 @@ describe('GalleryImageGrid mixed item cells', () => {expect(viewport.scrollTop).toBe(initialScrollTop);await interact(() => pointer('pointermove', document, x, edgeY - 20), 100);- await interact(() => pointer('pointerup', document, x, edgeY - 20));+ // dnd-kit briefly suppresses the click following a completed drag. Let+ // that document-level guard expire before the next interaction test.+ await interact(() => pointer('pointerup', document, x, edgeY - 20), 300);expect(viewport.scrollTop).toBe(initialScrollTop);});@@ -3363,14 +3365,15 @@ describe('GalleryImageGrid virtualization', () => {return countAttempts === 1 ? Promise.reject(new Error('Count unavailable')) : Promise.resolve(65);});mocks.fetchSparsePage.mockImplementation((_filter, offset) => Promise.resolve({ items, offset, total: 65 }));+ const gallery = createGallery({+ items: [],+ page: 1,+ settings: { ...DENSE_SETTINGS, paginationMode: 'paginated' },+ });+ // The selected board resolves against the boards query; left to load, its answer would re-key the count query.+ queryClient!.setQueryData(galleryBoardsOptions(getGalleryListingBoardsQuery(gallery.settings)).queryKey, [board]);- await renderQueryBackedGallery(- createGallery({- items: [],- page: 1,- settings: { ...DENSE_SETTINGS, paginationMode: 'paginated' },- })- );+ await renderQueryBackedGallery(gallery);await vi.waitFor(() => {expect(host?.querySelector('[data-gallery-page-error="0"]')).not.toBeNull();diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsxindex a1b4075f1d..b50b9f8e40 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx@@ -11,7 +11,7 @@ import i18next from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import { userEvent } from 'vitest/browser';import { GeneratePresetsPopover } from './GeneratePresetsPopover';@@ -143,6 +143,14 @@ describe('GeneratePresetsPopover', () => {});it('starts a rename reopened during the exit animation from the newly chosen preset', async () => {+ // The reopen has to land while the closed dialog is still animating out; on a loaded machine a real-length exit+ // animation can end before the Escape press even returns, so it is held for the whole test.+ const holdExit = document.createElement('style');+ holdExit.textContent =+ '[data-scope="dialog"][data-part="content"][data-state="closed"] { animation-duration: 3600s !important; }';+ document.head.append(holdExit);+ onTestFinished(() => holdExit.remove());+await openRename(0);await act(() => userEvent.type(renameInput()!, ' draft'));await act(() => userEvent.keyboard('{Escape}'));diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsxindex 6ebf4e5f9c..08239720f2 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx@@ -2,7 +2,8 @@import type { ReactNode } from 'react';import { Box, Menu, Portal } from '@chakra-ui/react';-import { MenuContent, useContextMenu } from '@platform/ui/Menu';+import { canCopyText, copyText } from '@platform/browser/clipboard';+import { MenuContent, MenuItem, useContextMenu } from '@platform/ui/Menu';import { useTranslation } from 'react-i18next';interface GenerateFieldContextMenuProps {@@ -25,6 +26,7 @@ export const GenerateFieldContextMenu = ({}: GenerateFieldContextMenuProps) => {const { t } = useTranslation();const { anchor: point, close, onRequestDismiss, open } = useContextMenu();+ const copyUnavailableReason = canCopyText() ? undefined : t('common.copyUnavailable');return (<Box@@ -56,9 +58,13 @@ export const GenerateFieldContextMenu = ({{resetLabel ?? t('widgets.generate.resetToModelDefault')}</Menu.Item>) : null}- <Menu.Item value="copy" onClick={() => void navigator.clipboard.writeText(copyValue())}>+ <MenuItem+ unavailableReason={copyUnavailableReason}+ value="copy"+ onClick={() => void copyText(copyValue()).catch(() => undefined)}+ >{t('widgets.generate.copyValue')}- </Menu.Item>+ </MenuItem></MenuContent></Menu.Positioner></Portal>diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsxindex b143e2df2d..491e222686 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/add-nodes/AddNodesView.tsx@@ -10,6 +10,7 @@ import {import { refreshCustomNodePacks, useCustomNodesSelector } from '@features/nodes/data/nodesStore';import { updateNodesUi, useNodesUiSelector } from '@features/nodes/ui/nodesUiStore';import { useNotify } from '@features/nodes/ui/useNodesNotify';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { useScopedAction } from '@platform/react/useScopedAction';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';@@ -110,9 +111,10 @@ export const AddNodesView = () => {);};+ const canCopyPath = canCopyText();const handleCopyPath = async (path: string) => {try {- await navigator.clipboard.writeText(path);+ await copyText(path);notify.success(t('nodes.pathCopied'));} catch {notify.error(t('common.couldNotCopy'));@@ -165,6 +167,8 @@ export const AddNodesView = () => {{t('nodes.nodesDirectory')}</Text><IconButton+ tooltip={t('nodes.copyPath')}+ unavailableReason={canCopyPath ? undefined : t('common.copyUnavailable')}aria-label={t('nodes.copyPath')}size="sm"variant="ghost"diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsxindex d81b6528ad..94d08298af 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackContextMenu.tsx@@ -5,7 +5,9 @@ import type { ListContextMenuAnchor } from '@platform/ui/list/ListItem';import { Icon, Menu, Portal } from '@chakra-ui/react';import { UninstallPackDialog } from '@features/nodes/ui/shared/UninstallPackDialog';import { useNotify } from '@features/nodes/ui/useNodesNotify';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { MenuContent } from '@platform/ui';+import { MenuItem } from '@platform/ui/Menu';import { ClipboardCopyIcon, Trash2Icon } from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';@@ -29,10 +31,11 @@ export const NodePackContextMenu = ({// Captured with the request: the menu target clears when the menu closes, before the dialog does.const [uninstallFocusTarget, setUninstallFocusTarget] = useState<(() => HTMLElement | null) | null>(null);const pack = target?.pack ?? null;+ const copyUnavailableReason = canCopyText() ? undefined : t('common.copyUnavailable');const handleCopyPath = async (path: string) => {try {- await navigator.clipboard.writeText(path);+ await copyText(path);notify.success(t('nodes.pathCopied'));} catch {notify.error(t('common.couldNotCopy'));@@ -60,10 +63,14 @@ export const NodePackContextMenu = ({<Menu.Positioner>{pack ? (<MenuContent minW="12rem">- <Menu.Item value="copy-path" onClick={() => void handleCopyPath(pack.path)}>+ <MenuItem+ unavailableReason={copyUnavailableReason}+ value="copy-path"+ onClick={() => void handleCopyPath(pack.path)}+ ><Icon as={ClipboardCopyIcon} boxSize="3.5" /><Menu.ItemText fontSize="md">{t('nodes.copyPath')}</Menu.ItemText>- </Menu.Item>+ </MenuItem><Menu.Separator /><Menu.Itemdata-danger=""diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex b61e4395b9..bb5b3f21eb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -19,8 +19,10 @@ import {shouldAddForReturnLoopLinkage,parseWorkflowJson,} from '@features/workflow/utility';+import { canCopyText } from '@platform/browser/clipboard';import { useMountEffect } from '@platform/react/useMountEffect';import { Button, IconButton, RenameDialog, Tooltip } from '@platform/ui';+import { MenuItem } from '@platform/ui/Menu';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import {BookmarkIcon,@@ -149,6 +151,7 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {downloadWorkflowJson(projectGraph);}, [getProjectGraph, notify, t]);+ const copyUnavailableReason = canCopyText() ? undefined : t('common.copyUnavailable');const copyWorkflow = useCallback(() => {const projectGraph = getProjectGraph();@@ -202,9 +205,9 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {<Menu.Item value="export" onClick={exportWorkflow}>{t('widgets.workflow.exportJson')}</Menu.Item>- <Menu.Item value="copy" onClick={copyWorkflow}>+ <MenuItem unavailableReason={copyUnavailableReason} value="copy" onClick={copyWorkflow}>{t('widgets.workflow.copyJson')}- </Menu.Item>+ </MenuItem><Menu.Item value="new" onClick={newWorkflow}>{t('widgets.workflow.newWorkflow')}</Menu.Item>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxindex 8e127cab62..d0a2a50bb6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -5,6 +5,7 @@ import type { ReactNode } from 'react';import { Box, Center, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { localizeForLoopValidationReason } from '@features/workflow/core/forLoops';import { useWorkflowGraphPreview } from '@features/workflow/ui/WorkflowUiContext';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { Button, JsonPreview, SegmentTabs, segmentTabsPanelId, segmentTabsTabId, toaster } from '@platform/ui';import { Dialog } from '@platform/ui/Dialog';import { CheckIcon, ChevronUpIcon, CopyIcon, TriangleAlertIcon } from 'lucide-react';@@ -174,11 +175,11 @@ export const GraphPreviewDialog = ({[mode]);+ const canCopy = canCopyText();const copyJson = useCallback(() => {const json = JSON.stringify(graph?.backendGraph ?? graph, null, 2);- navigator.clipboard- .writeText(json)+ copyText(json).then(() => {setHasCopied(true);@@ -276,7 +277,12 @@ export const GraphPreviewDialog = ({</Dialog.Body><Dialog.Footer justifyContent="space-between"><Box display="flex" gap="2">- <Button disabled={!graph} variant="outline" onClick={copyJson}>+ <Button+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}+ disabled={!graph}+ variant="outline"+ onClick={copyJson}+ ><Iconas={hasCopied ? CheckIcon : CopyIcon}boxSize="3.5"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.tsindex d4ae729b8f..30fe8aedca 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowTransfer.ts@@ -1,6 +1,7 @@import type { ProjectGraphState } from '@features/workflow/contracts';import { serializeWorkflowJson } from '@features/workflow/utility';+import { copyText } from '@platform/browser/clipboard';import { downloadText } from '@platform/browser/downloadBlob';/** Export-side helpers shared by the workflow menu items and panels. */@@ -16,5 +17,4 @@ export const downloadWorkflowJson = (document: ProjectGraphState): void => {export const getWorkflowJsonText = (document: ProjectGraphState): string =>JSON.stringify(serializeWorkflowJson(document), null, 2);-export const copyWorkflowJson = (document: ProjectGraphState): Promise<void> =>- navigator.clipboard.writeText(getWorkflowJsonText(document));+export const copyWorkflowJson = (document: ProjectGraphState): Promise<void> => copyText(getWorkflowJsonText(document));diff --git a/invokeai/frontend/webv2/src/platform/browser/clipboard.test.ts b/invokeai/frontend/webv2/src/platform/browser/clipboard.test.tsnew file mode 100644index 0000000000..24a6feeece--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/clipboard.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it, vi } from 'vitest';++import {+ canCopyImage,+ canCopyText,+ ClipboardUnavailableError,+ copyImage,+ copyText,+ readClipboardItems,+} from './clipboard';++class TestClipboardItem {+ constructor(readonly items: Record<string, Blob>) {}+}+const ClipboardItemCtor = TestClipboardItem as unknown as new (items: Record<string, Blob>) => ClipboardItem;++describe('clipboard', () => {+ // Unit tests run without a browser, as a plain-HTTP page does: neither `navigator.clipboard` nor `ClipboardItem`.+ it('reports copying unavailable without the Clipboard API, and rejects with a typed error', async () => {+ expect(canCopyText()).toBe(false);+ expect(canCopyImage()).toBe(false);++ await expect(copyText('x')).rejects.toBeInstanceOf(ClipboardUnavailableError);+ await expect(copyImage(new Blob(['pixels'], { type: 'image/png' }))).rejects.toBeInstanceOf(+ ClipboardUnavailableError+ );+ await expect(readClipboardItems()).rejects.toBeInstanceOf(ClipboardUnavailableError);+ });++ it('copies text when the clipboard can write it', async () => {+ const writeText = vi.fn(() => Promise.resolve());++ expect(canCopyText({ clipboard: { writeText } })).toBe(true);+ await copyText('project-id', { clipboard: { writeText } });++ expect(writeText).toHaveBeenCalledWith('project-id');+ });++ it('needs both a writable clipboard and ClipboardItem to copy an image, and keeps the blob type', async () => {+ const write = vi.fn((_items: ClipboardItem[]) => Promise.resolve());+ const webp = new Blob(['pixels'], { type: 'image/webp' });++ expect(canCopyImage({ clipboard: { write } })).toBe(false);+ expect(canCopyImage({ ClipboardItemCtor, clipboard: { write } })).toBe(true);+ await copyImage(webp, { ClipboardItemCtor, clipboard: { write } });+ await copyImage(new Blob(['pixels']), { ClipboardItemCtor, clipboard: { write } });++ const [[[typed]], [[untyped]]] = write.mock.calls as unknown as [[[TestClipboardItem]], [[TestClipboardItem]]];+ expect(typed.items).toEqual({ 'image/webp': webp });+ expect(Object.keys(untyped.items)).toEqual(['image/png']);+ });++ it('passes on a refused clipboard write as the browser reports it', async () => {+ const refused = new DOMException('Write permission denied.', 'NotAllowedError');++ await expect(copyText('x', { clipboard: { writeText: () => Promise.reject(refused) } })).rejects.toBe(refused);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/browser/clipboard.ts b/invokeai/frontend/webv2/src/platform/browser/clipboard.tsnew file mode 100644index 0000000000..97d909065a--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/clipboard.ts@@ -0,0 +1,70 @@+/**+ * The only accessor of the async Clipboard API. Browsers expose it only in a secure context (HTTPS or localhost), so+ * on a plain-HTTP origin `navigator.clipboard` and `ClipboardItem` are absent: callers ask `canCopy*` to disable their+ * control, and the operations reject with `ClipboardUnavailableError` instead of throwing a `TypeError`.+ */++type ClipboardItemConstructor = new (items: Record<string, Blob>) => ClipboardItem;++interface ClipboardLike {+ read?(): Promise<readonly ClipboardItem[]>;+ write?(items: ClipboardItem[]): Promise<void>;+ writeText?(text: string): Promise<void>;+}++/** Stands in for the browser's clipboard in tests; an omitted part falls back to the browser's. */+export interface ClipboardAccess {+ clipboard?: ClipboardLike;+ ClipboardItemCtor?: ClipboardItemConstructor;+}++export class ClipboardUnavailableError extends Error {+ constructor() {+ super('The clipboard is unavailable: browsers allow it only over HTTPS or on localhost.');+ this.name = 'ClipboardUnavailableError';+ }+}++const getClipboard = (access: ClipboardAccess): ClipboardLike | undefined => {+ if (access.clipboard) {+ return access.clipboard;+ }+ try {+ return typeof navigator === 'undefined' ? undefined : (navigator.clipboard ?? undefined);+ } catch {+ return undefined;+ }+};++const getClipboardItem = (access: ClipboardAccess): ClipboardItemConstructor | undefined =>+ access.ClipboardItemCtor ?? (typeof globalThis.ClipboardItem === 'function' ? globalThis.ClipboardItem : undefined);++export const canCopyText = (access: ClipboardAccess = {}): boolean =>+ typeof getClipboard(access)?.writeText === 'function';++export const copyText = async (text: string, access: ClipboardAccess = {}): Promise<void> => {+ const clipboard = getClipboard(access);+ if (typeof clipboard?.writeText !== 'function') {+ throw new ClipboardUnavailableError();+ }+ await clipboard.writeText(text);+};++export const canCopyImage = (access: ClipboardAccess = {}): boolean =>+ typeof getClipboard(access)?.write === 'function' && getClipboardItem(access) !== undefined;++/** Puts an image on the clipboard under its own type, PNG when the blob names none. */+export const copyImage = async (blob: Blob, access: ClipboardAccess = {}): Promise<void> => {+ const clipboard = getClipboard(access);+ const ClipboardItemImpl = getClipboardItem(access);+ if (typeof clipboard?.write !== 'function' || !ClipboardItemImpl) {+ throw new ClipboardUnavailableError();+ }+ await clipboard.write([new ClipboardItemImpl({ [blob.type || 'image/png']: blob })]);+};++/** What the clipboard holds, for paste; rejects as the browser does when permission is refused. */+export const readClipboardItems = (access: ClipboardAccess = {}): Promise<readonly ClipboardItem[]> => {+ const clipboard = getClipboard(access);+ return typeof clipboard?.read === 'function' ? clipboard.read() : Promise.reject(new ClipboardUnavailableError());+};diff --git a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.tsindex c69a40fc4a..c491ee751f 100644--- a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.test.ts@@ -10,6 +10,7 @@ import {interface TestEnvironmentOptions {browserFamily?: BrowserFamily;+ hasWebLocks?: boolean;isContextAvailable?: boolean;mutateReadback?: (pixels: Uint8ClampedArray) => void;readbackError?: Error;@@ -17,6 +18,7 @@ interface TestEnvironmentOptions {const createTestEnvironment = ({browserFamily = 'chromium',+ hasWebLocks = true,isContextAvailable = true,mutateReadback,readbackError,@@ -52,6 +54,7 @@ const createTestEnvironment = ({return {browserFamily,createCanvas: () => canvas,+ hasWebLocks: () => hasWebLocks,};};@@ -134,6 +137,18 @@ describe('known browser issues', () => {it('shows only the generic instruction elsewhere', () => {expect(getWorkaroundIds('other')).toEqual(['other-browser']);});++ it('detects the plain-HTTP limits whenever Web Locks are unavailable, and only then', () => {+ // A secure context can lack Web Locks too (an old browser, a disabled API): the notice follows the capability.+ expect(getDetectedIssueIds(createTestEnvironment({ hasWebLocks: false }))).toEqual(['plain-http-limits']);+ expect(getDetectedIssueIds(createTestEnvironment({ hasWebLocks: true }))).toEqual([]);+ expect(+ detectKnownBrowserIssues(createTestEnvironment({ hasWebLocks: false })).map(({ dismissible, id }) => ({+ dismissible,+ id,+ }))+ ).toEqual([{ dismissible: true, id: 'plain-http-limits' }]);+ });});describe('identifyBrowserFamily', () => {diff --git a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.tsindex 5daa53011f..1554916525 100644--- a/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts+++ b/invokeai/frontend/webv2/src/platform/browser/knownBrowserIssues.ts@@ -1,4 +1,6 @@-export type KnownBrowserIssueId = 'canvas-readback-integrity';+import { hasWebLocks } from './webLocks';++export type KnownBrowserIssueId = 'canvas-readback-integrity' | 'plain-http-limits';export type KnownBrowserIssueSeverity = 'warning' | 'error';@@ -15,10 +17,13 @@ export interface KnownBrowserIssueWorkaround {export interface BrowserIssueDetectionEnvironment {browserFamily: BrowserFamily;createCanvas: () => HTMLCanvasElement;+ hasWebLocks: () => boolean;}export interface DetectedBrowserIssue {id: KnownBrowserIssueId;+ /** The viewer may hide it; the dismissal is remembered per origin. Absent means it shows on every visit. */+ dismissible?: boolean;severity: KnownBrowserIssueSeverity;titleKey: string;descriptionKey: string;@@ -55,6 +60,7 @@ const CANVAS_PROBE_SIZE = 32;const createDefaultDetectionEnvironment = (): BrowserIssueDetectionEnvironment => ({browserFamily: identifyBrowserFamily(navigator as Navigator & BrowserIdentity),createCanvas: () => document.createElement('canvas'),+ hasWebLocks: () => hasWebLocks(),});const createExpectedCanvasPixels = (): Uint8ClampedArray => {@@ -131,6 +137,22 @@ export const KNOWN_BROWSER_ISSUES = [},],},+ {+ descriptionKey: 'launchpad.browserIssues.plainHttpLimits.description',+ // Browsers expose Web Locks (and the clipboard) only in a secure context, so plain HTTP from a network address+ // (another computer, or this one through its LAN IP) is the real-world cause; the issue follows the capability.+ detect: (environment) => !environment.hasWebLocks(),+ dismissible: true,+ id: 'plain-http-limits',+ severity: 'warning',+ titleKey: 'launchpad.browserIssues.plainHttpLimits.title',+ workarounds: [+ {+ id: 'localhost-or-https',+ instructionKey: 'launchpad.browserIssues.plainHttpLimits.workaround',+ },+ ],+ },] as const satisfies readonly KnownBrowserIssue[];const REGISTERED_ISSUES: readonly KnownBrowserIssue[] = KNOWN_BROWSER_ISSUES;diff --git a/invokeai/frontend/webv2/src/platform/browser/webLocks.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/webLocks.browser.test.tsindex 8105e411cd..ae6779e306 100644--- a/invokeai/frontend/webv2/src/platform/browser/webLocks.browser.test.ts+++ b/invokeai/frontend/webv2/src/platform/browser/webLocks.browser.test.ts@@ -1,8 +1,23 @@import { describe, expect, it } from 'vitest';-import { acquireExclusiveLock, isLockHeld, waitForSharedLock } from './webLocks';+import { acquireExclusiveLock, hasWebLocks, isLockHeld, waitForSharedLock } from './webLocks';describe('Web Locks adapter', () => {+ it('reports whether Web Locks are available, from the browser or an injected manager', () => {+ // The browser test page is a secure context (localhost), where the API exists.+ expect(hasWebLocks()).toBe(true);+ expect(hasWebLocks({} as LockManager)).toBe(true);++ const descriptor = Object.getOwnPropertyDescriptor(Navigator.prototype, 'locks');+ Object.defineProperty(Navigator.prototype, 'locks', { configurable: true, get: () => undefined });+ try {+ // As on a plain-HTTP origin, where the browser leaves `navigator.locks` undefined.+ expect(hasWebLocks()).toBe(false);+ } finally {+ Object.defineProperty(Navigator.prototype, 'locks', descriptor!);+ }+ });+it('holds one exclusive owner and releases it idempotently', async () => {const name = `invokeai:web-lock-test:${crypto.randomUUID()}`;const first = await acquireExclusiveLock(name);diff --git a/invokeai/frontend/webv2/src/platform/browser/webLocks.ts b/invokeai/frontend/webv2/src/platform/browser/webLocks.tsindex 659ee184fb..8d469cc8bc 100644--- a/invokeai/frontend/webv2/src/platform/browser/webLocks.ts+++ b/invokeai/frontend/webv2/src/platform/browser/webLocks.ts@@ -3,6 +3,21 @@ export type BrowserLockResult =| { kind: 'contended' }| { kind: 'unavailable' };+/** The injected manager, else the browser's; none outside a secure context (plain HTTP), where the API is absent. */+const getLockManager = (lockManager?: LockManager): LockManager | undefined => {+ if (lockManager) {+ return lockManager;+ }+ try {+ return typeof navigator === 'undefined' ? undefined : navigator.locks;+ } catch {+ return undefined;+ }+};++/** Whether tabs of this origin can coordinate through Web Locks; false on a plain-HTTP origin. */+export const hasWebLocks = (lockManager?: LockManager): boolean => getLockManager(lockManager) !== undefined;+const acquireLock = (name: string,mode: 'exclusive' | 'shared',@@ -10,14 +25,7 @@ const acquireLock = (/** Wait for the lock until it is granted or this aborts, instead of taking it only when free. */waitSignal?: AbortSignal): Promise<BrowserLockResult> => {- let manager = lockManager;- if (!manager) {- try {- manager = typeof navigator === 'undefined' ? undefined : navigator.locks;- } catch {- manager = undefined;- }- }+ const manager = getLockManager(lockManager);if (!manager) {return Promise.resolve({ kind: 'unavailable' });}@@ -85,14 +93,7 @@ export const waitForSharedLock = (* the name is never turned away. `null` when the Web Locks API or its query is unavailable.*/export const isLockHeld = async (name: string, lockManager?: LockManager): Promise<boolean | null> => {- let manager = lockManager;- if (!manager) {- try {- manager = typeof navigator === 'undefined' ? undefined : navigator.locks;- } catch {- manager = undefined;- }- }+ const manager = getLockManager(lockManager);if (!manager || typeof manager.query !== 'function') {return null;}diff --git a/invokeai/frontend/webv2/src/platform/ui/Button.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Button.browser.test.tsxnew file mode 100644index 0000000000..d1cb453fc3--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Button.browser.test.tsx@@ -0,0 +1,188 @@+import type { ReactNode } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { CopyIcon } from 'lucide-react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { Button, IconButton } from './Button';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(async () => {+ await userEvent.unhover(document.body);+ await act(() => root?.unmount());+ host?.remove();+ delete document.documentElement.dataset.reduceMotion;+ host = null;+ root = null;+});++const REASON = 'Copying needs HTTPS or localhost';++const mount = async (children: ReactNode) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(<ChakraProvider value={system}>{children}</ChakraProvider>);+ await Promise.resolve();+ });+};++const render = (reason: string | undefined, handlers: { copyId: () => void; copyLog: () => void }) =>+ mount(+ <>+ <IconButton aria-label="Copy ID" tooltip="Copy ID" unavailableReason={reason} onClick={handlers.copyId}>+ <CopyIcon />+ </IconButton>+ <Button unavailableReason={reason} onClick={handlers.copyLog}>+ Copy log+ </Button>+ </>+ );++const tooltipText = (): string | null | undefined => document.querySelector('[role="tooltip"]')?.textContent;++describe('unavailable buttons', () => {+ it('stay focusable, read as disabled and described by their reason, show it, and ignore activation', async () => {+ const handlers = { copyId: vi.fn(), copyLog: vi.fn() };+ await render(REASON, handlers);+ const copyId = page.getByRole('button', { name: 'Copy ID', exact: true });+ const copyLog = page.getByRole('button', { name: 'Copy log', exact: true });++ for (const button of [copyId, copyLog]) {+ await expect.element(button).toHaveAttribute('aria-disabled', 'true');+ await expect.element(button).toHaveAccessibleDescription(REASON);+ }+ // The hidden copy of the reason stays out of the name.+ await expect.element(copyLog).toHaveAccessibleName('Copy log');++ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(copyId.element());+ await vi.waitFor(() => expect(tooltipText()).toBe(`Copy ID${REASON}`));+ await act(() => userEvent.keyboard('{Enter}'));++ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(copyLog.element());+ await vi.waitFor(() => expect(tooltipText()).toBe(REASON));+ await act(() => userEvent.keyboard('{Enter}'));+ // Pointer tooling refuses aria-disabled targets; a click still reaches the element and must do nothing.+ await act(() => (copyLog.element() as HTMLButtonElement).click());++ expect(handlers.copyId).not.toHaveBeenCalled();+ expect(handlers.copyLog).not.toHaveBeenCalled();+ });++ it('act, with their own tooltip and no description, when available', async () => {+ const handlers = { copyId: vi.fn(), copyLog: vi.fn() };+ await render(undefined, handlers);+ const copyId = page.getByRole('button', { name: 'Copy ID', exact: true });++ await expect.element(copyId).not.toHaveAttribute('aria-disabled');+ await act(() => userEvent.hover(copyId));+ await vi.waitFor(() => expect(tooltipText()).toBe('Copy ID'));+ await act(() => userEvent.click(copyId));+ await act(() => userEvent.click(page.getByRole('button', { name: 'Copy log', exact: true })));++ expect(handlers.copyId).toHaveBeenCalledOnce();+ expect(handlers.copyLog).toHaveBeenCalledOnce();+ });++ it('do not submit their form, by click, key, or implicit submission', async () => {+ const submit = vi.fn((event: SubmitEvent) => event.preventDefault());+ await mount(+ <form onSubmit={(event) => submit(event.nativeEvent as SubmitEvent)}>+ <input aria-label="Name" />+ <Button type="submit" unavailableReason={REASON}>+ Save+ </Button>+ </form>+ );+ const ancestorClick = vi.fn();+ host?.addEventListener('click', ancestorClick);+ const save = page.getByRole('button', { name: 'Save', exact: true });++ await act(() => (save.element() as HTMLButtonElement).click());+ (save.element() as HTMLButtonElement).focus();+ await act(() => userEvent.keyboard('{Enter}'));+ await act(() => userEvent.keyboard(' '));+ // Enter in a field submits through the form's default button, which is this one.+ (page.getByRole('textbox', { name: 'Name' }).element() as HTMLInputElement).focus();+ await act(() => userEvent.keyboard('{Enter}'));++ expect(submit).not.toHaveBeenCalled();+ // Like a natively disabled button, it delivers no click to its ancestors either.+ expect(ancestorClick).not.toHaveBeenCalled();+ });++ it('keep the description the caller gives, beside the reason', async () => {+ await mount(+ <>+ <p id="copy-hint">Copies the whole log</p>+ <Button aria-describedby="copy-hint" unavailableReason={REASON}>+ Copy log+ </Button>+ <IconButton aria-describedby="copy-hint" aria-label="Copy ID" unavailableReason={REASON}>+ <CopyIcon />+ </IconButton>+ </>+ );++ for (const name of ['Copy log', 'Copy ID']) {+ await expect+ .element(page.getByRole('button', { name, exact: true }))+ .toHaveAccessibleDescription(`Copies the whole log ${REASON}`);+ }+ });++ it('keep their reason reachable when the caller also disables them', async () => {+ const copyLog = vi.fn();+ await mount(+ <Button disabled unavailableReason={REASON} onClick={copyLog}>+ Copy log+ </Button>+ );+ const button = page.getByRole('button', { name: 'Copy log', exact: true });++ await expect.element(button).not.toHaveAttribute('disabled');+ await expect.element(button).toHaveAttribute('aria-disabled', 'true');+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(button.element());+ await vi.waitFor(() => expect(tooltipText()).toBe(REASON));+ await act(() => userEvent.keyboard('{Enter}'));+ expect(copyLog).not.toHaveBeenCalled();+ });++ it('show no hover feedback, even while their reason shows', async () => {+ // Read settled colors: reduced motion shortens the hover transition to a millisecond.+ document.documentElement.dataset.reduceMotion = 'true';+ await mount(+ <>+ <Button variant="outline">Available</Button>+ <Button unavailableReason={REASON} variant="outline">+ Unavailable+ </Button>+ </>+ );+ const background = (name: string) =>+ getComputedStyle(page.getByRole('button', { name, exact: true }).element()).backgroundColor;+ const resting = { available: background('Available'), unavailable: background('Unavailable') };++ // The control: hovering an available button does change its fill.+ await act(() => userEvent.hover(page.getByRole('button', { name: 'Available', exact: true })));+ await vi.waitFor(() => expect(background('Available')).not.toBe(resting.available));++ await act(() => userEvent.hover(page.getByRole('button', { name: 'Unavailable', exact: true })));+ await vi.waitFor(() => expect(background('Available')).toBe(resting.available));+ expect(background('Unavailable')).toBe(resting.unavailable);+ // The open tooltip marks its trigger expanded, which buttons tint like hover.+ await vi.waitFor(() => expect(tooltipText()).toBe(REASON));+ expect(background('Unavailable')).toBe(resting.unavailable);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Button.tsx b/invokeai/frontend/webv2/src/platform/ui/Button.tsxindex 5629c318d3..acc745ec0c 100644--- a/invokeai/frontend/webv2/src/platform/ui/Button.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Button.tsx@@ -1,16 +1,28 @@-import type { ComponentProps, ReactNode } from 'react';+import type { ComponentProps, ReactNode, SyntheticEvent } from 'react';import {Button as ChakraButton,CloseButton as ChakraCloseButton,Icon,IconButton as ChakraIconButton,+ Stack,+ Text,} from '@chakra-ui/react';-import { useCallback } from 'react';+import { useCallback, useId, useMemo } from 'react';import { Tooltip } from './Tooltip';-type ButtonProps = ComponentProps<typeof ChakraButton>;+interface UnavailableProps {+ /**+ * Why the control cannot act now (say, no clipboard on a plain-HTTP origin). It stays visible and focusable, reads+ * as disabled (`aria-disabled`, described by the reason), lets no activation through (a submit button does not+ * submit), and shows the reason in its tooltip. The reason wins over `disabled`, which would hide it. Native+ * `disabled` alone stays for states the user can change, where there is nothing to explain.+ */+ unavailableReason?: string;+}++type ButtonProps = ComponentProps<typeof ChakraButton> & UnavailableProps;type CloseButtonProps = ComponentProps<typeof ChakraCloseButton>;type ChakraIconButtonProps = ComponentProps<typeof ChakraIconButton>;@@ -24,19 +36,107 @@ type IconButtonAccessibleName ='aria-labelledby': string;};-export type IconButtonProps = Omit<ChakraIconButtonProps, 'aria-label' | 'aria-labelledby'> & IconButtonAccessibleName;+export type IconButtonProps = Omit<ChakraIconButtonProps, 'aria-label' | 'aria-labelledby'> &+ IconButtonAccessibleName &+ UnavailableProps & {+ /** The platform tooltip an icon-only control carries; while unavailable it adds the reason. */+ tooltip?: ReactNode;+ };++/**+ * Cancels a click before any handler sees it, as native `disabled` would: the default (form submission, link+ * navigation) is prevented, and stopping propagation in the capture phase keeps the event from the control's own+ * handlers, a library's (Zag's menu item select), and its ancestors'. Keyboard activation arrives as a click too.+ */+const preventActivation = (event: SyntheticEvent) => {+ event.preventDefault();+ event.stopPropagation();+};++/**+ * What makes a Button or menu item unavailable: it reads as disabled (`aria-disabled`) yet stays focusable or+ * highlightable, no activation gets through, and a hidden copy of the reason describes it after any description the+ * caller gave. A tooltip cannot carry the description: a menu item is never focused, and a tooltip's own content exists+ * only while open. Render `description` inside the control. Callers drop native `disabled` while a reason holds, so the+ * reason is always reachable.+ */+export const useUnavailableControl = (reason: string | undefined, describedBy: string | undefined) => {+ const descriptionId = useId();++ if (!reason) {+ return null;+ }++ return {+ description: (+ <span hidden id={descriptionId}>+ {reason}+ </span>+ ),+ props: {+ 'aria-describedby': describedBy ? `${describedBy} ${descriptionId}` : descriptionId,+ 'aria-disabled': true,+ onClickCapture: preventActivation,+ } as const,+ };+};/** Solid defaults to accent; other variants to gray. Explicit colorPalette overrides both. */const defaultPalette = (variant: ButtonProps['variant']): ButtonProps['colorPalette'] =>variant === undefined || variant === 'solid' ? 'accent' : 'gray';-export const Button = ({ colorPalette, ...props }: ButtonProps) => (- <ChakraButton colorPalette={colorPalette ?? defaultPalette(props.variant)} {...props} />-);+export const Button = ({ children, colorPalette, disabled, unavailableReason, ...props }: ButtonProps) => {+ const unavailable = useUnavailableControl(unavailableReason, props['aria-describedby']);+ const button = (+ <ChakraButton+ colorPalette={colorPalette ?? defaultPalette(props.variant)}+ {...props}+ {...unavailable?.props}+ disabled={unavailable ? undefined : disabled}+ >+ {children}+ {unavailable?.description}+ </ChakraButton>+ );++ return unavailableReason ? <Tooltip content={unavailableReason}>{button}</Tooltip> : button;+};++export const IconButton = ({+ children,+ colorPalette,+ disabled,+ tooltip,+ unavailableReason,+ ...props+}: IconButtonProps) => {+ const unavailable = useUnavailableControl(unavailableReason, props['aria-describedby']);+ const content = useMemo(+ () =>+ unavailableReason ? (+ <Stack gap="0">+ {tooltip ? <Text>{tooltip}</Text> : null}+ <Text color={tooltip ? 'fg.muted' : undefined}>{unavailableReason}</Text>+ </Stack>+ ) : (+ tooltip+ ),+ [tooltip, unavailableReason]+ );+ const button = (+ <ChakraIconButton+ colorPalette={colorPalette ?? defaultPalette(props.variant)}+ {...props}+ {...unavailable?.props}+ disabled={unavailable ? undefined : disabled}+ >+ {children}+ {unavailable?.description}+ </ChakraIconButton>+ );-export const IconButton = ({ colorPalette, ...props }: IconButtonProps) => (- <ChakraIconButton colorPalette={colorPalette ?? defaultPalette(props.variant)} {...props} />-);+ return content ? <Tooltip content={content}>{button}</Tooltip> : button;+};/** Dismissal chrome is muted. */export const CloseButton = (props: CloseButtonProps) => <ChakraCloseButton color="fg.muted" {...props} />;diff --git a/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx b/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsxindex 16899db93f..2fadb35d34 100644--- a/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/JsonPreview.tsx@@ -1,6 +1,8 @@import { Box, Code, Icon, ScrollArea } from '@chakra-ui/react';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { CheckIcon, CopyIcon } from 'lucide-react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';import { IconButton } from './Button';import { toaster } from './toaster';@@ -27,6 +29,8 @@ export const JsonPreview = ({text?: string;value?: unknown;}) => {+ const { t } = useTranslation();+ const canCopy = canCopyText();const [hasCopied, setHasCopied] = useState(false);const copyResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const viewportRef = useRef<HTMLDivElement | null>(null);@@ -44,8 +48,7 @@ export const JsonPreview = ({);const copy = useCallback(() => {- navigator.clipboard- .writeText(json)+ copyText(json).then(() => {setHasCopied(true);@@ -73,12 +76,13 @@ export const JsonPreview = ({w="full"><IconButton+ tooltip={copyLabel}+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}aria-label={copyLabel}bg="bg.muted"position="absolute"right="1.5"size="sm"- title={copyLabel}top="1.5"variant="ghost"zIndex="1"diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsxnew file mode 100644index 0000000000..e40429a002--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsx@@ -0,0 +1,137 @@+import { ChakraProvider, Menu } from '@chakra-ui/react';+import { system } from '@theme/system';+import { CopyIcon } from 'lucide-react';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { MenuActionItem, MenuIconItem, MenuItem } from './Menu';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++const REASON = 'Copying needs HTTPS or localhost';++const handlers = () => ({+ copyImage: vi.fn(),+ copyJson: vi.fn(),+ copyPath: vi.fn(),+ rename: vi.fn(),+ rootSelect: vi.fn(),+});++const renderMenu = async (actions: ReturnType<typeof handlers>) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Menu.Root onSelect={actions.rootSelect}>+ <Menu.Trigger>Actions</Menu.Trigger>+ <Menu.Positioner>+ <Menu.Content>+ <MenuIconItem+ icon={CopyIcon}+ label="Copy image"+ unavailableReason={REASON}+ value="copy-image"+ onSelect={actions.copyImage}+ />+ <MenuActionItem label="Rename" value="rename" onSelect={actions.rename} />+ {/* The caller's own `disabled` must not hide the reason. */}+ <MenuActionItem+ disabled+ label="Copy JSON"+ unavailableReason={REASON}+ value="copy-json"+ onSelect={actions.copyJson}+ />+ <MenuItem+ aria-describedby="copy-path-hint"+ unavailableReason={REASON}+ value="copy-path"+ onClick={actions.copyPath}+ >+ <CopyIcon />+ <Menu.ItemText>Copy path</Menu.ItemText>+ </MenuItem>+ </Menu.Content>+ </Menu.Positioner>+ </Menu.Root>+ <p id="copy-path-hint">Copies the folder path</p>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+};++const item = (value: string): HTMLElement => document.querySelector<HTMLElement>(`[data-value="${value}"]`)!;+const tooltipText = (): string | null | undefined => document.querySelector('[role="tooltip"]')?.textContent;++const highlight = async (value: string) => {+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await vi.waitFor(() => expect(item(value).hasAttribute('data-highlighted')).toBe(true));+};++describe('unavailable menu items', () => {+ it('stay reachable by keyboard, read as disabled and described by their reason, and never act', async () => {+ const actions = handlers();+ await renderMenu(actions);++ await act(() => userEvent.click(page.getByRole('button', { name: 'Actions' })));+ await vi.waitFor(() => expect(item('rename')).toBeVisible());++ // Their name stays the label; the reason is their description, read without the tooltip, after the caller's own.+ for (const [value, name, description] of [+ ['copy-image', 'Copy image', REASON],+ ['copy-json', 'Copy JSON', REASON],+ ['copy-path', 'Copy path', `Copies the folder path ${REASON}`],+ ] as const) {+ expect(item(value).getAttribute('aria-disabled')).toBe('true');+ // One description mechanism: `aria-description` beside `aria-describedby` would be read twice by some readers.+ expect(item(value).hasAttribute('aria-description')).toBe(false);+ const menuItem = page.getByRole('menuitem', { name, exact: true });+ await expect.element(menuItem).toHaveAccessibleName(name);+ await expect.element(menuItem).toHaveAccessibleDescription(description);+ }++ // Keyboard navigation does not skip them, and highlighting shows the reason without a pointer. The icon-only+ // item shows its label beside the reason, since the tooltip is the only place its name appears.+ await highlight('copy-image');+ await vi.waitFor(() => expect(tooltipText()).toBe(`Copy image${REASON}`));+ await act(() => userEvent.keyboard('{Enter}'));++ await highlight('rename');+ await highlight('copy-json');+ await vi.waitFor(() => expect(tooltipText()).toBe(REASON));+ await act(() => userEvent.keyboard('{Enter}'));++ await highlight('copy-path');+ await vi.waitFor(() => expect(tooltipText()).toBe(REASON));+ await act(() => userEvent.keyboard('{Enter}'));+ // A pointer click on an unavailable item does nothing either.+ await act(() => item('copy-path').click());++ expect(actions.copyImage).not.toHaveBeenCalled();+ expect(actions.copyJson).not.toHaveBeenCalled();+ expect(actions.copyPath).not.toHaveBeenCalled();+ expect(actions.rootSelect).not.toHaveBeenCalled();+ // Selecting an unavailable item leaves the menu open, as a disabled one would.+ expect(item('rename')).toBeVisible();++ // The control: an available item's selection reaches both its handler and the menu root.+ await act(() => userEvent.click(item('rename')));+ expect(actions.rename).toHaveBeenCalledOnce();+ expect(actions.rootSelect).toHaveBeenCalledWith({ value: 'rename' });+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsxindex 840143b8a5..e62c65c6b7 100644--- a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx@@ -1,12 +1,12 @@import type { LucideIcon } from 'lucide-react';import type { ComponentProps, ReactNode, Ref } from 'react';-import { Box, HStack, Icon, Menu, Portal, Stack, Text, useMenuContext } from '@chakra-ui/react';+import { Box, HStack, Icon, Menu, Portal, Stack, Text, useMenuContext, useMenuItemContext } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';import { createExternalStore } from '@platform/state/externalStore';import { useCallback, useId, useMemo } from 'react';-import { IconButton } from './Button';+import { IconButton, useUnavailableControl } from './Button';import { Tooltip } from './Tooltip';import { useRegisterWidgetOverlay } from './widgetOverlays';@@ -19,6 +19,59 @@ export const MenuContent = (props: MenuContentProps) => {return stale ? null : <Menu.Content {...props} />;};+const UNAVAILABLE_REASON_POSITIONING = { placement: 'right' } as const;++/**+ * The reason an unavailable item cannot act, shown while the item is highlighted, by pointer or keyboard alike: Zag+ * highlights with `aria-activedescendant`, so the item never takes focus and a focus-opened tooltip would never show.+ * The tooltip anchors to an overlay of the whole item, so the item's own children and layout stay as the caller wrote+ * them, and the item keeps its Zag id (a tooltip trigger would take it over).+ */+const UnavailableReason = ({ label, reason }: { label: string | undefined; reason: string }) => {+ const item = useMenuItemContext();+ const content = useMemo(+ () =>+ label ? (+ <Stack gap="0">+ <Text>{label}</Text>+ <Text color="fg.muted">{reason}</Text>+ </Stack>+ ) : (+ reason+ ),+ [label, reason]+ );+ return (+ <Tooltip content={content} open={item.highlighted} positioning={UNAVAILABLE_REASON_POSITIONING}>+ <Box aria-hidden inset="0" pointerEvents="none" position="absolute" />+ </Tooltip>+ );+};++export type MenuItemProps = ComponentProps<typeof Menu.Item> & {+ /**+ * Why the item cannot act now (say, no clipboard on a plain-HTTP origin). It reads as disabled (`aria-disabled`,+ * described by the reason) but stays highlightable, where Zag's `disabled` would skip it in keyboard navigation; no+ * selection gets through (neither its handlers nor the menu root's `onSelect`, and the menu stays open); and the+ * reason shows beside it while highlighted. An item named only by `aria-label` shows that name with the reason. The+ * reason wins over `disabled`, which would make it unreachable.+ */+ unavailableReason?: string;+};++/** `Menu.Item`, plus the unavailable state. */+export const MenuItem = ({ children, disabled, unavailableReason, ...props }: MenuItemProps) => {+ const unavailable = useUnavailableControl(unavailableReason, props['aria-describedby']);++ return (+ <Menu.Item {...props} {...unavailable?.props} disabled={unavailable ? undefined : disabled}>+ {children}+ {unavailableReason ? <UnavailableReason label={props['aria-label']} reason={unavailableReason} /> : null}+ {unavailable?.description}+ </Menu.Item>+ );+};+export interface MenuActionItemProps {value: string;label: string;@@ -29,6 +82,8 @@ export interface MenuActionItemProps {iconColor?: string;tone?: 'danger';disabled?: boolean;+ /** See `MenuItem`. */+ unavailableReason?: string;/** Trailing keycaps; the caller renders them, since key glyphs are a workbench concern. */shortcut?: ReactNode;onSelect: () => void;@@ -46,15 +101,10 @@ export const MenuActionItem = ({onSelect,shortcut,tone,+ unavailableReason,value,-}: MenuActionItemProps) => (- <Menu.Item- {...(hint ? TWO_LINE_ITEM : undefined)}- data-danger={tone === 'danger' ? '' : undefined}- disabled={disabled}- value={value}- onSelect={onSelect}- >+}: MenuActionItemProps) => {+ const content = (<HStack alignItems={hint ? 'flex-start' : 'center'} gap={hint ? '2.5' : '2'} minW="0" w="full">{icon ? (<Icon@@ -80,8 +130,21 @@ export const MenuActionItem = ({)}{shortcut}</HStack>- </Menu.Item>-);+ );++ return (+ <MenuItem+ {...(hint ? TWO_LINE_ITEM : undefined)}+ data-danger={tone === 'danger' ? '' : undefined}+ disabled={disabled}+ unavailableReason={unavailableReason}+ value={value}+ onSelect={onSelect}+ >+ {content}+ </MenuItem>+ );+};const ICON_ITEM_TOOLTIP_CONTENT_PROPS = { fontSize: 'xs' } as const;const ICON_ITEM_TOOLTIP_POSITIONING_PROPS = { placement: 'top' } as const;@@ -95,33 +158,56 @@ export interface MenuIconItemProps {iconFill?: string;tone?: 'danger';disabled?: boolean;+ /** See `MenuItem`; the reason's tooltip names the item too. */+ unavailableReason?: string;onSelect: () => void;}/** Wrap the icon, not Menu.Item: tooltip IDs would replace Zag's selection ID and prevent onSelect. */-export const MenuIconItem = ({ disabled, icon, iconFill, label, onSelect, tone, value }: MenuIconItemProps) => (- <Menu.Item- aria-label={label}- data-danger={tone === 'danger' ? '' : undefined}- disabled={disabled}- flex="1"- justifyContent="center"- value={value}- onSelect={onSelect}- >- <Tooltip- showArrow- content={label}- contentProps={ICON_ITEM_TOOLTIP_CONTENT_PROPS}- openDelay={300}- positioning={ICON_ITEM_TOOLTIP_POSITIONING_PROPS}+export const MenuIconItem = ({+ disabled,+ icon,+ iconFill,+ label,+ onSelect,+ tone,+ unavailableReason,+ value,+}: MenuIconItemProps) => {+ const glyph = (+ <Box alignItems="center" display="flex" h="full" justifyContent="center" w="full">+ <Icon as={icon} boxSize="4" color={tone === 'danger' ? undefined : 'fg'} fill={iconFill ?? 'none'} />+ </Box>+ );++ return (+ <MenuItem+ aria-label={label}+ data-danger={tone === 'danger' ? '' : undefined}+ disabled={disabled}+ flex="1"+ justifyContent="center"+ unavailableReason={unavailableReason}+ value={value}+ onSelect={onSelect}>- <Box alignItems="center" display="flex" h="full" justifyContent="center" w="full">- <Icon as={icon} boxSize="4" color={tone === 'danger' ? undefined : 'fg'} fill={iconFill ?? 'none'} />- </Box>- </Tooltip>- </Menu.Item>-);+ {/* The reason's tooltip names an unavailable item, so the hover label would only repeat it. */}+ {unavailableReason ? (+ glyph+ ) : (+ <Tooltip+ showArrow+ content={label}+ contentProps={ICON_ITEM_TOOLTIP_CONTENT_PROPS}+ openDelay={300}+ positioning={ICON_ITEM_TOOLTIP_POSITIONING_PROPS}+ >+ {glyph}+ </Tooltip>+ )}+ </MenuItem>+ );+};export interface IconRadioMenuOption<Value extends string> {value: Value;diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsxindex f73bafd8b7..b2226670a1 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx@@ -43,6 +43,7 @@ let root: Root | null = null;// Reset the pointer after each test so a newly mounted trigger cannot open under the previous test's cursor.afterEach(async () => {+ vi.useRealTimers();await act(() => root?.unmount());host?.remove();host = null;@@ -169,11 +170,20 @@ describe('FeatureHint', () => {it('opens the card with its heading and paragraphs on hover', async () => {const trigger = await render({ enabled: true, onDisable: vi.fn() });+ // The open delay runs on a fake clock: on a loaded machine the hover itself can outlast it.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });await act(async () => {await userEvent.hover(trigger);});- // Guard against a false pass from an instantly-open card.+ // Guard against a false pass from an instantly-open card: a pointer brushing past the label opens nothing.+ await act(() => {+ vi.advanceTimersByTime(100);+ });expect(cardText()).toBe('');+ await act(() => {+ vi.runOnlyPendingTimers();+ });+ vi.useRealTimers();await waitForCard();expect(cardText()).toContain('CLIP Skip');@@ -262,13 +272,22 @@ describe('FeatureHint', () => {const exit = { x: label.right - 2, y: label.top + label.height / 2 };// Short of the card and clear of its arrow, which points at the label and counts as the card.const pause = { x: card.left - 4, y: exit.y + 24 };-+ const advance = (ms: number) =>+ act(() => {+ vi.advanceTimersByTime(ms);+ });++ // Fake time from here, so the rest lasts exactly 400ms: on the real clock, slow pointer moves on a loaded machine+ // stretched it past the corridor's grace window.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });// A pause that outlasts the close delay: only the corridor keeps the card open through it.await movePointerAlong(exit, pause, MOVE);- await settle(400);+ await advance(400);await movePointerAlong(pause, { x: to.left + to.width / 2, y: to.top + to.height / 2 }, MOVE);- await settle(500);+ await advance(500);+ // The state, not just the text: a closing card keeps its content through the exit animation.+ expect(trigger.getAttribute('data-state')).toBe('open');expect(cardText()).toContain('Learn more');expect(document.elementFromPoint(to.left + to.width / 2, to.top + to.height / 2)?.closest('a')).toBe(link);});diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts b/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.tsindex 780338e90a..0de444a95f 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts+++ b/invokeai/frontend/webv2/src/platform/ui/hints/featureHint.testing.ts@@ -1,4 +1,5 @@import { act } from 'react';+import { vi } from 'vitest';import { userEvent } from 'vitest/browser';const FRAME_MS = 16;@@ -53,9 +54,33 @@ export const openHintCard = async (trigger: Element, timeoutMs = 5000): Promise<type Point = { x: number; y: number };+/**+ * The probe sits on top of everything, so hovering it is also a leave from whatever lies beneath (the card, say). The+ * browser recomputes hover in the next frame and re-enters that element; wait for it, or a close the leave scheduled+ * can fire first. Bounded by a second frame: by then the recomputation has run, and a step that never put the+ * pointer over the probe has nothing to re-enter.+ */+const pointerUncovered = (): Promise<void> =>+ new Promise<void>((resolve) => {+ let frame = 0;+ const done = () => {+ document.removeEventListener('pointerover', done, true);+ cancelAnimationFrame(frame);+ resolve();+ };++ document.addEventListener('pointerover', done, true);+ frame = requestAnimationFrame(() => {+ frame = requestAnimationFrame(done);+ });+ });+/*** Walk the real pointer from `from` to `to` in straight steps, one pointermove per step: a single hover jumps, which* never crosses the space between a label and its card.+ *+ * Under fake timers each step advances the clock by exactly `stepDelayMs`, so the walk's timing no longer depends on+ * how long the browser takes to move the pointer.*/export const movePointerAlong = async (from: Point,@@ -71,11 +96,20 @@ export const movePointerAlong = async (probe.style.cssText = `position:fixed;left:${x - 1}px;top:${y - 1}px;width:2px;height:2px;z-index:2147483647`;document.body.append(probe);await act(() => userEvent.hover(probe));+probe.remove();- await act(async () => {- await new Promise<void>((resolve) => {- globalThis.setTimeout(resolve, stepDelayMs);+ await act(() => pointerUncovered());++ if (vi.isFakeTimers()) {+ await act(() => {+ vi.advanceTimersByTime(stepDelayMs);});- });+ } else {+ await act(async () => {+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, stepDelayMs);+ });+ });+ }}};diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/ToastContrast.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/theme/ToastContrast.browser.test.tsxindex 38569b8444..2b3adc1ead 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/ToastContrast.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/theme/ToastContrast.browser.test.tsx@@ -36,7 +36,12 @@ describe('toast contrast', () => {);});await act(() => {- toaster.create({ description: 'Layer thumbnail rasterization failed.', title: 'Error', type });+ toaster.create({+ description: 'Layer thumbnail rasterization failed.',+ duration: Infinity,+ title: 'Error',+ type,+ });});await expect.poll(() => document.querySelector('[data-part="description"]')).not.toBeNull();const description = document.querySelector<HTMLElement>('[data-part="description"]')!;@@ -93,6 +98,8 @@ describe('toast contrast', () => {{ label: 'Retry', onClick: () => {} },{ label: 'Show in Gallery', onClick: () => {} },],+ // Success toasts expire after 2s; a loaded machine can take longer to hover every button.+ duration: Infinity,title: 'Saved',type,});diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.tsindex 5c7198e883..37ea1bd205 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts@@ -262,8 +262,24 @@ const highContrastConditions = {const motionDurationToken = (base: string): TokenValue => ({ value: { base, _reduceMotion: '1ms' } });const motionAnimationToken = (base: string): TokenValue => ({ value: { base, _reduceMotion: 'none' } });+/**+ * Chakra's hover and active exclude only native and `data-disabled` controls. An `aria-disabled` one (kept focusable+ * so it can explain itself) must not respond to the pointer either. Nor may it look expanded: a tooltip marks its+ * trigger expanded while open, and buttons give expanded their hover fill, so showing the reason would tint it.+ */+const interactionConditions = {+ hover: ['@media (hover: hover)', '&:is(:hover, [data-hover]):not(:disabled, [data-disabled], [aria-disabled=true])'],+ active: '&:is(:active, [data-active]):not(:disabled, [data-disabled], [aria-disabled=true], [data-state=open])',+ expanded: '&:is([aria-expanded=true], [data-expanded], [data-state=expanded]):not([aria-disabled=true])',+};+const config = defineConfig({- conditions: { ...themeConditions, ...highContrastConditions, reduceMotion: ':root[data-reduce-motion=true]' },+ conditions: {+ ...themeConditions,+ ...highContrastConditions,+ ...interactionConditions,+ reduceMotion: ':root[data-reduce-motion=true]',+ },globalCss: {'html, body, #root': {height: '100%',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex 95b68ba6d4..a64deac581 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@ -354,10 +354,13 @@ describe('importGalleryImagesToCanvas', () => {});expect(result.status).toBe('imported');- expect(fetchImage.mock.calls.map(([url]) => url)).toEqual([- 'https://images.example/wide.png',- 'https://images.example/square.png',+ // The fixture URLs name another origin, as a selection saved elsewhere does: the fetch derives from the name.+ const fetchedUrls = fetchImage.mock.calls.map(([url]) => String(url));+ expect(fetchedUrls).toEqual([+ expect.stringMatching(/\/api\/v1\/images\/i\/wide\.png\/full$/),+ expect.stringMatching(/\/api\/v1\/images\/i\/square\.png\/full$/),]);+ expect(fetchedUrls.join()).not.toContain('images.example');expect(uploadImage).toHaveBeenCalledTimes(2);expect(uploadImage.mock.calls.map(([, options]) => options)).toEqual([expect.objectContaining({diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.tsindex 6416ea9a34..4ac9fa5bc6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts@@ -5,6 +5,7 @@ import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engiimport type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import type { Project } from '@workbench/projectContracts';+import { galleryImageUrls } from '@features/gallery/utility';import { getArchitectureCapabilitiesSnapshot } from '@features/generation/runtime';import {calculateNewSize,@@ -185,7 +186,8 @@ const resizeImages = async (const dimensions = getGenerationDimensions(generateValues?.model);const results = await mapWithConcurrency(images, 4, async (image): Promise<ResizeResult> => {try {- const response = await fetchImage(image.imageUrl, { signal });+ // Derived from the name, never the caller's cached URL: a URL saved at another origin is a cross-origin fetch.+ const response = await fetchImage(galleryImageUrls.full(image.imageName), { signal });signal.throwIfAborted();if (!response.ok) {diff --git a/invokeai/frontend/webv2/src/workbench/diagnostics/DiagnosticsPanel.tsx b/invokeai/frontend/webv2/src/workbench/diagnostics/DiagnosticsPanel.tsxindex 11c25b828a..7b492fe8d4 100644--- a/invokeai/frontend/webv2/src/workbench/diagnostics/DiagnosticsPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/diagnostics/DiagnosticsPanel.tsx@@ -8,6 +8,7 @@ import type {} from '@platform/logging/contracts';import { Badge, Box, createListCollection, HStack, Icon, Input, InputGroup, Stack, Text } from '@chakra-ui/react';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { downloadText } from '@platform/browser/downloadBlob';import { LOG_LEVEL_ORDER, LOG_NAMESPACES, matchesLogScope } from '@platform/logging/contracts';import { createLogExport } from '@platform/logging/export';@@ -247,17 +248,11 @@ export const DiagnosticsPanel = ({ projectId }: { projectId: string | null }) =>),[config, matched, scope, snapshot.retention]);+ const canCopy = canCopyText();const copyFiltered = useCallback(() => {const count = matched.length;- const clipboard = navigator.clipboard;- if (!clipboard) {- toaster.create({ title: t('widgets.diagnostics.copyFailed'), type: 'error' });-- return;- }-- clipboard.writeText(buildExport()).then(+ copyText(buildExport()).then(() => toaster.create({ duration: 2500, title: t('widgets.diagnostics.copied', { count }), type: 'success' }),() => toaster.create({ title: t('widgets.diagnostics.copyFailed'), type: 'error' }));@@ -329,7 +324,13 @@ export const DiagnosticsPanel = ({ projectId }: { projectId: string | null }) =><RecordingStatus config={config} snapshot={snapshot} /><HStack flexWrap="wrap" gap="2" justify="space-between"><HStack flexWrap="wrap" gap="2">- <Button disabled={matched.length === 0} size="sm" variant="outline" onClick={copyFiltered}>+ <Button+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}+ disabled={matched.length === 0}+ size="sm"+ variant="outline"+ onClick={copyFiltered}+ >{t('widgets.diagnostics.copyFiltered', { count: matched.length })}</Button><Button disabled={matched.length === 0} size="sm" variant="outline" onClick={downloadFiltered}>diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.modal.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.modal.browser.test.tsxindex 18ea3a4b3f..fcf669824a 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.modal.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.modal.browser.test.tsx@@ -16,7 +16,7 @@ import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';import { createWorkbenchStore } from '@workbench/workbenchStore';import { act, StrictMode, useCallback } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';/**@@ -225,6 +225,12 @@ describe('WorkbenchHotkeyRuntime under a modal dialog', () => {});it('runs nothing behind for the Escape or Enter that closes a dialog, and the next press reaches it', async () => {+ // The next press lands while the closed dialog is still animating out; on a loaded machine a real-length exit+ // animation can end before then, so it is held for the whole test.+ const holdExit = document.createElement('style');+ holdExit.textContent = '[role="alertdialog"][data-state="closed"] { animation-duration: 3600s !important; }';+ document.head.append(holdExit);+ onTestFinished(() => holdExit.remove());await openConfirm();await userEvent.keyboard('{Escape}');expect(ran).toEqual([]);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex de5f4931b4..f176cc8b52 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -11,8 +11,10 @@ import {toGalleryItemKey,} from '@features/gallery';import { galleryKeys } from '@features/gallery/queries';+import { canCopyImage } from '@platform/browser/clipboard';import { captureAccountScope } from '@platform/state/accountLifecycle';import { MenuContent, MenuIconItem } from '@platform/ui';+import { MenuItem } from '@platform/ui/Menu';import { useQuery } from '@tanstack/react-query';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';@@ -496,9 +498,11 @@ const SingleItemMenuItems = ({{item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (<><ContextMenuItem+ // Without a clipboard (plain HTTP) the item says why; a frame still loading only disables it.disabled={!previewVideoActions.isCopyCurrentFrameAvailable}icon={CopyIcon}label={t('widgets.preview.copyCurrentFrame')}+ unavailableReason={canCopyImage() ? undefined : t('common.copyUnavailable')}value="copy-current-video-frame"onClick={previewVideoActions.onCopyCurrentFrame}/>@@ -903,9 +907,18 @@ const OpenInNewTabQuickMenuItem = ({ image }: { image: GalleryImage }) => {};const CopyQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {+ const { t } = useTranslation();const handleClick = useCallback(() => void actions.copyImage(image), [actions, image]);- return <MenuIconItem icon={CopyIcon} label="Copy to clipboard" value="copy-to-clipboard" onSelect={handleClick} />;+ return (+ <MenuIconItem+ icon={CopyIcon}+ label="Copy to clipboard"+ unavailableReason={canCopyImage() ? undefined : t('common.copyUnavailable')}+ value="copy-to-clipboard"+ onSelect={handleClick}+ />+ );};const DownloadQuickMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {@@ -1142,6 +1155,7 @@ const ContextMenuItem = ({iconFill,isDanger,label,+ unavailableReason,value,onClick,}: {@@ -1151,15 +1165,23 @@ const ContextMenuItem = ({iconFill?: string;isDanger?: boolean;label: string;+ /** Why the item cannot act now; see `MenuItem`. */+ unavailableReason?: string;value: string;onClick?: () => void;}) => (- <Menu.Item data-danger={isDanger ? '' : undefined} disabled={disabled} value={value} onClick={onClick}>+ <MenuItem+ data-danger={isDanger ? '' : undefined}+ disabled={disabled}+ unavailableReason={unavailableReason}+ value={value}+ onClick={onClick}+ ><HStack gap="2" minW="0" w="full"><Icon as={icon} boxSize="3.5" color={isDanger ? undefined : 'fg.subtle'} fill={iconFill} flexShrink={0} /><Text flex="1" fontSize="md">{label}</Text></HStack>- </Menu.Item>+ </MenuItem>);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex e59220f543..f19ed50f3b 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -36,6 +36,7 @@ import { setPendingPromptTemplateDraft } from '@features/generation/react';import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { getMaxReferenceImages, isVaeModelConfig, isSupportedGenerateModel } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';+import { copyImage } from '@platform/browser/clipboard';import { downloadBlob } from '@platform/browser/downloadBlob';import { useMountEffect } from '@platform/react/useMountEffect';import {@@ -864,7 +865,7 @@ export const useImageActions = ({const blob = await toPngBlob(sourceBlob);assertAccountScopeCurrent(owner);- await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);+ await copyImage(blob);assertAccountScopeCurrent(owner);recordSuccess('Copied image to clipboard');} catch (error: unknown) {diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsxindex 57f6f7abc4..dfcfd0855b 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.browser.test.tsx@@ -27,6 +27,11 @@ const translations: Record<string, string> = {'launchpad.browserIssues.canvasReadbackIntegrity.title': 'Canvas protection may corrupt painted strokes','launchpad.browserIssues.copyFailed': 'Could not copy browser setting','launchpad.browserIssues.copySetting': 'Copy browser setting',+ 'common.copyUnavailable': 'Copying needs HTTPS or localhost',+ 'launchpad.browserIssues.dismiss': 'Dismiss',+ 'launchpad.browserIssues.plainHttpLimits.description': 'Invoke is open over plain HTTP from a network address.',+ 'launchpad.browserIssues.plainHttpLimits.title': 'Some features are limited on this address',+ 'launchpad.browserIssues.plainHttpLimits.workaround': 'Open Invoke at localhost, or serve it over HTTPS.','launchpad.browserIssues.settingCopied': 'Browser setting copied',};@@ -38,7 +43,7 @@ vi.mock('react-i18next', () => ({import { KnownBrowserIssuesAlert } from './KnownBrowserIssuesAlert';-const [CANVAS_ISSUE] = KNOWN_BROWSER_ISSUES;+const [CANVAS_ISSUE, PLAIN_HTTP_ISSUE] = KNOWN_BROWSER_ISSUES;const createDetectedIssue = (...workaroundIds: readonly string[]): DetectedBrowserIssue => {const { detect: _detect, ...issue } = CANVAS_ISSUE;@@ -49,6 +54,23 @@ const createDetectedIssue = (...workaroundIds: readonly string[]): DetectedBrows};};+const createPlainHttpIssue = (): DetectedBrowserIssue => {+ const { detect: _detect, ...issue } = PLAIN_HTTP_ISSUE;++ return issue;+};++const DISMISSED_KEY = 'invokeai:v7:webv2:browser-issue-dismissed:plain-http-limits';++const findButton = (name: string): HTMLButtonElement | null =>+ host?.querySelector<HTMLButtonElement>(`button[aria-label="${name}"]`) ?? null;++const remount = async (): Promise<void> => {+ await act(() => root?.unmount());+ root = createRoot(host!);+ await renderAlert();+};+let host: HTMLDivElement | null = null;let root: Root | null = null;let originalClipboardDescriptor: PropertyDescriptor | undefined;@@ -65,6 +87,7 @@ const renderAlert = async (): Promise<void> => {};beforeEach(() => {+ window.localStorage.removeItem(DISMISSED_KEY);detectKnownBrowserIssuesMock.mockReset();detectKnownBrowserIssuesMock.mockReturnValue([]);originalClipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');@@ -95,7 +118,7 @@ describe('known browser issues alert', () => {await renderAlert();expect(detectKnownBrowserIssuesMock).toHaveBeenCalledOnce();- expect(host?.querySelector('[role="alert"]')).toBeNull();+ expect(host?.querySelector('[role="status"]')).toBeNull();expect(document.body.childElementCount).toBe(bodyChildCount);});@@ -104,7 +127,7 @@ describe('known browser issues alert', () => {await renderAlert();- const alert = host?.querySelector('[role="alert"]');+ const alert = host?.querySelector('[role="status"]');const copyButton = host?.querySelector<HTMLButtonElement>('button[aria-label="Copy browser setting"]');expect(alert).not.toBeNull();@@ -112,7 +135,8 @@ describe('known browser issues alert', () => {expect(alert?.textContent).toContain('disable “[Helium Noise] Canvas pixel noising”');expect(alert?.textContent).toContain('canvas-protection extension');expect(alert?.textContent).toContain('helium://flags/#helium-noise-canvas');- expect(copyButton?.title).toBe('Copy browser setting');+ expect(copyButton?.hasAttribute('title')).toBe(false);+ // The readback alert stays until the browser is fixed: no dismiss control.expect(host?.querySelectorAll('button')).toHaveLength(1);});@@ -121,7 +145,7 @@ describe('known browser issues alert', () => {await renderAlert();- const alert = host?.querySelector('[role="alert"]');+ const alert = host?.querySelector('[role="status"]');expect(alert?.textContent).toContain('turn Shields off for this site');expect(alert?.textContent).not.toContain('Helium');@@ -144,4 +168,73 @@ describe('known browser issues alert', () => {expect(writeText).toHaveBeenCalledWith('helium://flags/#helium-noise-canvas');});++ it('remembers a dismissed plain-HTTP notice across reloads and moves focus to the page heading', async () => {+ const heading = document.createElement('h1');+ heading.textContent = 'Welcome to Invoke';+ host!.before(heading);+ detectKnownBrowserIssuesMock.mockReturnValue([createPlainHttpIssue()]);++ try {+ await renderAlert();+ expect(host?.textContent).toContain('Some features are limited on this address');++ await act(() => userEvent.click(findButton('Dismiss')!));++ expect(host?.querySelector('[role="status"]')).toBeNull();+ expect(document.activeElement).toBe(heading);+ expect(window.localStorage.getItem(DISMISSED_KEY)).toBe('true');++ await remount();+ expect(host?.querySelector('[role="status"]')).toBeNull();+ } finally {+ heading.remove();+ }+ });++ it('moves focus to the next alert when one of several is dismissed', async () => {+ detectKnownBrowserIssuesMock.mockReturnValue([createPlainHttpIssue(), createDetectedIssue('other-browser')]);++ await renderAlert();+ await act(() => userEvent.click(findButton('Dismiss')!));++ expect(host?.querySelectorAll('[role="status"]')).toHaveLength(1);+ expect(document.activeElement?.getAttribute('data-browser-issue')).toBe('canvas-readback-integrity');+ });++ it('hides the notice for this page and shows it again next time when storage throws', async () => {+ const getItem = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new DOMException('Storage disabled', 'SecurityError');+ });+ const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new DOMException('Storage disabled', 'SecurityError');+ });+ detectKnownBrowserIssuesMock.mockReturnValue([createPlainHttpIssue()]);++ try {+ await renderAlert();+ await act(() => userEvent.click(findButton('Dismiss')!));+ expect(host?.querySelector('[role="status"]')).toBeNull();++ await remount();+ expect(host?.querySelector('[role="status"]')).not.toBeNull();+ } finally {+ getItem.mockRestore();+ setItem.mockRestore();+ }+ });++ it('keeps the copy control, disabled with its reason, when the clipboard is unavailable', async () => {+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });+ detectKnownBrowserIssuesMock.mockReturnValue([createDetectedIssue('helium')]);++ await renderAlert();+ const copyButton = findButton('Copy browser setting');++ expect(copyButton?.getAttribute('aria-disabled')).toBe('true');+ // Pointer tooling refuses aria-disabled targets; a click still reaches the element and must do nothing.+ await act(() => copyButton!.click());+ await act(() => userEvent.hover(copyButton!));+ await vi.waitFor(() => expect(document.body.textContent).toContain('Copying needs HTTPS or localhost'));+ });});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsxindex def243d819..67d37e6e62 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/KnownBrowserIssuesAlert.tsx@@ -1,36 +1,102 @@import { Alert, Code, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { canCopyText, copyText } from '@platform/browser/clipboard';import {detectKnownBrowserIssues,type DetectedBrowserIssue,+ type KnownBrowserIssueId,type KnownBrowserIssueWorkaround,} from '@platform/browser/knownBrowserIssues';-import { IconButton, toaster } from '@platform/ui';-import { CopyIcon } from 'lucide-react';-import { useCallback, useState } from 'react';+import { IconButton } from '@platform/ui/Button';+import { toaster } from '@platform/ui/toaster';+import { Tooltip } from '@platform/ui/Tooltip';+import { CopyIcon, XIcon } from 'lucide-react';+import { useCallback, useRef, useState } from 'react';+import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';+/** Per origin by nature of `localStorage`, so another address the viewer opens shows the notice again. */+const DISMISSED_STORAGE_KEY_PREFIX = 'invokeai:v7:webv2:browser-issue-dismissed:';++const isRememberedDismissed = (id: KnownBrowserIssueId): boolean => {+ try {+ return window.localStorage.getItem(`${DISMISSED_STORAGE_KEY_PREFIX}${id}`) === 'true';+ } catch {+ return false;+ }+};++const rememberDismissed = (id: KnownBrowserIssueId): void => {+ try {+ window.localStorage.setItem(`${DISMISSED_STORAGE_KEY_PREFIX}${id}`, 'true');+ } catch {+ // Storage unavailable: the notice is hidden for this page and shows again on the next visit.+ }+};++/** The page heading above the alerts, where focus goes once the last one is dismissed. */+const findPrecedingHeading = (element: HTMLElement): HTMLElement | null =>+ [...document.querySelectorAll<HTMLElement>('h1, h2')]+ .filter((heading) => heading.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING)+ .at(-1) ?? null;+export const KnownBrowserIssuesAlert = () => {// The probe is cheap and its result is fixed for the page's lifetime, so it runs once per mount.const [issues] = useState(() => detectKnownBrowserIssues());+ const [dismissedIds, setDismissedIds] = useState<ReadonlySet<KnownBrowserIssueId>>(+ () => new Set(issues.filter((issue) => issue.dismissible && isRememberedDismissed(issue.id)).map(({ id }) => id))+ );+ const stackRef = useRef<HTMLDivElement | null>(null);+ const dismiss = useCallback((id: KnownBrowserIssueId) => {+ rememberDismissed(id);+ const stack = stackRef.current;+ const alerts = stack ? [...stack.querySelectorAll<HTMLElement>('[data-browser-issue]')] : [];+ const index = alerts.findIndex((alert) => alert.dataset.browserIssue === id);+ // Focus never falls to the body: the next alert, else the previous one, else the page heading.+ const nextFocus = alerts[index + 1] ?? alerts[index - 1] ?? (stack ? findPrecedingHeading(stack) : null);++ flushSync(() => setDismissedIds((previous) => new Set(previous).add(id)));+ if (nextFocus) {+ if (!nextFocus.hasAttribute('tabindex')) {+ nextFocus.tabIndex = -1;+ }+ nextFocus.focus();+ }+ }, []);+ const visible = issues.filter((issue) => !dismissedIds.has(issue.id));- if (issues.length === 0) {+ if (visible.length === 0) {return null;}return (- <Stack gap="2">- {issues.map((issue) => (- <BrowserIssueAlert issue={issue} key={issue.id} />+ <Stack ref={stackRef} gap="2">+ {visible.map((issue) => (+ <BrowserIssueAlert issue={issue} key={issue.id} onDismiss={issue.dismissible ? dismiss : undefined} />))}</Stack>);};-const BrowserIssueAlert = ({ issue }: { issue: DetectedBrowserIssue }) => {+const BrowserIssueAlert = ({+ issue,+ onDismiss,+}: {+ issue: DetectedBrowserIssue;+ onDismiss?: (id: KnownBrowserIssueId) => void;+}) => {const { t } = useTranslation();+ const handleDismiss = useCallback(() => onDismiss?.(issue.id), [issue.id, onDismiss]);return (- <Alert.Root borderRadius="md" role="alert" status={issue.severity} variant="surface">+ <Alert.Root+ borderRadius="md"+ data-browser-issue={issue.id}+ // A standing notice present on every visit, not an event: polite, so it never interrupts a screen reader.+ role="status"+ status={issue.severity}+ tabIndex={-1}+ variant="surface"+ ><Alert.Indicator alignSelf="start" mt="0.5" /><Alert.Content gap="2" minW="0"><Stack gap="0.5">@@ -43,6 +109,20 @@ const BrowserIssueAlert = ({ issue }: { issue: DetectedBrowserIssue }) => {))}</Stack></Alert.Content>+ {onDismiss ? (+ <Tooltip content={t('launchpad.browserIssues.dismiss')}>+ <IconButton+ alignSelf="start"+ aria-label={t('launchpad.browserIssues.dismiss')}+ flexShrink={0}+ size="sm"+ variant="ghost"+ onClick={handleDismiss}+ >+ <Icon as={XIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ ) : null}</Alert.Root>);};@@ -62,13 +142,10 @@ const BrowserIssueWorkaround = ({ workaround }: { workaround: KnownBrowserIssueWconst CopyableBrowserSetting = ({ value }: { value: string }) => {const { t } = useTranslation();+ const canCopy = canCopyText();const copySetting = useCallback(async () => {try {- if (!navigator.clipboard) {- throw new Error('Clipboard API unavailable');- }-- await navigator.clipboard.writeText(value);+ await copyText(value);toaster.create({title: t('launchpad.browserIssues.settingCopied'),type: 'success',@@ -98,10 +175,11 @@ const CopyableBrowserSetting = ({ value }: { value: string }) => {{value}</Code><IconButton+ tooltip={t('launchpad.browserIssues.copySetting')}+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}aria-label={t('launchpad.browserIssues.copySetting')}flexShrink={0}size="sm"- title={t('launchpad.browserIssues.copySetting')}variant="ghost"onClick={handleCopy}>diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdindex 944ea26fea..f40e974149 100644--- a/invokeai/frontend/webv2/src/workbench/projects/README.md+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -6,6 +6,8 @@ Backend project record is authoritative. Writes use `expected_revision`; diverge`ProjectDocumentV3` allowlists editable document fields. Optional fields added within schema 3 (`lastFloatingGeometry`, `presetWorkingLayouts`) are additive: absent means none, so older schema-3 documents load unchanged, and a build predating a field ignores it and drops it from the next document it saves to the server instead of refusing the project (a schema bump would refuse it). Queue runs, events, undo and per-workflow edit histories are not project documents. Documents capped at 32 MiB of UTF-8 JSON on both sides of the API.+Stored media URLs are derived, never authoritative: the name beside each one is. A URL names the origin that saved it (`http://localhost:9090/...`), which another origin or computer cannot reach, and `.invk` transfer blanks it. So every load (`deserializeProjectDocument`: server records, drafts, `.invk` import, duplication) rebuilds each image and video URL the document stores (gallery selection, compare and recents in every gallery instance, canvas staging candidates, regional reference images in the canvas and its snapshots) from its name for the deployment the page runs on (`projectMediaUrls.ts`, with Gallery's URL helpers injected). Untouched subtrees keep their identity. Sync baselines are taken from the loaded project, so the rebuild alone never saves; the next real edit saves this origin's URLs.+## Content and workspaceThe server holds a project as two documents (document schema 4): its **content**, what the project is and every member shares (name; the canvas document, its snapshots and revision counter; workflow entries), and each member's **workspace**, how they work on it (layout, widgets and generation settings, prompt history, project settings, the canvas selection and staging area, the open workflow and each workflow's last run). The browser keeps one whole document per project, in memory, drafts and the unload journal; `workbench/projects/projectHalves.ts` splits it at the server boundary and joins the two halves back when a project loads. A member with no workspace yet joins onto the workspace a new project starts with.@@ -42,7 +44,8 @@ Workbench persistence is scoped to one mounted Workbench and its account lifetim- Another tab's load reconciles only entries of pages that are gone. Page proves it still runs by its editor session's Web Lock, held until its last editor releases it or the page unloads or crashes; an entry whose writing page (the editor session it names, not the lineage it is written under) another page still holds is left in place (a merely hidden tab still writes its lineages, and staging its entry elsewhere would hand that tab's unsaved edit to another tab, where an undo could never retire it). Entry written before it named its page counts as a gone page's. Hidden page settles the entry with its own saves, or next load after it is gone recovers it. Browser that keeps a page holding its session in the back/forward cache keeps the lock held, so the entry waits until the page is restored (and saves) or evicted; one that evicts such pages (Chromium today) releases the lock, and the entry is recovered as a gone page's. Reload of same tab reclaims its session, retrying up to half a second (five retries 100 ms apart) while old document lets go, then reconciles its own entries. Two cases fall outside it. If old document holds the lock longer, reload takes a fresh session, its own entries and staged drafts count as a running page's on that load, and a later load recovers them once old document is gone. Duplicated tab waits the same half second before taking its own session; if the original reloads within it, the duplicate can take the original's session instead and then takes the original's entries and staged drafts, while reloaded original takes a fresh session. Staged drafts follow same rule: a load does not adopt, auto-open, or offer for recovery a draft whose lineage is named after another running page's session, and editor route does not count it. Draft records its lineage, not the page staging it, so it is judged by the session that lineage is named after: a lineage isolated for an unopenable draft names no page and is adopted as before. A lineage the session blob hands on (today only isolated ones) is not judged at all: loading page claims its handed-on lineage directly, whether or not the page staging it still runs. Without Web Locks (plain-HTTP deployment, say) liveness cannot be told, so every entry is reconciled and every draft adopted as before. Hidden event during save-as-new journals the source project: if page goes away before the copy exists, edit is recovered into the conflicted source and retried copy keeps its reserved document; once copy exists, source lineage has moved, so entry is discarded and copy is never written from it.- Entry the draft store cannot take waits. One for a damaged lineage waits for that lineage's cleanup, at most 7 days, then is discarded. One refused for lack of storage is applied by a later load only while its lineage is unclaimed; the load that refused it usually claims the lineage when it opens the project, and then the edit is lost. Both report degraded local recovery for that project until its next stage succeeds. Unavailable journal (database will not open, or reconciliation fails) is logged, not reported: recovery then works exactly as without the journal. A journal operation failing on its own (a deletion whose transaction could not open, say) fails alone; next hidden event journals again.- Writer settles and removes its entries when server acknowledges a generation at or above them, when document returns to what recovery holds (on next save; a hidden event meanwhile also deletes the entry, and the save still writes the mark), and when it deletes the project or discards its draft; failed removal leaves the entry settled, and one whose mark fails is retried with the next save. When an older generation is acknowledged, a newer entry is rewritten onto the acknowledged revision, as a newer staged draft is rebased. Aborted journal write is written again on next hidden event. Nothing journaled for a closed session, after account lifetime ended, for a project being deleted, or beyond 8 MiB of documents per event; larger projects rely on autosave, and the skip is logged. Editor route counts projects with entries as ones that would open, so a new project typed into and reloaded before its first save reopens.-- Queue ownership uses Web Locks. Journal writes precede submission; backend receipts make retries safe after lost responses. Accepted IDs must be durable before their receipt can expire. Fresh runs that never reached browser storage use best-effort terminal acknowledgement instead.+- Queue ownership uses Web Locks; without them a tab treats its runs as its own, with no cross-tab exclusion. Journal writes precede submission; backend receipts make retries safe after lost responses. Accepted IDs must be durable before their receipt can expire. Fresh runs that never reached browser storage use best-effort terminal acknowledgement instead.+- Project delete, conflict discard and save as new take the project's lifecycle lock, which every tab's active queue run holds shared, then check the queue-run journal. Without Web Locks (a plain-HTTP origin) they run in single-tab mode (`withSingleTabFallback` in `projectLifecycleLocks.ts`): only the journal check guards them, and the server fences the rest, since a deleted project answers every later write with 404, saves are revision-checked, and a copy reuses its reserved identity. Where the API exists, a failed lock request is refused instead, because other tabs may hold the lock. A run another tab never journaled delivers its images to Uncategorized. Queue-recovery discard has nothing on the server to fence it, so it keeps refusing there and offers export. The Launchpad tells the viewer once per origin.- Completed, failed, and cancelled runs keep exact recall values in an LRU cache, capped at 500 entries / 32 MiB. Eviction removes recall convenience, not project data or active-run recovery.- Projects with journal entries stay reachable even if another tab saved an empty session. Automatic reopening is bounded; remaining entries can be opened, exported as queue-recovery JSON, or explicitly discarded. Discarding local recovery does not cancel backend work.- Browser-storage failures do not block backend project loads or saves. Recovery warnings separate degraded local durability from successful server persistence.diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.tsindex a6e4d52522..ab6951db68 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts@@ -13,6 +13,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ProjectSummaryDTO, ProjectWithWorkspaceDTO } from './api';import type { ProjectDraftStore } from './draftStore';+import type * as projectLifecycleLocksModule from './projectLifecycleLocks';import type { WorkbenchSessionBlob } from './session';import { ProjectCreateAbsentError } from './api';@@ -40,7 +41,8 @@ const listQueueRunProjectIds = vi.hoisted(() =>));-vi.mock('./projectLifecycleLocks', () => ({+vi.mock('./projectLifecycleLocks', async (importOriginal) => ({+ ...(await importOriginal<typeof projectLifecycleLocksModule>()),acquireProjectMutationLock: vi.fn(() =>Promise.resolve({ kind: 'acquired' as const, release: () => Promise.resolve() })),@@ -404,6 +406,109 @@ describe('durable project persistence', () => {expect(api.createProject).not.toHaveBeenCalled();});+ it('resolves a conflict in this tab alone when Web Locks are unavailable, as on a plain-HTTP origin', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const draftStore = createMemoryProjectDraftStore();+ const discarded = createDraftProject([]);+ const copied = createDraftProject([discarded]);+ for (const project of [discarded, copied]) {+ api.records.set(project.id, toRecord(project, 2));+ await draftStore.stage({+ baseRevision: 1,+ documentJson: JSON.stringify(serializeProjectDocumentV3({ ...project, name: 'local edit' })),+ documentSchemaVersion: 3,+ editorSessionId: 'editor-1',+ generation: 1,+ projectId: project.id,+ updatedAt: Date.parse(now),+ writerToken: 'old-writer',+ });+ await draftStore.settleConflict(project.id, 'editor-1', 'old-writer', 1, {+ kind: 'revision',+ serverRevision: 2,+ });+ }+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: discarded.id,+ editorSessionId: 'editor-1',+ openProjectIds: [discarded.id, copied.id],+ });+ vi.mocked(acquireProjectMutationLock).mockResolvedValue({ kind: 'unavailable' });+ const saveDraftAsNew = vi.fn((input: { copyProjectId: string; name: string }) => {+ const copy = toRecord({ ...copied, id: input.copyProjectId, name: input.name });+ api.records.set(copy.project_id, copy);+ return Promise.resolve(copy);+ });+ const service = createDurableSyncedWorkbenchPersistence(owner, {+ api,+ draftStore: Promise.resolve(draftStore),+ editorSession: Promise.resolve({ id: 'editor-1', release: () => Promise.resolve() }),+ now: () => now,+ saveDraftAsNew,+ writerToken: 'writer-1',+ });+ const loaded = await service.loadWorkbench();++ await service.resolveConflictDiscard(discarded.id);+ const copy = await service.resolveConflictSaveAsNew(loaded.state.projects.find(({ id }) => id === copied.id)!);++ await expect(draftStore.get(discarded.id, 'editor-1')).resolves.toMatchObject({ kind: 'empty' });+ expect(saveDraftAsNew).toHaveBeenCalledOnce();+ expect(api.records.has(copy.targetProjectId)).toBe(true);+ });++ it('refuses conflict resolution when the lock request fails although the browser has Web Locks', async () => {+ // A secure context: other tabs can hold the lock, so a failed request is not single-tab mode.+ vi.stubGlobal('navigator', { locks: {} });+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ vi.mocked(acquireProjectMutationLock).mockResolvedValue({ kind: 'unavailable' });+ const service = createService(owner, api);++ try {+ await expect(service.resolveConflictSaveAsNew(project)).rejects.toThrow('cross-tab coordination');+ await expect(service.resolveConflictDiscard(project.id)).rejects.toThrow('cross-tab coordination');+ // The refused copy released its capture, so a retry is not reported as already saving.+ await expect(service.resolveConflictSaveAsNew(project)).rejects.toThrow('cross-tab coordination');+ } finally {+ vi.unstubAllGlobals();+ }++ expect(api.createProject).not.toHaveBeenCalled();+ });++ it('still refuses conflict resolution without Web Locks while a queue journal row exists', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const project = createDraftProject([]);+ vi.mocked(acquireProjectMutationLock).mockResolvedValue({ kind: 'unavailable' });+ vi.mocked(createAccountOwnedQueueRunJournal).mockResolvedValue({+ availability: 'available',+ acknowledgeReceipt: vi.fn(),+ listPendingReceipts: vi.fn(),+ close: vi.fn(),+ deleteForProject: vi.fn(),+ listAll: vi.fn(),+ listProjectIds: vi.fn().mockResolvedValue({ kind: 'available', projectIds: [project.id] }),+ listForProject: vi.fn().mockResolvedValue({+ entries: [{ item: {}, projectId: project.id, queueItemId: 'run-1', submissionOrder: 1 }],+ kind: 'available',+ removedCorrupt: 0,+ }),+ record: vi.fn(),+ settle: vi.fn(),+ });+ const service = createService(owner, api);++ await expect(service.resolveConflictSaveAsNew(project)).rejects.toThrow('active queue runs');+ await expect(service.resolveConflictDiscard(project.id)).rejects.toThrow('active queue runs');++ expect(api.createProject).not.toHaveBeenCalled();+ });+it('refuses conflict resolution when a dormant queue journal row exists', async () => {const owner = captureAccountScope();const api = createApi();@@ -516,6 +621,59 @@ describe('durable project persistence', () => {expect(listForProject).not.toHaveBeenCalled();});+ it('opens a project saved at another origin with media URLs of this one, without saving it', async () => {+ const owner = captureAccountScope();+ const api = createApi();+ const stale = 'http://192.168.1.5:9090/api/v1/images/i';+ const base = createDraftProject([]);+ const project: Project = {+ ...base,+ widgetInstances: {+ ...base.widgetInstances,+ gallery: {+ ...base.widgetInstances.gallery!,+ state: {+ ...base.widgetInstances.gallery!.state,+ values: {+ ...base.widgetInstances.gallery!.state.values,+ selectedImage: {+ boardId: 'none',+ category: 'general',+ createdAt: now,+ fullUrl: `${stale}/x.png/full`,+ height: 8,+ isIntermediate: false,+ kind: 'image',+ name: 'x.png',+ starred: false,+ thumbnailUrl: `${stale}/x.png/thumbnail`,+ width: 8,+ },+ },+ },+ },+ },+ };+ api.records.set(project.id, toSplitRecord(project));+ vi.mocked(api.loadSession).mockResolvedValue({+ account: createInitialWorkbenchState().account,+ activeProjectId: project.id,+ openProjectIds: [project.id],+ });+ const service = createService(owner, api);++ const loaded = await service.loadWorkbench();++ const [opened] = loaded.state.projects;+ expect(opened!.widgetInstances.gallery!.state.values.selectedImage).toMatchObject({+ fullUrl: expect.stringMatching(/^http:\/\/localhost\/api\/v1\/images\/i\/x\.png\/full$/),+ thumbnailUrl: expect.stringMatching(/^http:\/\/localhost\/api\/v1\/images\/i\/x\.png\/thumbnail$/),+ });+ await service.saveWorkbench(loaded.state);+ expect(api.updateProject).not.toHaveBeenCalled();+ expect(api.saveProjectWorkspace).not.toHaveBeenCalled();+ });+it('restores a server project with durable queue work after another tab empties the session', async () => {const owner = captureAccountScope();const api = createApi();diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.tsindex 33f0329890..d0bd517cce 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.ts@@ -90,7 +90,7 @@ import {import { assertProjectFlushed, ProjectFlushError } from './projectFlush';import { findRepeatedWorkflowItem, splitProjectDocument, toProjectCreation } from './projectHalves';import { deserializeProjectDocument, deserializeProjectRecord, isSplitProjectRecord } from './projectHydration';-import { acquireProjectMutationLock } from './projectLifecycleLocks';+import { acquireProjectMutationLock, withSingleTabFallback } from './projectLifecycleLocks';import { fetchSessionBlobStrict, serializeSessionBlob, SESSION_STATE_KEY } from './session';import { getOpenProject, reportProjectSync, reportProjectSyncEntry, resolveProjectSyncConflict } from './syncStore';import { deleteWorkbenchDatabase } from './workbenchDatabase';@@ -592,9 +592,11 @@ export const createDurableSyncedWorkbenchPersistence = (const getEditorSessionForService = () => (editorSessionPromise ??= dependencies.editorSession ?? getEditorSession());const isOtherEditorSessionLive = dependencies.isEditorSessionLive ?? isEditorSessionLive;const now = dependencies.now ?? (() => new Date().toISOString());- const getProjectMutationLock =+ const acquireMutationLock =dependencies.projectMutationLock ??((projectId: string) => acquireProjectMutationLock(owner.storageSuffix, projectId));+ const getProjectMutationLock = async (projectId: string) =>+ withSingleTabFallback(await acquireMutationLock(projectId));const openQueueRunJournal = dependencies.queueRunJournal ?? createAccountOwnedQueueRunJournal;const listQueueRunProjectIds = async (): Promise<{ kind: 'available'; projectIds: string[] } | { kind: 'unavailable' }diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts b/invokeai/frontend/webv2/src/workbench/projects/library.test.tsindex 1789acc7c9..89b8408a67 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as libraryModule from './library';import type { ProjectPushOutcome } from './projectFlush';+import type * as projectLifecycleLocksModule from './projectLifecycleLocks';import type * as syncStoreModule from './syncStore';const api = vi.hoisted(() => ({@@ -37,7 +38,10 @@ const queueJournal = vi.hoisted(() => ({vi.mock('./api', () => api);vi.mock('./invk/duplicateProject', () => duplication);-vi.mock('./projectLifecycleLocks', () => projectLocks);+vi.mock('./projectLifecycleLocks', async (importOriginal) => ({+ ...(await importOriginal<typeof projectLifecycleLocksModule>()),+ ...projectLocks,+}));vi.mock('@workbench/queue-integration/queueRunJournal', () => queueJournal);let library: typeof libraryModule;@@ -336,6 +340,42 @@ describe('library mutations', () => {expect(queueJournal.createAccountOwnedQueueRunJournal).not.toHaveBeenCalled();});+ it('deletes in this tab alone when Web Locks are unavailable, as on a plain-HTTP origin', async () => {+ projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'unavailable' });+ api.deleteProject.mockResolvedValue(undefined);++ await library.deleteLibraryProject('closed');++ expect(api.deleteProject).toHaveBeenCalledWith('closed', expect.any(AbortSignal), 'release');+ });++ it('refuses to delete when the lock request fails although the browser has Web Locks', async () => {+ // A secure context: other tabs can hold the lock, so a failed request is not single-tab mode.+ vi.stubGlobal('navigator', { locks: {} });+ projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'unavailable' });++ try {+ await expect(library.deleteLibraryProject('closed')).rejects.toThrow('cross-tab coordination');+ } finally {+ vi.unstubAllGlobals();+ }++ expect(api.deleteProject).not.toHaveBeenCalled();+ });++ it('still refuses without Web Locks while the project has journaled queue runs', async () => {+ projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'unavailable' });+ queueJournal.createAccountOwnedQueueRunJournal.mockResolvedValueOnce({+ close: vi.fn(),+ deleteForProject: vi.fn(),+ listForProject: vi.fn().mockResolvedValue({ entries: [{}], kind: 'available', removedCorrupt: 0 }),+ });++ await expect(library.deleteLibraryProject('closed')).rejects.toThrow('active queue runs');++ expect(api.deleteProject).not.toHaveBeenCalled();+ });+it('fails closed when durable queue runs cannot be verified', async () => {const release = vi.fn().mockResolvedValue(undefined);projectLocks.acquireProjectMutationLock.mockResolvedValueOnce({ kind: 'acquired', release });diff --git a/invokeai/frontend/webv2/src/workbench/projects/library.ts b/invokeai/frontend/webv2/src/workbench/projects/library.tsindex 8153f09891..ad8485c717 100644--- a/invokeai/frontend/webv2/src/workbench/projects/library.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/library.ts@@ -200,13 +200,11 @@ export const deleteLibraryProject = async (boards: DeleteProjectBoards = 'release'): Promise<void> => {const owner = captureAccountScope();- const [{ acquireProjectMutationLock }, { createAccountOwnedQueueRunJournal }] = await Promise.all([- import('./projectLifecycleLocks'),- import('@workbench/queue-integration/queueRunJournal'),- ]);+ const [{ acquireProjectMutationLock, withSingleTabFallback }, { createAccountOwnedQueueRunJournal }] =+ await Promise.all([import('./projectLifecycleLocks'), import('@workbench/queue-integration/queueRunJournal')]);assertAccountScopeCurrent(owner);const openProject = getOpenProject(projectId);- const mutationLock = await acquireProjectMutationLock(owner.storageSuffix, projectId);+ const mutationLock = withSingleTabFallback(await acquireProjectMutationLock(owner.storageSuffix, projectId));if (mutationLock.kind === 'contended') {throw new Error('Wait for active queue runs to finish before deleting this project.');}diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex 0147753c12..c35b6c2b41 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -412,6 +412,29 @@ describe('stripInstallationState', () => {expect(JSON.stringify(stripped)).not.toContain('source-install');});+ it('blanks a gallery item full URL kept outside the selection keys', () => {+ const stripped = stripInstallationState({+ widgetInstances: {+ 'preview-1': {+ state: {+ values: {+ heldItem: {+ fullUrl: 'http://source-install/api/v1/images/i/held.png/full',+ kind: 'image',+ name: 'held.png',+ thumbnailUrl: 'http://source-install/api/v1/images/i/held.png/thumbnail',+ },+ },+ },+ typeId: 'preview',+ },+ },+ });++ expect(JSON.stringify(stripped)).not.toContain('source-install');+ expect(JSON.stringify(stripped)).toContain('"name":"held.png"');+ });+/** Preserve unchanged identity and authored workflow board inputs. */it.each([['no selection', { canvas: { document: { stacks: { raster: [imageLayer('l1', 'a.png')] } } }, id: 'p1' }],diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.tsindex 5b277692bf..b805ab62c5 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.ts@@ -44,8 +44,20 @@ const INSTALLATION_STATE_KEYS: ReadonlySet<string> = new Set([...GALLERY_POSITION_KEYS,]);-/** Blank cached URLs instead of deleting keys, preserving entries while forcing URL derivation from remapped names. */-const DERIVED_URL_KEYS: ReadonlySet<string> = new Set(['imageUrl', 'thumbnailUrl', 'videoUrl']);+/**+ * The URL fields a project stores beside a media name, by record shape, each with the builder that derives it from the+ * name. Transfer blanks these keys at any depth and every load rebuilds them (`projectMediaUrls.ts`), both from these+ * lists, so the two cannot drift apart. Here, not there, because the Launchpad loads this module eagerly.+ *+ * A generated-image record's, beside its `imageName`.+ */+export const GENERATED_IMAGE_URL_FIELDS = { imageUrl: 'full', thumbnailUrl: 'thumbnail' } as const;++/** A gallery item's URL fields, beside its `name` and `kind`. */+export const GALLERY_ITEM_URL_FIELDS = { fullUrl: 'full', thumbnailUrl: 'thumbnail' } as const;++const isDerivedMediaUrlKey = (key: string): boolean =>+ Object.hasOwn(GENERATED_IMAGE_URL_FIELDS, key) || Object.hasOwn(GALLERY_ITEM_URL_FIELDS, key);export type ProjectAssetRefs = MediaNameRefs;@@ -267,7 +279,9 @@ export const stripInstallationState = (projectDocument: Record<string, unknown>)return { drop: true };}- return DERIVED_URL_KEYS.has(key) && typeof value === 'string' ? { value: '' } : null;+ // Blank derived URLs instead of deleting their keys: entries survive, and each load derives them from the+ // (remapped) names again.+ return isDerivedMediaUrlKey(key) && typeof value === 'string' ? { value: '' } : null;}) as Record<string, unknown>;export interface ProjectAssetMappings {diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts b/invokeai/frontend/webv2/src/workbench/projects/projectHydration.tsindex b574ff58d7..30e83beb59 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectHydration.ts@@ -1,5 +1,6 @@import type { Project, ProjectLoadResult } from '@workbench/projectContracts';+import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';import { createDraftProject, loadWorkbenchProject, withAuthoritativeProjectBoard } from '@workbench/workbenchState';import type { ProjectWithWorkspaceDTO } from './api';@@ -12,6 +13,7 @@ import {type ProjectDocumentMigration,} from './projectDocument';import { findRepeatedWorkflowItem, joinProjectDocument, splitProjectDocument } from './projectHalves';+import { rebuildProjectMediaUrls } from './projectMediaUrls';const toFutureProjectDocumentRefusal = (data: Record<string, unknown>,@@ -66,6 +68,14 @@ export const deserializeProjectDocument = (data: Record<string, unknown>): ProjeworkflowHistories: {},} as unknown as Project);+ if (result.status === 'loaded') {+ // Every load path (server records, drafts, `.invk` import, duplicate) passes here, and the sync baseline is taken+ // from what it returns, so rebuilding here never by itself causes a save.+ return {+ project: rebuildProjectMediaUrls(result.project, { image: galleryImageUrls, video: galleryVideoUrls }),+ status: 'loaded',+ };+ }return result.status === 'refused' ? { refused: { ...result.refused, raw: data }, status: 'refused' } : result;};diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.ts b/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.tsindex 0d696e74f6..842e5a446f 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectLifecycleLocks.ts@@ -1,12 +1,26 @@-import { acquireExclusiveLock, type BrowserLockResult } from '@platform/browser/webLocks';+import { acquireExclusiveLock, type BrowserLockResult, hasWebLocks } from '@platform/browser/webLocks';const LOCK_PREFIX = 'invokeai:v7:webv2:project-lifecycle';export const getProjectLifecycleLockName = (storageSuffix: string, projectId: string): string =>`${LOCK_PREFIX}${storageSuffix}:${JSON.stringify(projectId)}`;+/**+ * The exclusive project-lifecycle lock: held, it means no tab has an active queue run for the project (each run holds+ * the name shared). `unavailable` without Web Locks.+ */export const acquireProjectMutationLock = (storageSuffix: string,projectId: string,acquire: (name: string) => Promise<BrowserLockResult> = acquireExclusiveLock): Promise<BrowserLockResult> => acquire(getProjectLifecycleLockName(storageSuffix, projectId));++/**+ * The lock policy for project delete, conflict discard and save as new. The backend rejects every write that would+ * conflict with them (revision checks, and 404 once a project is deleted), so without the Web Locks API (a plain-HTTP+ * origin) they run in single-tab mode: nothing is held, and the queue-run journal check is the only cross-tab guard+ * left. Where the API exists, other tabs can hold the lock, so a failed request stays `unavailable` and the caller+ * refuses. Queue-recovery discard has no backend fence and refuses `unavailable` either way.+ */+export const withSingleTabFallback = (lock: BrowserLockResult): BrowserLockResult =>+ lock.kind === 'unavailable' && !hasWebLocks() ? { kind: 'acquired', release: () => Promise.resolve() } : lock;diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.tsnew file mode 100644index 0000000000..60f378e2f2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.test.ts@@ -0,0 +1,191 @@+import type { GeneratedImageContract } from '@features/gallery';+import type { CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';+import type { Project } from '@workbench/projectContracts';++import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createRegionalGuidanceLayerWithRefImage } from '@workbench/widgets/layers/layerOps';+import { createDraftProject } from '@workbench/workbenchState';+import { describe, expect, it } from 'vitest';++import { stripInstallationState } from './projectAssets';+import { rebuildProjectMediaUrls, type ProjectMediaUrlResolver } from './projectMediaUrls';++const urls: ProjectMediaUrlResolver = {+ image: {+ full: (name) => `https://here/images/${name}/full`,+ thumbnail: (name) => `https://here/images/${name}/thumb`,+ },+ video: {+ full: (name) => `https://here/videos/${name}/full`,+ thumbnail: (name) => `https://here/videos/${name}/thumb`,+ },+};++const STALE = 'http://localhost:9090/api/v1';++const generated = (imageName: string, url = `${STALE}/images/i/${imageName}/full`): GeneratedImageContract => ({+ height: 64,+ imageName,+ imageUrl: url,+ queuedAt: '2026-10-19T00:00:00.000Z',+ sourceQueueItemId: 'queue-1',+ thumbnailUrl: url === '' ? '' : `${STALE}/images/i/${imageName}/thumbnail`,+ width: 64,+});++const galleryItem = (kind: 'image' | 'video', name: string) => ({+ boardId: 'none',+ category: 'general',+ createdAt: '2026-10-19T00:00:00.000Z',+ fullUrl: `${STALE}/${kind}s/i/${name}/full`,+ height: 64,+ isIntermediate: false,+ kind,+ name,+ starred: false,+ thumbnailUrl: `${STALE}/${kind}s/i/${name}/thumbnail`,+ width: 64,+ ...(kind === 'video' ? { durationSeconds: 2 } : {}),+});++const regionalWith = (id: string, image: GeneratedImageContract | null): CanvasRegionalGuidanceLayerContract => {+ const layer = createRegionalGuidanceLayerWithRefImage(id, 0, 'sdxl', id);+ const [reference] = layer.referenceImages;+ return { ...layer, referenceImages: [{ ...reference!, config: { ...reference!.config, image } }] };+};++const withGallery = (project: Project, instanceId: string, values: Record<string, unknown>): Project => ({+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ [instanceId]: { id: instanceId, state: { values }, typeId: 'gallery' } as Project['widgetInstances'][string],+ },+});++/** A project holding a stale or blank URL in every place a project stores one. */+const staleProject = (): Project => {+ const base = createDraftProject([]);+ const document = {+ ...base.canvas.document,+ stacks: stacksFrom([groupContract('group', [regionalWith('nested', generated('nested.png'))])]),+ };+ const withCanvas: Project = {+ ...base,+ canvas: {+ ...base.canvas,+ document,+ snapshots: [+ {+ createdAt: '2026-10-19T00:00:00.000Z',+ document: { ...document, stacks: stacksFrom([regionalWith('snap', generated('snap.png', ''))]) },+ id: 'snapshot-1',+ name: 'Snapshot',+ },+ ],+ stagingArea: {+ ...base.canvas.stagingArea,+ pendingImages: [{ ...generated('staged.png'), placement: { height: 64, opacity: 1, width: 64, x: 0, y: 0 } }],+ },+ },+ };+ return withGallery(+ withGallery(withCanvas, 'gallery', {+ compareImage: generated('compare.png'),+ recentImages: [generated('recent.png'), generated('imported.png', '')],+ selectedImage: galleryItem('image', 'selected.png'),+ }),+ 'gallery-2',+ { selectedImage: galleryItem('video', 'clip.mp4') }+ );+};++const galleryValues = (project: Project, instanceId: string) => project.widgetInstances[instanceId]!.state.values;++describe('rebuildProjectMediaUrls', () => {+ it('rebuilds every stored media URL from the name beside it', () => {+ const rebuilt = rebuildProjectMediaUrls(staleProject(), urls);++ expect(galleryValues(rebuilt, 'gallery')).toMatchObject({+ compareImage: {+ imageUrl: 'https://here/images/compare.png/full',+ thumbnailUrl: 'https://here/images/compare.png/thumb',+ },+ recentImages: [+ { imageUrl: 'https://here/images/recent.png/full', thumbnailUrl: 'https://here/images/recent.png/thumb' },+ // `.invk` transfer blanks URLs; a load fills them.+ { imageUrl: 'https://here/images/imported.png/full', thumbnailUrl: 'https://here/images/imported.png/thumb' },+ ],+ selectedImage: {+ fullUrl: 'https://here/images/selected.png/full',+ thumbnailUrl: 'https://here/images/selected.png/thumb',+ },+ });+ expect(galleryValues(rebuilt, 'gallery-2').selectedImage).toMatchObject({+ fullUrl: 'https://here/videos/clip.mp4/full',+ thumbnailUrl: 'https://here/videos/clip.mp4/thumb',+ });+ expect(rebuilt.canvas.stagingArea.pendingImages[0]).toMatchObject({+ imageUrl: 'https://here/images/staged.png/full',+ placement: { height: 64, opacity: 1, width: 64, x: 0, y: 0 },+ thumbnailUrl: 'https://here/images/staged.png/thumb',+ });+ const [group] = rebuilt.canvas.document.stacks.regional_guidance;+ const nested = group?.type === 'group' ? group.children[0] : null;+ expect(nested?.type === 'regional_guidance' ? nested.referenceImages[0]?.config.image : null).toMatchObject({+ imageUrl: 'https://here/images/nested.png/full',+ thumbnailUrl: 'https://here/images/nested.png/thumb',+ });+ const [snapshotLayer] = rebuilt.canvas.snapshots[0]!.document.stacks.regional_guidance;+ expect(+ snapshotLayer?.type === 'regional_guidance' ? snapshotLayer.referenceImages[0]?.config.image : null+ ).toMatchObject({+ imageUrl: 'https://here/images/snap.png/full',+ thumbnailUrl: 'https://here/images/snap.png/thumb',+ });+ expect(JSON.stringify(rebuilt)).not.toContain('localhost:9090');+ });++ it('keeps the identity of a project, and of every untouched subtree, whose URLs already match', () => {+ const rebuilt = rebuildProjectMediaUrls(staleProject(), urls);++ expect(rebuildProjectMediaUrls(rebuilt, urls)).toBe(rebuilt);++ const base = createDraftProject([]);+ const selectedOnly = withGallery(base, 'gallery', { selectedImage: galleryItem('image', 'a.png') });+ const healed = rebuildProjectMediaUrls(selectedOnly, urls);+ expect(healed).not.toBe(selectedOnly);+ expect(healed.canvas).toBe(selectedOnly.canvas);+ expect(healed.widgetInstances.generate).toBe(selectedOnly.widgetInstances.generate);+ });++ it('rebuilds every URL field that `.invk` transfer blanks, so an imported project loads with working media', () => {+ const urlValues = (node: unknown, found: unknown[] = []): unknown[] => {+ if (Array.isArray(node)) {+ node.forEach((item) => urlValues(item, found));+ } else if (typeof node === 'object' && node !== null) {+ for (const [key, value] of Object.entries(node)) {+ if (key.endsWith('Url')) {+ found.push(value);+ }+ urlValues(value, found);+ }+ }+ return found;+ };+ const transferred = stripInstallationState(staleProject() as unknown as Record<string, unknown>);++ expect(urlValues(transferred)).toContain('');+ const loaded = urlValues(rebuildProjectMediaUrls(transferred as unknown as Project, urls));+ expect(loaded.length).toBeGreaterThan(0);+ for (const url of loaded) {+ expect(url).toMatch(/^https:\/\/here\//);+ }+ });++ it('leaves an item without a name untouched', () => {+ const nameless = { fullUrl: `${STALE}/images/i/x.png/full`, kind: 'image', name: '' };+ const project = withGallery(createDraftProject([]), 'gallery', { selectedImage: nameless });++ expect(galleryValues(rebuildProjectMediaUrls(project, urls), 'gallery').selectedImage).toBe(nameless);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.ts b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.tsnew file mode 100644index 0000000000..9427e5e705--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/projectMediaUrls.ts@@ -0,0 +1,174 @@+import type {+ CanvasDocumentContractV3,+ CanvasNodeContract,+ CanvasStateContractV3,+ RegionalGuidanceReferenceImage,+} from '@workbench/canvas-engine/api';+import type { Project } from '@workbench/projectContracts';++import { GALLERY_ITEM_URL_FIELDS, GENERATED_IMAGE_URL_FIELDS } from './projectAssets';++/** Builds one kind of media's URLs from its name, against the deployment the page runs on. */+export interface MediaUrlBuilders {+ readonly full: (name: string) => string;+ readonly thumbnail: (name: string) => string;+}++export interface ProjectMediaUrlResolver {+ readonly image: MediaUrlBuilders;+ readonly video: MediaUrlBuilders;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const isName = (value: unknown): value is string => typeof value === 'string' && value.length > 0;++type UrlFields = Readonly<Record<string, keyof MediaUrlBuilders>>;++/** The value with `fields` derived from `name`; the value itself when every URL already matches, keeping identity. */+const withUrls = <T extends Record<string, unknown>>(+ value: T,+ fields: UrlFields,+ builders: MediaUrlBuilders,+ name: string+): T => {+ let next: Record<string, unknown> | null = null;+ for (const [key, builder] of Object.entries(fields)) {+ const url = builders[builder](name);+ if (value[key] !== url) {+ next ??= { ...value };+ next[key] = url;+ }+ }+ return (next as T | null) ?? value;+};++const mapShared = <T>(items: T[], rebuild: (item: T) => T): T[] => {+ let next: T[] | null = null;+ items.forEach((item, index) => {+ const rebuilt = rebuild(item);+ if (rebuilt !== item) {+ next ??= items.slice();+ next[index] = rebuilt;+ }+ });+ return next ?? items;+};++/** A generated-image record (`imageName` beside `imageUrl`/`thumbnailUrl`): recents, staging, references. */+const rebuildGeneratedImage = <T>(value: T, urls: ProjectMediaUrlResolver): T =>+ isRecord(value) && isName(value.imageName)+ ? (withUrls(value, GENERATED_IMAGE_URL_FIELDS, urls.image, value.imageName) as T)+ : value;++/** A gallery selection: a gallery item (`name` and `kind`), or the generated-image shape older documents stored. */+const rebuildGallerySelection = (value: unknown, urls: ProjectMediaUrlResolver): unknown => {+ if (!isRecord(value)) {+ return value;+ }+ if (isName(value.name) && (value.kind === 'image' || value.kind === 'video')) {+ return withUrls(value, GALLERY_ITEM_URL_FIELDS, value.kind === 'video' ? urls.video : urls.image, value.name);+ }+ return rebuildGeneratedImage(value, urls);+};++const rebuildGalleryValues = (+ values: Record<string, unknown>,+ urls: ProjectMediaUrlResolver+): Record<string, unknown> => {+ const selectedImage = rebuildGallerySelection(values.selectedImage, urls);+ const compareImage = rebuildGallerySelection(values.compareImage, urls);+ const recentImages = Array.isArray(values.recentImages)+ ? mapShared(values.recentImages as unknown[], (image) => rebuildGeneratedImage(image, urls))+ : values.recentImages;+ return selectedImage === values.selectedImage &&+ compareImage === values.compareImage &&+ recentImages === values.recentImages+ ? values+ : { ...values, compareImage, recentImages, selectedImage };+};++const rebuildWidgetInstances = (+ instances: Project['widgetInstances'],+ urls: ProjectMediaUrlResolver+): Project['widgetInstances'] => {+ let next: Project['widgetInstances'] | null = null;+ for (const [instanceId, instance] of Object.entries(instances)) {+ if (instance.typeId !== 'gallery') {+ continue;+ }+ const values = rebuildGalleryValues(instance.state.values, urls);+ if (values !== instance.state.values) {+ next ??= { ...instances };+ next[instanceId] = { ...instance, state: { ...instance.state, values } };+ }+ }+ return next ?? instances;+};++const rebuildReferenceImage = (+ reference: RegionalGuidanceReferenceImage,+ urls: ProjectMediaUrlResolver+): RegionalGuidanceReferenceImage => {+ const image = rebuildGeneratedImage(reference.config.image, urls);+ return image === reference.config.image ? reference : { ...reference, config: { ...reference.config, image } };+};++const rebuildRegionalNode = (node: CanvasNodeContract, urls: ProjectMediaUrlResolver): CanvasNodeContract => {+ if (node.type === 'group') {+ const children = mapShared(node.children, (child) => rebuildRegionalNode(child, urls));+ return children === node.children ? node : { ...node, children };+ }+ if (node.type !== 'regional_guidance') {+ return node;+ }+ const referenceImages = mapShared(node.referenceImages, (reference) => rebuildReferenceImage(reference, urls));+ return referenceImages === node.referenceImages ? node : { ...node, referenceImages };+};++/** Regional guidance is the only canvas layer that keeps image URLs; every other leaf holds names alone. */+const rebuildCanvasDocument = (+ document: CanvasDocumentContractV3,+ urls: ProjectMediaUrlResolver+): CanvasDocumentContractV3 => {+ const regional = document.stacks.regional_guidance;+ const rebuilt = mapShared(regional, (node) => rebuildRegionalNode(node, urls));+ return rebuilt === regional ? document : { ...document, stacks: { ...document.stacks, regional_guidance: rebuilt } };+};++const rebuildCanvas = (canvas: CanvasStateContractV3, urls: ProjectMediaUrlResolver): CanvasStateContractV3 => {+ const document = rebuildCanvasDocument(canvas.document, urls);+ const snapshots = mapShared(canvas.snapshots, (snapshot) => {+ const snapshotDocument = rebuildCanvasDocument(snapshot.document, urls);+ return snapshotDocument === snapshot.document ? snapshot : { ...snapshot, document: snapshotDocument };+ });+ const pendingImages = mapShared(canvas.stagingArea.pendingImages, (image) => rebuildGeneratedImage(image, urls));+ return document === canvas.document &&+ snapshots === canvas.snapshots &&+ pendingImages === canvas.stagingArea.pendingImages+ ? canvas+ : {+ ...canvas,+ document,+ snapshots,+ stagingArea:+ pendingImages === canvas.stagingArea.pendingImages+ ? canvas.stagingArea+ : { ...canvas.stagingArea, pendingImages },+ };+};++/**+ * Rebuilds every media URL a project stores from the name stored beside it. Stored URLs name the origin that saved+ * them (`http://localhost:9090/...`), which another origin or machine cannot reach, and `.invk` transfer blanks them,+ * so each load derives them again for the deployment the page runs on. Names are the durable reference; a URL is+ * overwritten whatever it held, and an item without a name is left alone. Unchanged subtrees keep their identity.+ */+export const rebuildProjectMediaUrls = (project: Project, urls: ProjectMediaUrlResolver): Project => {+ const widgetInstances = rebuildWidgetInstances(project.widgetInstances, urls);+ const canvas = rebuildCanvas(project.canvas, urls);+ return widgetInstances === project.widgetInstances && canvas === project.canvas+ ? project+ : { ...project, canvas, widgetInstances };+};diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.tsindex 6615be0936..3c5c4051db 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectSync.test.ts@@ -288,6 +288,54 @@ describe('project document serialization', () => {});});+ it('loads media URLs rebuilt for this deployment, whether stored at another origin or blanked by transfer', () => {+ const recent = (imageName: string, imageUrl: string, thumbnailUrl: string) => ({+ height: 8,+ imageName,+ imageUrl,+ queuedAt: 't1',+ sourceQueueItemId: 'q1',+ thumbnailUrl,+ width: 8,+ });+ const document = serializeProjectDocumentV3(getProject());+ const gallery = document.widgetInstances.gallery!;+ const loaded = loadDocument({+ ...document,+ widgetInstances: {+ ...document.widgetInstances,+ gallery: {+ ...gallery,+ state: {+ ...gallery.state,+ values: {+ ...gallery.state.values,+ recentImages: [+ recent(+ 'saved.png',+ 'http://localhost:9090/api/v1/images/i/saved.png/full',+ 'http://localhost:9090/api/v1/images/i/saved.png/thumbnail'+ ),+ recent('imported.png', '', ''),+ ],+ },+ },+ },+ },+ } as unknown as Record<string, unknown>);++ expect(loaded.widgetInstances.gallery!.state.values.recentImages).toEqual([+ expect.objectContaining({+ imageUrl: 'http://localhost/api/v1/images/i/saved.png/full',+ thumbnailUrl: 'http://localhost/api/v1/images/i/saved.png/thumbnail',+ }),+ expect.objectContaining({+ imageUrl: 'http://localhost/api/v1/images/i/imported.png/full',+ thumbnailUrl: 'http://localhost/api/v1/images/i/imported.png/thumbnail',+ }),+ ]);+ });+it('refuses a schema-3 document whose collection would lose a workflow instead of repairing it', () => {const document = serializeProjectDocumentV3(getProject());const refusal = (data: Record<string, unknown>) => {diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsxindex 82db26cb0e..4174c1c397 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecoveryNotice.browser.test.tsx@@ -261,6 +261,19 @@ describe('QueueRecoveryNotice', () => {expect(harness.deleteForProject).not.toHaveBeenCalled();});+ it('keeps refusing discard without Web Locks, as on a plain-HTTP origin, and says why', async () => {+ // Nothing on the server fences this discard (the journal is browser-local), so unlike project delete it never+ // falls back to single-tab mode.+ harness.lockResult = { kind: 'unavailable' };+ await renderNotice({ openProjectIds: ['open-project'] });+ await clickButton('shell.queueRecovery.discard');+ await act(() => userEvent.click(document.querySelector<HTMLButtonElement>('[data-testid="confirm-discard"]')!));+ await vi.waitFor(() => expect(document.body.textContent).toContain('shell.queueRecovery.lockUnavailable'));++ expect(harness.deleteForProject).not.toHaveBeenCalled();+ expect(document.body.textContent).toContain('shell.queueRecovery.export');+ });+it('shows unknown recovery state when IndexedDB cannot be inspected', async () => {harness.listProjectIds.mockResolvedValueOnce({ kind: 'unavailable' });await renderNotice();diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsxindex 2b8111715c..b2737630f7 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFailureBoundary.tsx@@ -6,6 +6,7 @@ import type {} from '@workbench/widgetContracts';import { Box, Code, Flex, HStack, ScrollArea, Stack, Text, useRecipe } from '@chakra-ui/react';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { createLogger } from '@platform/logging/logger';import { Button } from '@platform/ui/Button';import { toaster } from '@platform/ui/toaster';@@ -62,6 +63,7 @@ const WidgetFailureCard = ({const viewportRef = useRef<HTMLDivElement | null>(null);useScrollAreaPhantomHeal(viewportRef);+ const canCopy = canCopyText();// The card has no other feedback channel: without a toast the click is// indistinguishable from one that silently failed.const copy = useCallback(@@ -98,7 +100,13 @@ const WidgetFailureCard = ({<Button alignSelf="start" size="sm" variant="outline" onClick={onRetry}>{t('widgets.failure.retry')}</Button>- <Button alignSelf="start" size="sm" variant="outline" onClick={copy}>+ <Button+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}+ alignSelf="start"+ size="sm"+ variant="outline"+ onClick={copy}+ >{t('widgets.failure.copyError')}</Button></Stack>@@ -218,9 +226,7 @@ export class WidgetFailureBoundary extends Component<WidgetFailureBoundaryProps,private handleCopyError = (): Promise<void> => {const { details, error } = this.state;- return error && navigator.clipboard- ? navigator.clipboard.writeText(details ?? error.message)- : Promise.reject(new Error('clipboard unavailable'));+ return error ? copyText(details ?? error.message) : Promise.reject(new Error('No error to copy.'));};static getDerivedStateFromProps(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsxindex 633da74c91..f2ca20ea2d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx@@ -96,8 +96,8 @@ const candidate: CanvasStagingCandidateContract = {width: 64,};-/** Stages the first image of a three-image batch whose remaining images are `status`. */-const renderView = async (status: QueueItem['status']) => {+/** Stages the first image of a three-image batch whose remaining images are `status`; unstaged, the surface is live. */+const renderView = async (status: QueueItem['status'], { staged = true } = {}) => {const initial = createInitialWorkbenchState();const base = initial.projects[0]!;const batch = {@@ -117,8 +117,10 @@ const renderView = async (status: QueueItem['status']) => {} as unknown as QueueItem;const store = createWorkbenchStore({ ...initial, projects: [{ ...base, queue: { items: [batch] } }] });const projectId = store.getState().activeProjectId;- store.commands.canvas.appendStagingCandidate({ candidate, projectId });- store.commands.canvas.apply(projectId, { imageIndex: 0, type: 'setStagedImageIndex' });+ if (staged) {+ store.commands.canvas.appendStagingCandidate({ candidate, projectId });+ store.commands.canvas.apply(projectId, { imageIndex: 0, type: 'setStagedImageIndex' });+ }harness.store = store;harness.engine = createCanvasEngine({backend: createTestStubRasterBackend(),@@ -133,7 +135,16 @@ const renderView = async (status: QueueItem['status']) => {host.style.width = '1000px';document.body.append(host);root = createRoot(host);- const runtime = { commands: { register: () => () => undefined }, hotkeys: { register: () => () => undefined } };+ const commandHandlers = new Map<string, () => void>();+ const runtime = {+ commands: {+ register: ({ handler, id }: { handler: () => void; id: string }) => {+ commandHandlers.set(id, handler);+ return () => commandHandlers.delete(id);+ },+ },+ hotkeys: { register: () => () => undefined },+ };await act(() =>root!.render(<I18nextProvider i18n={i18n}>@@ -145,7 +156,7 @@ const renderView = async (status: QueueItem['status']) => {</I18nextProvider>));- return { projectId, store };+ return { commandHandlers, projectId, store };};describe('CanvasWidgetView accept and stop', () => {@@ -174,3 +185,69 @@ describe('CanvasWidgetView accept and stop', () => {expect(project.queue.items[0]?.status).toBe('completed');});});++describe('CanvasWidgetView clipboard shortcuts', () => {+ // A plain-HTTP origin is not a secure context, so the browser exposes no async Clipboard API.+ const withoutClipboard = () => vi.spyOn(Navigator.prototype, 'clipboard', 'get').mockReturnValue(undefined!);++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('says why copy and cut fail, and keeps the pixels a failed cut would erase', async () => {+ const { commandHandlers, store } = await renderView('completed', { staged: false });+ withoutClipboard();+ vi.spyOn(harness.engine!.selection, 'exportSelectionBlob').mockResolvedValue(new Blob([], { type: 'image/png' }));+ const erase = vi.spyOn(harness.engine!.selection, 'eraseSelection');++ await act(() => commandHandlers.get('canvas.copySelection')!());+ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ message: 'Copying needs HTTPS or localhost',+ title: 'Could not copy the selection to the clipboard',+ })+ );++ // Cut fails the same way, so the store coalesces it into the same notice.+ await act(() => commandHandlers.get('canvas.cutSelection')!());+ await vi.waitFor(() => expect(store.getState().notifications[0]?.occurrenceCount).toBe(2));+ expect(erase).not.toHaveBeenCalled();+ });++ it('says why paste does nothing', async () => {+ const { commandHandlers, store } = await renderView('completed', { staged: false });+ withoutClipboard();++ await act(() => commandHandlers.get('canvas.pasteImage')!());++ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ message: 'Pasting needs HTTPS or localhost',+ title: 'Could not paste an image from the clipboard',+ })+ );+ });++ it('reports a clipboard image that cannot be retrieved without blaming the address', async () => {+ const { commandHandlers, store } = await renderView('completed', { staged: false });+ const item = {+ getType: () => Promise.reject(new DOMException('Image data unavailable', 'DataError')),+ types: ['image/png'],+ } as unknown as ClipboardItem;+ vi.spyOn(Navigator.prototype, 'clipboard', 'get').mockReturnValue({+ read: () => Promise.resolve([item]),+ } as unknown as Clipboard);++ await act(() => commandHandlers.get('canvas.pasteImage')!());++ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ title: 'Could not paste an image from the clipboard',+ })+ );+ expect(store.getState().notifications[0]?.message).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex d8a0a47980..30e09df87c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -4,6 +4,7 @@ import type { MouseEvent as ReactMouseEvent } from 'react';import { Box } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';import { useQueueItemProgressImage } from '@features/queue/react';+import { ClipboardUnavailableError, copyImage } from '@platform/browser/clipboard';import { useMountEffect } from '@platform/react/useMountEffect';import { preloadCanvasInvocation } from '@workbench/activeInvocationSubmission';import { getCanvasImportNotice } from '@workbench/canvas-operations/api';@@ -29,7 +30,7 @@ import { useTranslation } from 'react-i18next';import { useModelGridSize } from './bboxGrid';import { CanvasBottomOverlay } from './CanvasBottomOverlay';-import { copyBlobToClipboard, decodeImageBlob, readClipboardImage } from './canvasClipboard';+import { decodeImageBlob, readClipboardImage } from './canvasClipboard';import {resolveCanvasContextMenu,resolveCanvasContextMenuBranch,@@ -272,13 +273,17 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {if (!blob) {return;}- await copyBlobToClipboard(blob);+ await copyImage(blob);if (cut) {// Only after the write succeeds — a failed copy must not destroy pixels.mountedEngine.selection.eraseSelection();}- } catch {- notifications.add({ kind: 'error', title: t('widgets.canvas.clipboard.copyFailed') });+ } catch (error) {+ notifications.add({+ kind: 'error',+ message: error instanceof ClipboardUnavailableError ? t('common.copyUnavailable') : undefined,+ title: t('widgets.canvas.clipboard.copyFailed'),+ });}})();});@@ -290,7 +295,18 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {return;}void (async () => {- const blob = await readClipboardImage();+ let blob: Blob | null;+ try {+ blob = await readClipboardImage();+ } catch (error) {+ // A missing clipboard API (plain HTTP) gets its reason; an item that fails to yield its image does not.+ notifications.add({+ kind: 'error',+ message: error instanceof ClipboardUnavailableError ? t('common.pasteUnavailable') : undefined,+ title: t('widgets.canvas.clipboard.pasteFailed'),+ });+ return;+ }if (!blob) {return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.tsindex 989e717e21..495b6c7065 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.test.ts@@ -1,3 +1,4 @@+import { ClipboardUnavailableError } from '@platform/browser/clipboard';import { describe, expect, it, vi } from 'vitest';import { decodeImageBlob, readClipboardImage } from './canvasClipboard';@@ -12,8 +13,8 @@ const item = (types: string[], payload: Record<string, Blob> = {}): ClipboardIte}) as unknown as ClipboardItem;describe('readClipboardImage', () => {- it('returns null when the clipboard API is unavailable', async () => {- await expect(readClipboardImage({ clipboard: undefined })).resolves.toBeNull();+ it('rejects when the clipboard API is unavailable, so paste can say why', async () => {+ await expect(readClipboardImage({ clipboard: {} })).rejects.toBeInstanceOf(ClipboardUnavailableError);});it('returns null when permission is refused rather than throwing', async () => {@@ -23,6 +24,15 @@ describe('readClipboardImage', () => {await expect(readClipboardImage({ clipboard })).resolves.toBeNull();});+ it("rejects with the item's own error when a listed image cannot be retrieved", async () => {+ const failure = new DOMException('Image data unavailable', 'DataError');+ const clipboard = {+ read: () =>+ Promise.resolve([{ getType: () => Promise.reject(failure), types: ['image/png'] } as unknown as ClipboardItem]),+ };+ await expect(readClipboardImage({ clipboard })).rejects.toBe(failure);+ });+it('returns null when the clipboard holds no image', async () => {const clipboard = { read: () => Promise.resolve([item(['text/plain'])]) };await expect(readClipboardImage({ clipboard })).resolves.toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.tsindex c39ecd11a4..29647f695f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts@@ -3,32 +3,25 @@* clipboard/canvas access.*/-export { copyBlobToClipboard } from '@workbench/widgets/layers/layerExportActions';--type ClipboardReadLike = { read(): Promise<readonly ClipboardItem[]> };--export interface ReadClipboardImageDeps {- clipboard?: ClipboardReadLike;-}+import { type ClipboardAccess, ClipboardUnavailableError, readClipboardItems } from '@platform/browser/clipboard';/** MIME types accepted from the clipboard, best first. */const IMAGE_TYPES = ['image/png', 'image/webp', 'image/jpeg'] as const;/**- * The first image on the clipboard, or `null` when it holds none. Returns- * `null` rather than throwing when the clipboard is unavailable or permission- * was refused — a paste that finds nothing is an ordinary outcome, not an error.+ * The first image on the clipboard, or `null` when it holds none or cannot be read (permission refused, document not+ * focused): a paste that finds nothing is an ordinary outcome. Rejects with `ClipboardUnavailableError` when the+ * browser has no clipboard API (plain HTTP), so paste can say why, and with the item's own error when an image it+ * lists cannot be retrieved.*/-export const readClipboardImage = async (deps: ReadClipboardImageDeps = {}): Promise<Blob | null> => {- const clipboard = deps.clipboard ?? (globalThis.navigator?.clipboard as ClipboardReadLike | undefined);- if (!clipboard?.read) {- return null;- }+export const readClipboardImage = async (deps: ClipboardAccess = {}): Promise<Blob | null> => {let items: readonly ClipboardItem[];try {- items = await clipboard.read();- } catch {- // Permission refused, or the document is not focused. Nothing to paste.+ items = await readClipboardItems(deps);+ } catch (error) {+ if (error instanceof ClipboardUnavailableError) {+ throw error;+ }return null;}for (const item of items) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsxindex f90837defc..bdedd2496f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ClusterStrengthField.browser.test.tsx@@ -65,7 +65,7 @@ let root: Root | null = null;const SETTLE_MS = 900;/**- * Real-time settle, for the tests that type through the real keyboard. Everything else fakes the clock (see+ * Real-time settle, for some of the tests that type through the real keyboard. The rest fake the clock (see* `setValue`): this file runs beside other browser test files that share the page's focus, and seconds of real* typing and waiting here were enough to knock their popovers and menus closed on CI.*/@@ -206,11 +206,15 @@ describe('ClusterStrengthField', () => {});it('does not mistake a half-typed number for a cleared box', async () => {+ // Faked so the keys stay one burst however slowly a loaded browser+ // delivers them: on the real clock, a "." landing past the debounce finds+ // the box genuinely empty and commits that as a deliberate clear.+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });// `type="number"` reports an empty value for "0." too. Reading that as// "use the heuristic" would throw the user's setting away mid-keystroke.await render(0.0945);await setValue('0.25');- await settle();+ await settleFake();settings.patch.mockClear();// One keyboard sequence: clear() waits long enough to commit the intentionally empty box before type() runs.@@ -219,7 +223,7 @@ describe('ClusterStrengthField', () => {expect(spinner().value).toBe('');expect(spinner().validity.badInput).toBe(true);- await settle();+ await settleFake();expect(settings.patch).not.toHaveBeenCalled();});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex c37df16db3..177f203343 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -18,6 +18,7 @@ import type { ComponentProps, Dispatch, ReactNode } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { galleryTransfers } from '@features/gallery';import { useModelsSelector } from '@features/models';+import { canCopyImage } from '@platform/browser/clipboard';import { IconButton, MenuActionItem, MenuContent, MenuIconItem, RenameDialog, Tooltip } from '@platform/ui';import { useQueryClient } from '@tanstack/react-query';import {@@ -1310,6 +1311,14 @@ const LayerMenuSubmenu = ({);};+type LayerMenuTranslate = (key: string, options: { count?: number; defaultValue: string }) => string;++/** Copying a layer needs the clipboard, which a plain-HTTP origin lacks; the item says so instead of failing. */+const getUnavailableReason = (action: LayerContextAction, t: LayerMenuTranslate): string | undefined =>+ action.id === 'copy-to-clipboard' && !canCopyImage()+ ? t('common.copyUnavailable', { defaultValue: 'Copying needs HTTPS or localhost' })+ : undefined;+const LayerMenuIconActionItem = ({action,runAction,@@ -1317,7 +1326,7 @@ const LayerMenuIconActionItem = ({}: {action: LayerContextAction;runAction: RunLayerAction;- t: (key: string, options: { count?: number; defaultValue: string }) => string;+ t: LayerMenuTranslate;}) => {const onSelect = useCallback(() => runAction(action), [action, runAction]);@@ -1327,6 +1336,7 @@ const LayerMenuIconActionItem = ({icon={action.icon}label={t(action.labelKey, { count: action.labelCount, defaultValue: action.defaultLabel })}tone={action.tone}+ unavailableReason={getUnavailableReason(action, t)}value={action.id}onSelect={onSelect}/>@@ -1340,7 +1350,7 @@ const LayerMenuActionItem = ({}: {action: LayerContextAction;runAction: RunLayerAction;- t: (key: string, options: { count?: number; defaultValue: string }) => string;+ t: LayerMenuTranslate;}) => {const onSelect = useCallback(() => runAction(action), [action, runAction]);@@ -1352,6 +1362,7 @@ const LayerMenuActionItem = ({iconColor={action.iconColor}label={t(action.labelKey, { count: action.labelCount, defaultValue: action.defaultLabel })}tone={action.tone}+ unavailableReason={getUnavailableReason(action, t)}value={action.id}onSelect={onSelect}/>@@ -1366,6 +1377,7 @@ const LayerMenuItem = ({label,onSelect,tone,+ unavailableReason,value,}: {disabled?: boolean;@@ -1376,6 +1388,7 @@ const LayerMenuItem = ({label: string;onSelect: () => void;tone?: 'danger';+ unavailableReason?: string;value: string;}) => {const shortcut = useMemo(@@ -1391,6 +1404,7 @@ const LayerMenuItem = ({label={label}shortcut={shortcut}tone={tone}+ unavailableReason={unavailableReason}value={value}onSelect={onSelect}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.tsindex 9f3c5ed0de..f959155180 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.test.ts@@ -10,36 +10,7 @@ import { ApiError } from '@platform/transport/http';import { QueryClient, QueryObserver } from '@tanstack/react-query';import { afterEach, describe, expect, it, vi } from 'vitest';-import { copyBlobToClipboard, copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';--describe('copyBlobToClipboard', () => {- it('writes a ClipboardItem using the blob MIME type', async () => {- const write = vi.fn(() => Promise.resolve());- const created: Record<string, Blob>[] = [];- class TestClipboardItem {- presentationStyle: PresentationStyle = 'unspecified';- types: string[] = [];- constructor(items: Record<string, Blob>) {- created.push(items);- this.types = Object.keys(items);- }- getType(type: string): Promise<Blob> {- return Promise.resolve(created.at(-1)?.[type] ?? new Blob());- }- }- const blob = new Blob(['pixels'], { type: 'image/png' });-- await copyBlobToClipboard(blob, { ClipboardItemCtor: TestClipboardItem, clipboard: { write } });-- expect(created).toHaveLength(1);- expect(created[0]?.['image/png']).toBe(blob);- expect(write).toHaveBeenCalledWith([expect.any(TestClipboardItem)]);- });-- it('fails when the clipboard API is unavailable', async () => {- await expect(copyBlobToClipboard(new Blob(['pixels']))).rejects.toThrow('Clipboard image copy is unavailable');- });-});+import { copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';describe('copyLayerToClipboard', () => {it('bakes the layer with disabled content and writes it; a refused export reports its status', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.tsindex 76ed2da76a..97546259b4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerExportActions.ts@@ -10,34 +10,17 @@ import {invalidateGalleryBoardDestinations,invalidateGalleryItems,} from '@features/gallery/queries';+import { type ClipboardAccess, copyImage } from '@platform/browser/clipboard';import {assertAccountScopeCurrent,captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';-type ClipboardLike = { write(items: ClipboardItem[]): Promise<void> };-type ClipboardItemCtor = new (items: Record<string, Blob>) => ClipboardItem;--export interface CopyBlobToClipboardDeps {- clipboard?: ClipboardLike;- ClipboardItemCtor?: ClipboardItemCtor;-}--export const copyBlobToClipboard = async (blob: Blob, deps: CopyBlobToClipboardDeps = {}): Promise<void> => {- const clipboard = deps.clipboard ?? globalThis.navigator?.clipboard;- const ClipboardItemImpl = deps.ClipboardItemCtor ?? globalThis.ClipboardItem;- if (!clipboard || !ClipboardItemImpl) {- throw new Error('Clipboard image copy is unavailable');- }- const type = blob.type || 'image/png';- await clipboard.write([new ClipboardItemImpl({ [type]: blob })]);-};-type LayerAssetExportFailureStatus = Exclude<ExportBakedLayerBlobResult['status'], 'ok'>;type LayerAssetExportResult = { status: 'ok'; blob: Blob } | { status: LayerAssetExportFailureStatus };-interface CopyLayerToClipboardDeps extends CopyBlobToClipboardDeps {+interface CopyLayerToClipboardDeps extends ClipboardAccess {exportLayer(layerId: string, options: { includeDisabled: boolean }): Promise<LayerAssetExportResult>;}@@ -50,7 +33,7 @@ export const copyLayerToClipboard = async (if (result.status !== 'ok') {return result.status;}- await copyBlobToClipboard(result.blob, clipboard);+ await copyImage(result.blob, clipboard);return 'ok';};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsxindex c7302f9f46..9e240fb2bb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx@@ -4,6 +4,7 @@ import type { ImageActions } from '@workbench/image-actions';import { HStack, Icon, Menu, Portal } from '@chakra-ui/react';import { galleryImageItemToGalleryImage, isGalleryImageItem, toGalleryItemRef } from '@features/gallery/contracts';+import { canCopyImage } from '@platform/browser/clipboard';import { Button, IconButton, MenuActionItem, MenuContent, Tooltip, useTooltipTriggerIds } from '@platform/ui';import { getGalleryCanvasImportMenuItems } from '@workbench/image-actions';import {@@ -96,9 +97,11 @@ export const PreviewActionStrip = ({{starButton}{item.kind === 'video' && onCopyCurrentFrame ? (<StripIconButton+ // Without a clipboard (plain HTTP) the control says why; a frame still loading only disables it.disabled={!isVideoFrameCopyAvailable}icon={CopyIcon}label={t('widgets.preview.copyCurrentFrame')}+ unavailableReason={canCopyImage() ? undefined : t('common.copyUnavailable')}onClick={copyCurrentFrame}/>) : null}@@ -162,16 +165,25 @@ const StripIconButton = ({disabled,icon,label,+ unavailableReason,onClick,}: {disabled?: boolean;icon: LucideIcon;label: string;+ unavailableReason?: string;onClick: (event: MouseEvent<HTMLButtonElement>) => void;}) => (- <Tooltip content={label}>- <IconButton aria-label={label} color="fg.muted" disabled={disabled} size="sm" variant="ghost" onClick={onClick}>- <Icon as={icon} boxSize="3.5" />- </IconButton>- </Tooltip>+ <IconButton+ aria-label={label}+ color="fg.muted"+ disabled={disabled}+ size="sm"+ tooltip={label}+ unavailableReason={unavailableReason}+ variant="ghost"+ onClick={onClick}+ >+ <Icon as={icon} boxSize="3.5" />+ </IconButton>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 2603f4c8cb..20234b5563 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -6,6 +6,7 @@ import { Badge, Flex, Text } from '@chakra-ui/react';import { useDraggable } from '@dnd-kit/core';import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { getAuthSession, refreshProtectedMediaCookie } from '@features/identity';+import { canCopyImage, copyImage } from '@platform/browser/clipboard';import { useMountEffect } from '@platform/react/useMountEffect';import { Button } from '@platform/ui/Button';import { GripHorizontalIcon } from 'lucide-react';@@ -461,10 +462,8 @@ const PreviewVideo = ({);const copyCurrentFrame = useCallback(async (): Promise<PreviewVideoFrameCopyResult> => {const video = videoRef.current;- const clipboardItem = globalThis.ClipboardItem;- const write = navigator.clipboard?.write?.bind(navigator.clipboard);- if (!clipboardItem || !write) {+ if (!canCopyImage()) {return { ok: false, reason: 'unsupported' };}@@ -512,11 +511,8 @@ const PreviewVideo = ({return { ok: false, reason: 'stale' };}- let item: ClipboardItem;-try {- item = new clipboardItem({ 'image/png': blob });- await write([item]);+ await copyImage(blob);} catch {return { ok: false, reason: 'clipboard-failed' };}@@ -981,9 +977,7 @@ const isVideoFrameReady = (video: HTMLVideoElement | null): video is HTMLVideoEl);const isVideoFrameCopyAvailable = (video: HTMLVideoElement | null): boolean =>- typeof globalThis.ClipboardItem !== 'undefined' &&- typeof navigator.clipboard?.write === 'function' &&- isVideoFrameReady(video);+ canCopyImage() && isVideoFrameReady(video);const encodeCanvasPng = (canvas: HTMLCanvasElement): Promise<Blob | null> =>new Promise((resolve, reject) => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsxindex 304e7b4605..fc3c39d73c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx@@ -93,7 +93,12 @@ void i18n.use(initReactI18next).init({resources: {en: {translation: {- common: { countOfTotal: '{{count}} of {{total}}', edit: 'Edit', generating: 'Generating' },+ common: {+ copyUnavailable: 'Copying needs HTTPS or localhost',+ countOfTotal: '{{count}} of {{total}}',+ edit: 'Edit',+ generating: 'Generating',+ },widgets: {canvas: { import: { control: 'Control Layer', raster: 'Raster Layer' } },gallery: {@@ -413,6 +418,35 @@ describe('Preview mixed media actions', () => {expect(onCopyCurrentFrame).toHaveBeenCalledOnce();});+ it('keeps frame copy reachable but unavailable, with its reason, where the page has no clipboard', async () => {+ const onCopyCurrentFrame = vi.fn();+ // As on a plain-HTTP origin, where the browser leaves `navigator.clipboard` undefined.+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });++ try {+ await render(+ <PreviewActionStrip+ actions={{ setItemsStarred: vi.fn() } as unknown as ImageActions}+ density="full"+ isVideoFrameCopyAvailable={false}+ item={sharedVideo}+ onCopyCurrentFrame={onCopyCurrentFrame}+ onOpenMenu={() => undefined}+ />+ );+ const copyFrame = host!.querySelector<HTMLButtonElement>('[aria-label="Copy Current Frame"]')!;++ // Not natively disabled: that would take it out of the tab order and hide why.+ expect(copyFrame.disabled).toBe(false);+ expect(copyFrame.getAttribute('aria-disabled')).toBe('true');+ await expect.element(copyFrame).toHaveAccessibleDescription('Copying needs HTTPS or localhost');+ await interact(() => copyFrame.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })));+ expect(onCopyCurrentFrame).not.toHaveBeenCalled();+ } finally {+ Reflect.deleteProperty(navigator, 'clipboard');+ }+ });+it('opens Edit onto the canvas layer destinations and sends the image to the chosen one', async () => {const actions = {copyImage: vi.fn(() => Promise.resolve()),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsxindex 389d57b11f..d8cd8e19d3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMetadataPanel.tsx@@ -3,9 +3,11 @@ import type { GalleryImage, GalleryImageMetadata, GalleryItem, GalleryItemKey }import { DataList, HStack, Icon, Stack, Tabs, Text } from '@chakra-ui/react';import { galleryImages, galleryVideos } from '@features/gallery';import { toGalleryItemKey } from '@features/gallery/contracts';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { IconButton, Scrollable, Tooltip } from '@platform/ui';import { JsonPreview } from '@platform/ui/JsonPreview';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { toaster } from '@platform/ui/toaster';import { useQuery } from '@tanstack/react-query';import {EMPTY_IMAGE_RECALL_CAPABILITIES,@@ -315,7 +317,14 @@ const MetadataRow = ({recallKind?: ImageRecallKind;}) => {const { t } = useTranslation();- const copyValue = useCallback(() => void navigator.clipboard.writeText(entry.value), [entry.value]);+ const canCopy = canCopyText();+ const copyValue = useCallback(+ () =>+ void copyText(entry.value).catch(() =>+ toaster.create({ description: t('common.clipboardBlocked'), title: t('common.couldNotCopy'), type: 'error' })+ ),+ [entry.value, t]+ );const recallValue = useCallback(() => {if (recallKind) {onRecall(recallKind);@@ -356,11 +365,17 @@ const MetadataRow = ({</IconButton></Tooltip>) : null}- <Tooltip content={t('common.copy')}>- <IconButton aria-label={t('common.copy')} color="fg.muted" size="sm" variant="ghost" onClick={copyValue}>- <Icon as={CopyIcon} boxSize="3" />- </IconButton>- </Tooltip>+ <IconButton+ tooltip={t('common.copy')}+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}+ aria-label={t('common.copy')}+ color="fg.muted"+ size="sm"+ variant="ghost"+ onClick={copyValue}+ >+ <Icon as={CopyIcon} boxSize="3" />+ </IconButton></HStack></DataList.ItemValue></DataList.Item>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsxindex 084ef48215..7cee3a8b24 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/project/ProjectWidgetView.tsx@@ -1,6 +1,7 @@import type { Project } from '@workbench/projectContracts';import { HStack, Input, Stack, Text } from '@chakra-ui/react';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { IconButton, Field, FieldLabel, Panel } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useProjectSyncSelector } from '@workbench/projects/syncStore';@@ -113,13 +114,14 @@ const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {const copyId = useCallback(async () => {try {- await navigator.clipboard.writeText(project.id);+ await copyText(project.id);notify.success(t('widgets.project.idCopied'));} catch {notify.error(t('common.couldNotCopy'), t('common.clipboardBlocked'));}}, [notify, project.id, t]);const handleCopyId = useCallback(() => void copyId(), [copyId]);+ const canCopy = canCopyText();return (<Stack gap="2">@@ -129,6 +131,8 @@ const DetailsSection = ({ project }: { project: ProjectPanelViewModel }) => {<HStack gap="1" minW="0"><MiddleTruncate fontFamily="mono" fontSize="xs" text={project.id} /><IconButton+ tooltip={t('widgets.project.copyId')}+ unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}aria-label={t('widgets.project.copyId')}color="fg.muted"size="sm"diff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.pyindex 911f88efaf..4841b651ae 100644--- a/tests/app/services/download/test_download_queue.py+++ b/tests/app/services/download/test_download_queue.py@@ -193,6 +193,86 @@ def test_mismatched_416_resume_keeps_in_progress_file(tmp_path: Path) -> None:assert in_progress_path.exists()[email protected](timeout=10, method="thread")+def test_refused_resume_keeps_the_partials_validator(tmp_path: Path) -> None:+ # The server ignores If-Range "v1" and sends the whole of a newer revision. Its ETag describes that revision,+ # not the partial on disk, so a later resume must not send it.+ source = AnyHttpUrl("https://test.com/changed.safetensors")+ destination = tmp_path / "changed.safetensors"+ in_progress_path = destination.with_name(destination.name + ".downloading")+ in_progress_path.write_bytes(b"old revision, first half")++ session = TestSession()+ new_revision = b"new revision"+ session.mount(+ str(source),+ TestAdapter(new_revision, headers={"ETag": '"v2"', "Content-Length": str(len(new_revision))}),+ )+ queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)+ queue.start()+ try:+ job = DownloadJob(source=source, dest=destination, etag='"v1"')+ queue.submit_download_job(job)+ queue.join()+ finally:+ queue.stop()++ assert job.status == DownloadJobStatus.PAUSED+ assert job.resume_required and job.resume_refused+ assert job.etag == '"v1"'+ assert in_progress_path.read_bytes() == b"old revision, first half"+ assert not destination.exists()+++class _RangeAdapter(TestAdapter):+ """Serves `data` under a Content-Disposition file name, honoring Range with HTTP 206 and If-Range by ETag."""++ def __init__(self, data: bytes, file_name: str, etag: str) -> None:+ super().__init__(data)+ self.data = data+ self.headers = {"Content-Disposition": f'attachment; filename="{file_name}"', "ETag": etag}++ def send(self, request, stream=False, **kwargs):+ headers = {**self.headers, "Content-Length": str(len(self.data))}+ byte_range = request.headers.get("Range")+ if byte_range and request.headers.get("If-Range") in (None, self.headers["ETag"]):+ start = int(byte_range.removeprefix("bytes=").removesuffix("-"))+ headers["Content-Length"] = str(len(self.data) - start)+ headers["Content-Range"] = f"bytes {start}-{len(self.data) - 1}/{len(self.data)}"+ return TestAdapter(self.data[start:], status=206, headers=headers).send(request, stream=stream, **kwargs)+ return TestAdapter(self.data, headers=headers).send(request, stream=stream, **kwargs)++[email protected]("etag", ['"v1"', None], ids=["validated", "unvalidated"])[email protected](timeout=10, method="thread")+def test_directory_resume_never_appends_to_a_file_the_response_does_not_name(tmp_path: Path, etag: str | None) -> None:+ # A directory download resumes its only partial file, but the response names the file. When it names another,+ # the range it sends continues nothing on disk.+ source = AnyHttpUrl("https://test.com/download/model")+ data = b"0123456789abcdefghij"+ partial = tmp_path / "old_name.safetensors.downloading"+ partial.write_bytes(data[:10])+ session = TestSession()+ session.mount(str(source), _RangeAdapter(data, "new_name.safetensors", '"v1"'))+ queue = DownloadQueueService(requests_session=session, requests_session_is_trusted=True)+ queue.start()+ try:+ job = DownloadJob(source=source, dest=tmp_path, etag=etag)+ queue.submit_download_job(job)+ queue.join()+ finally:+ queue.stop()++ assert not (tmp_path / "new_name.safetensors").exists()+ assert not (tmp_path / "new_name.safetensors.downloading").exists()+ assert job.status == DownloadJobStatus.PAUSED+ assert job.resume_required and job.resume_refused+ # The pause records the partial it kept, so a restart can find and remove it.+ assert job.download_path == tmp_path / "old_name.safetensors"+ assert job.etag == etag # the response's ETag describes the file it named, not this partial+ assert partial.read_bytes() == data[:10]++@pytest.mark.timeout(timeout=10, method="thread")def test_event_bus(tmp_path: Path, mm2_session: Session) -> None:event_bus = TestEventService()diff --git a/tests/app/services/model_install/test_install_staging_ledger.py b/tests/app/services/model_install/test_install_staging_ledger.pyindex 1abd9acf16..24b38e5e2e 100644--- a/tests/app/services/model_install/test_install_staging_ledger.py+++ b/tests/app/services/model_install/test_install_staging_ledger.py@@ -139,6 +139,39 @@ def test_a_v1_marker_from_an_earlier_release_is_restored_as_written()+ ("recorded", "refused"),+ [+ ({"resume_required": True, "resume_message": "Resume refused by server. Restart required."}, True),+ ({"resume_required": True, "resume_message": "Download interrupted. Resume required."}, False),+ (+ {+ "resume_required": True,+ "resume_refused": False,+ "resume_message": "Resume refused by server. Restart required.",+ },+ False,+ ),+ ],+ ids=["refused-before-the-flag", "interrupted", "flag-written"],+)+def test_a_refusal_recorded_only_in_the_message_restores_as_refused(+ ledger: InstallStagingLedger, models_path: Path, recorded: dict[str, Any], refused: bool+) -> None:+ # Releases before `resume_refused` recorded a refused resume only in its message. Restoring it as refused keeps the+ # partial, which may carry the refusing response's ETag, from resuming onto a newer revision.+ tmpdir = _staging_dir(models_path, "refused")+ entry = {"url": SOURCE, "etag": '"v2"', **recorded}+ _write_v1_marker(tmpdir, status="paused", files=[entry])++ [restored] = ledger.recoverable_installs()++ assert bool(restored.files[0].get("resume_refused")) is refused+ assert {key: value for key, value in restored.files[0].items() if key != "resume_refused"} == {+ key: value for key, value in entry.items() if key != "resume_refused"+ }++def test_a_marker_without_status_restores_as_waiting(ledger: InstallStagingLedger, models_path: Path) -> None:_write_v1_marker(_staging_dir(models_path, "no-status"), status="")@@ -233,6 +266,9 @@ def test_a_temporary_marker_left_by_a_crash_is_ignored_and_removed_with_the_markleftover = tmpdir / ".invokeai_install.json.k2j4f8.tmp"leftover.write_text('{"version": 1, "sta', encoding="utf-8")+ ledger.remove_dangling_staging([])+ assert (tmpdir / "weights.safetensors.downloading").read_bytes() == b"partial download"+[entry] = ledger.recoverable_installs()assert entry.status is InstallStatus.DOWNLOADS_DONEentry.staging.delete_marker()diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.pyindex e014c0bab4..959eec4025 100644--- a/tests/app/services/model_install/test_model_install.py+++ b/tests/app/services/model_install/test_model_install.py@@ -71,6 +71,7 @@ from invokeai.backend.model_manager.taxonomy import (ModelSourceType,ModelType,)+from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.backend.model_manager.model_manager_fixtures import * # noqa F403from tests.test_nodes import TestEventService@@ -1547,6 +1548,7 @@ def test_stop_preserves_restored_downloads_without_a_multifile_job("final_url": "https://cdn.example.com/weights-v1.safetensors","download_path": (tmpdir / "weights.safetensors").as_posix(),"resume_required": False,+ "resume_refused": False,"resume_message": None,}]@@ -2927,6 +2929,744 @@ def test_download_authorization_while_logged_in_to_hf(assert adapter.authorizations == [expected_authorization]+_SDXL_TURBO_SOURCE = HFModelSource(repo_id="stabilityai/sdxl-turbo", variant=ModelRepoVariant.Default)+_SDXL_TURBO_FILES_URL = "https://huggingface.co/stabilityai/sdxl-turbo/resolve/main/"+# Downloads run in URL order, so every other file of the repo is complete before this one starts. The file list+# assumes full-precision weights, which `sdxl_turbo_server` pins.+_SDXL_TURBO_LAST_FILE = "vae/diffusion_pytorch_model.safetensors"+++class _RepoFileServer:+ """Serves the sdxl-turbo repo files, records every download, and scripts failures per file.++ A "fail" attempt answers HTTP 500, which errors the install. A "short" attempt announces one byte more than it+ sends, which pauses the install with a resume-required part. (The repo's weight files are empty.)++ Each file carries an ETag naming its revision, unless `validators` is off. A Range request is recorded in+ `resumed` with its If-Range; it gets the rest of the file (HTTP 206) unless If-Range names another revision, which+ gets the whole current file (HTTP 200), as RFC 9110 specifies.+ """++ def __init__(self, session, repo_dir: Path) -> None:+ self.downloads: list[str] = []+ self.resumed: list[tuple[str, str, str | None]] = []+ self.scripted: dict[str, list[str]] = {}+ self.validators = True+ # Called with each downloaded file's name before the server answers.+ self.on_download: Callable[[str], None] | None = None+ self.files: dict[str, bytes] = {}+ self._revisions: dict[str, int] = {}+ for path in sorted(repo_dir.rglob("*")):+ if path.is_file():+ name = path.relative_to(repo_dir).as_posix()+ self.files[name] = path.read_bytes()+ session.mount(_SDXL_TURBO_FILES_URL + name, _RepoFileAdapter(self, name))++ def etag(self, name: str) -> str:+ return f'"{name}@{self._revisions.get(name, 1)}"'++ def publish(self, name: str, data: bytes) -> None:+ """Replace a file upstream with a new revision."""+ self.files[name] = data+ self._revisions[name] = self._revisions.get(name, 1) + 1++ def take_downloads(self) -> list[str]:+ downloads, self.downloads = self.downloads, []+ return downloads+++class _RepoFileAdapter(TestAdapter):+ def __init__(self, server: _RepoFileServer, name: str) -> None:+ super().__init__(b"")+ self.server = server+ self.name = name++ def send(self, request, stream=False, **kwargs):+ data = self.server.files[self.name]+ headers: dict[str, Any] = {"Content-Length": len(data)}+ if self.server.validators:+ headers["ETag"] = self.server.etag(self.name)+ if stream: # a download, not a metadata read of model_index.json+ self.server.downloads.append(self.name)+ if self.server.on_download is not None:+ self.server.on_download(self.name)+ attempts = self.server.scripted.get(self.name)+ attempt = attempts.pop(0) if attempts else None+ if attempt == "fail":+ return TestAdapter(b"", status=500).send(request, stream=stream, **kwargs)+ if attempt == "short":+ headers["Content-Length"] = len(data) + 1+ elif byte_range := request.headers.get("Range"):+ if_range = request.headers.get("If-Range")+ self.server.resumed.append((self.name, byte_range, if_range))+ if if_range is None or if_range == headers.get("ETag"):+ start = int(byte_range.removeprefix("bytes=").removesuffix("-"))+ headers["Content-Length"] = len(data) - start+ headers["Content-Range"] = f"bytes {start}-{len(data) - 1}/{len(data)}"+ return TestAdapter(data[start:], status=206, headers=headers).send(request, stream=stream, **kwargs)+ return TestAdapter(data, headers=headers).send(request, stream=stream, **kwargs)+++def sdxl_turbo_server(mm2_session, diffusers_dir: Path, monkeypatch: pytest.MonkeyPatch) -> _RepoFileServer:+ """Serve the sdxl-turbo repo to an installer that picks its full-precision weights on any device.++ The installer reads `ModelRepoVariant.Default` (an empty string) as no variant and guesses one from the torch dtype:+ fp16 weights on CUDA or MPS, full-precision ones on CPU. Pinning the dtype fixes the files these tests script.+ """+ import torch++ monkeypatch.setattr(TorchDevice, "choose_torch_dtype", staticmethod(lambda device=None: torch.float32))+ return _RepoFileServer(mm2_session, diffusers_dir)+++def _stop_halfway(job: ModelInstallJob, server: _RepoFileServer, names: list[str]) -> None:+ """Turn finished staged files back into half-written partials, as a pause leaves them."""+ for name in names:+ staged = job.local_path / name+ staged.unlink()+ staged.with_name(staged.name + ".downloading").write_bytes(server.files[name][: len(server.files[name]) // 2])+++def _installed_files(app_config: InvokeAIAppConfig, job: ModelInstallJob) -> set[str]:+ assert job.config_out is not None+ model_dir = app_config.models_path / job.config_out.path+ return {path.relative_to(model_dir).as_posix() for path in model_dir.rglob("*") if path.is_file()}++[email protected]("failures", [1, 2], ids=["one_failure", "repeated_failure"])[email protected](timeout=20, method="thread")+def test_restart_failed_refetches_files_deleted_by_the_failed_attempt(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ failures: int,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["fail"] * failures++ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.errored+ repo_files = server.take_downloads()+ assert repo_files[-1] == _SDXL_TURBO_LAST_FILE and len(repo_files) > 1+ assert job._staging is not None+ staging = job._staging.tmpdir+ assert staging is not None and not staging.exists()++ for _ in range(failures - 1):+ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.errored+ assert sorted(server.take_downloads()) == sorted(repo_files)+ assert not staging.exists()++ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert sorted(server.take_downloads()) == sorted(repo_files)+ assert _installed_files(mm2_app_config, job) == set(repo_files)+ assert not staging.exists()+ assert not _claim_path(staging).exists()++[email protected]("operation", ["restart_failed", "restart_file"])[email protected](timeout=20, method="thread")+def test_restart_of_a_paused_install_fetches_only_files_missing_from_staging(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ operation: str,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]++ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ assert any(part.resume_required for part in job.download_parts)+ repo_files = server.take_downloads()+ assert repo_files[-1] == _SDXL_TURBO_LAST_FILE and len(repo_files) > 1++ if operation == "restart_failed":+ mm2_installer.restart_failed(job)+ else:+ mm2_installer.restart_file(job, _SDXL_TURBO_FILES_URL + _SDXL_TURBO_LAST_FILE)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert server.take_downloads() == [_SDXL_TURBO_LAST_FILE]+ assert _installed_files(mm2_app_config, job) == set(repo_files)++[email protected](timeout=20, method="thread")+def test_retry_after_a_partial_restart_failed_fetches_every_file(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ # The pause keeps staging, so the first restart fetches one file; its failure then deletes staging while+ # job.download_parts lists only that file.+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short", "fail"]++ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ repo_files = server.take_downloads()++ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.errored+ assert server.take_downloads() == [_SDXL_TURBO_LAST_FILE]+ assert [str(part.source) for part in job.download_parts] == [_SDXL_TURBO_FILES_URL + _SDXL_TURBO_LAST_FILE]++ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert sorted(server.take_downloads()) == sorted(repo_files)+ assert _installed_files(mm2_app_config, job) == set(repo_files)+++ ("operation", "validators", "expected_resumed"),+ [+ ("restart_file", True, ["scheduler/scheduler_config.json"]),+ ("restart_failed", True, ["scheduler/scheduler_config.json", "unet/config.json"]),+ ("restart_failed", False, []),+ ],+ ids=["restart_file", "restart_failed", "restart_failed_without_validators"],+)[email protected](timeout=20, method="thread")+def test_restart_of_a_paused_install_resumes_partials_it_does_not_restart(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ diffusers_dir: Path,+ operation: str,+ validators: bool,+ expected_resumed: list[str],+) -> None:+ server = sdxl_turbo_server+ server.validators = validators+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ repo_files = server.take_downloads()+ partials = ["scheduler/scheduler_config.json", "unet/config.json"]+ _stop_halfway(job, server, partials)++ if operation == "restart_file":+ mm2_installer.restart_file(job, _SDXL_TURBO_FILES_URL + "unet/config.json")+ else:+ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert sorted(server.take_downloads()) == sorted([*partials, _SDXL_TURBO_LAST_FILE])+ assert server.resumed == [+ (name, f"bytes={len(server.files[name]) // 2}-", server.etag(name)) for name in expected_resumed+ ]+ assert _installed_files(mm2_app_config, job) == set(repo_files)+ assert job.config_out is not None+ installed = mm2_app_config.models_path / job.config_out.path+ for name in partials:+ assert (installed / name).read_bytes() == (diffusers_dir / name).read_bytes()++[email protected](timeout=20, method="thread")+def test_restart_never_splices_a_partial_onto_a_newer_upstream_revision(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ changed = "scheduler/scheduler_config.json"+ _stop_halfway(job, server, [changed])+ old_etag = server.etag(changed)+ # Same size, so only the validator can tell the revisions apart.+ new_revision = server.files[changed].replace(b"scaled_linear", b"SCALED_LINEAR")+ assert new_revision != server.files[changed] and len(new_revision) == len(server.files[changed])+ server.publish(changed, new_revision)++ mm2_installer.restart_file(job, _SDXL_TURBO_FILES_URL + _SDXL_TURBO_LAST_FILE)+ mm2_installer.wait_for_installs(timeout=10)++ # The server refused the stale range, so the part needs a restart instead of being completed from two revisions.+ assert server.resumed == [(changed, f"bytes={len(new_revision) // 2}-", old_etag)]+ assert job.status is InstallStatus.PAUSED+ assert [str(part.source) for part in job.download_parts if part.resume_required] == [+ _SDXL_TURBO_FILES_URL + changed+ ]++ server.take_downloads()+ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ # The refused part paused the job before the requested file, which follows it in URL order, was fetched.+ assert server.take_downloads() == [changed, _SDXL_TURBO_LAST_FILE]+ assert job.config_out is not None+ assert (mm2_app_config.models_path / job.config_out.path / changed).read_bytes() == new_revision++[email protected](timeout=20, method="thread")+def test_resume_never_splices_a_partial_onto_a_newer_upstream_revision(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ changed = "scheduler/scheduler_config.json"+ _stop_halfway(job, server, [changed])+ old_etag = server.etag(changed)+ new_revision = server.files[changed].replace(b"scaled_linear", b"SCALED_LINEAR")+ assert new_revision != server.files[changed] and len(new_revision) == len(server.files[changed])+ server.publish(changed, new_revision)++ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert server.resumed == [(changed, f"bytes={len(new_revision) // 2}-", old_etag)]+ assert job.status is InstallStatus.PAUSED+ assert [str(part.source) for part in job.download_parts if part.resume_required] == [+ _SDXL_TURBO_FILES_URL + changed+ ]++ mm2_installer.restart_failed(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert job.config_out is not None+ assert (mm2_app_config.models_path / job.config_out.path / changed).read_bytes() == new_revision++[email protected](timeout=20, method="thread")+def test_resume_restarts_a_partial_without_validators_from_zero(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ server = sdxl_turbo_server+ server.validators = False+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ changed = "scheduler/scheduler_config.json"+ _stop_halfway(job, server, [changed])++ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert server.resumed == []+ assert job.config_out is not None+ assert (mm2_app_config.models_path / job.config_out.path / changed).read_bytes() == server.files[changed]+++class _ShortOnceAdapter(TestAdapter):+ """Serves a file without validators, and records each download's Range header. With `short_first`, the first+ download announces one byte more than it sends, which pauses the install with the whole body left as a partial."""++ def __init__(self, data: bytes, short_first: bool = True) -> None:+ super().__init__(data, headers={"Content-Length": len(data)})+ self.short_first = short_first+ self.ranges: list[str | None] = []++ def send(self, request, stream=False, **kwargs):+ self.ranges.append(request.headers.get("Range"))+ if self.short_first and len(self.ranges) == 1:+ short = TestAdapter(self.stream, headers={"Content-Length": len(self.stream) + 1})+ return short.send(request, stream=stream, **kwargs)+ return super().send(request, stream=stream, **kwargs)++[email protected]("operation", ["resume_job", "restart_failed"])[email protected](timeout=20, method="thread")+def test_url_source_partial_restarted_from_zero_is_deleted_and_fetched_whole(+ mm2_installer: ModelInstallServiceBase,+ mm2_session,+ embedding_file: Path,+ operation: str,+) -> None:+ # A single-file URL source downloads into its staging directory and names the file from the response, so the+ # partial is not at the part's destination.+ url = "https://www.test.foo/download/unvalidated_embedding.safetensors"+ adapter = _ShortOnceAdapter(embedding_file.read_bytes())+ mm2_session.mount(url, adapter)+ job = mm2_installer.heuristic_import(source=url, config=ModelRecordChanges(type=ModelType.TextualInversion))+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ assert job._staging is not None and job._staging.tmpdir is not None+ assert [path.name for path in job._staging.tmpdir.glob("*.downloading")] == [+ "unvalidated_embedding.safetensors.downloading"+ ]++ getattr(mm2_installer, operation)(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert adapter.ranges == [None, None]++[email protected](timeout=20, method="thread")+def test_restored_download_path_outside_staging_is_never_used(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ mm2_session,+ embedding_file: Path,+ tmp_path: Path,+) -> None:+ # A marker from a moved or copied root can name a download path in some other folder.+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ url = "https://www.test.foo/download/outside_embedding.safetensors"+ adapter = _ShortOnceAdapter(embedding_file.read_bytes(), short_first=False)+ mm2_session.mount(url, adapter)+ elsewhere = tmp_path / "elsewhere" / "outside_embedding.safetensors"+ elsewhere.parent.mkdir()+ elsewhere.write_bytes(b"someone else's file")+ elsewhere_partial = elsewhere.with_name(elsewhere.name + ".downloading")+ elsewhere_partial.write_bytes(b"someone else's partial")+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}outside-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ job = ModelInstallJob(+ id=9910,+ source=URLModelSource(url=Url(url)),+ config_in=ModelRecordChanges(type=ModelType.TextualInversion),+ local_path=tmpdir,+ status=InstallStatus.PAUSED,+ )+ _stage(job, tmpdir)+ job._resume_metadata = {+ url: {"url": url, "canonical_url": url, "etag": '"v1"', "download_path": elsewhere.as_posix()}+ }+ mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)+ mm2_installer._restore_incomplete_installs()+ restored_job = mm2_installer.get_job_by_source(URLModelSource(url=Url(url)))[-1]+ assert restored_job.status is InstallStatus.PAUSED++ mm2_installer.resume_job(restored_job)+ mm2_installer.wait_for_installs(timeout=10)++ assert restored_job.complete, restored_job.error+ assert adapter.ranges == [None]+ assert elsewhere.read_bytes() == b"someone else's file"+ assert elsewhere_partial.read_bytes() == b"someone else's partial"++[email protected]("recorded_path", ["outside_staging", "missing"])[email protected](timeout=20, method="thread")+def test_restored_url_source_partial_without_validators_restarts_from_zero(+ mm2_installer: ModelInstallServiceBase,+ mm2_session,+ mm2_app_config: InvokeAIAppConfig,+ embedding_file: Path,+ tmp_path: Path,+ recorded_path: str,+) -> None:+ # A single-file URL source names its file from the response, so its partial is found inside the staging folder,+ # not at a recorded path that a moved root or an interrupted marker write left unusable.+ assert isinstance(mm2_installer, ModelInstallService)+ assert mm2_installer._wait_for_restore_complete(timeout=10)+ url = "https://www.test.foo/download/unvalidated_embedding.safetensors"+ data = embedding_file.read_bytes()+ adapter = _ShortOnceAdapter(data, short_first=False)+ mm2_session.mount(url, adapter)+ tmpdir = mm2_app_config.models_path / f"{TMPDIR_PREFIX}restored-{uuid.uuid4().hex}"+ tmpdir.mkdir()+ (tmpdir / "unvalidated_embedding.safetensors.downloading").write_bytes(data[: len(data) // 2])+ elsewhere = tmp_path / "elsewhere" / "unvalidated_embedding.safetensors"+ job = ModelInstallJob(+ id=9911,+ source=URLModelSource(url=Url(url)),+ config_in=ModelRecordChanges(type=ModelType.TextualInversion),+ local_path=tmpdir,+ )+ _stage(job, tmpdir)+ job._resume_metadata = {+ url: {+ "url": url,+ "canonical_url": url,+ "download_path": elsewhere.as_posix() if recorded_path == "outside_staging" else None,+ }+ }+ mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)+ mm2_installer._restore_incomplete_installs()+ restored_job = mm2_installer.get_job_by_source(URLModelSource(url=Url(url)))[-1]++ mm2_installer.resume_job(restored_job)+ [part] = restored_job.download_parts+ assert part.resume_from_scratch and part.resume_message+ mm2_installer.wait_for_installs(timeout=10)++ assert restored_job.complete, restored_job.error+ assert adapter.ranges == [None]+ assert restored_job.config_out is not None+ assert (mm2_app_config.models_path / restored_job.config_out.path).read_bytes() == data++[email protected]("case", ["refused", "unvalidated"])[email protected](timeout=20, method="thread")+def test_resume_never_sends_an_unguarded_range_for_a_partial_it_cannot_delete(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ monkeypatch: pytest.MonkeyPatch,+ case: str,+) -> None:+ # A partial that must restart but is held open (a Windows lock) cannot be deleted. Resuming it without If-Range+ # would splice: in the refused case upstream is known to have changed, in the unvalidated one nothing would tell.+ server = sdxl_turbo_server+ server.validators = case == "refused"+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ changed = "scheduler/scheduler_config.json"+ _stop_halfway(job, server, [changed])+ old_revision = server.files[changed]+ new_revision = old_revision.replace(b"scaled_linear", b"SCALED_LINEAR")+ server.publish(changed, new_revision)+ if case == "refused":+ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ resumed_before = list(server.resumed)+ partial = job.local_path / f"{changed}.downloading"+ real_unlink = Path.unlink++ def locked_unlink(path: Path, missing_ok: bool = False) -> None:+ if path == partial:+ raise PermissionError(13, "The process cannot access the file", str(path))+ real_unlink(path, missing_ok=missing_ok)++ with monkeypatch.context() as patch:+ patch.setattr(Path, "unlink", locked_unlink)+ with pytest.raises(InstallDownloadConflictError, match="scheduler_config.json"):+ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ assert server.resumed == resumed_before+ assert partial.read_bytes() == old_revision[: len(old_revision) // 2]++ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert server.resumed == resumed_before+ assert job.config_out is not None+ assert (mm2_app_config.models_path / job.config_out.path / changed).read_bytes() == new_revision++[email protected](timeout=20, method="thread")+def test_resume_after_a_refused_range_restarts_the_partial_from_zero(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["short"]+ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED+ changed = "scheduler/scheduler_config.json"+ _stop_halfway(job, server, [changed])+ old_revision, old_etag = server.files[changed], server.etag(changed)+ new_revision = old_revision.replace(b"scaled_linear", b"SCALED_LINEAR")+ server.publish(changed, new_revision)++ mm2_installer.resume_job(job)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.status is InstallStatus.PAUSED++ # The refusal recorded no validator of the new revision, so a second resume cannot pass If-Range with it.+ mm2_installer.resume_job(job)+ changed_part = next(part for part in job.download_parts if str(part.source) == _SDXL_TURBO_FILES_URL + changed)+ assert changed_part.resume_from_scratch and "refused" in (changed_part.resume_message or "")+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert server.resumed == [(changed, f"bytes={len(old_revision) // 2}-", old_etag)]+ assert job.config_out is not None+ assert (mm2_app_config.models_path / job.config_out.path / changed).read_bytes() == new_revision+++_CRASHED_PART = "unet/config.json"+++def _stage_a_crash_during(+ installer: ModelInstallService,+ app_config: InvokeAIAppConfig,+ server: _RepoFileServer,+ interrupted: str,+ case: str,+) -> tuple[Path, Path, bytes]:+ """Leave a staging folder as a crash while `interrupted` downloads leaves it.++ Returns the staging folder, the staged path of `interrupted` and that file's data.++ A crash leaves the marker as the last part start wrote it, with that part half written. Parts run in URL order.+ Copying the staging folder when the part after `interrupted` is requested captures the marker and finished files+ as such a crash leaves them; `interrupted` is then cut back to a half partial, or removed for "vanished". The+ original install then fails, which removes its own staging.+ """+ assert installer._wait_for_restore_complete(timeout=10)+ server.validators = case != "unvalidated"+ following = "unet/diffusion_pytorch_model.safetensors"+ crashed = app_config.models_path / f"{TMPDIR_PREFIX}crashed-{uuid.uuid4().hex}"+ jobs: list[ModelInstallJob] = []++ def crash_before(name: str) -> None:+ if name == following:+ assert jobs[0]._staging is not None and jobs[0]._staging.tmpdir is not None+ shutil.copytree(jobs[0]._staging.tmpdir, crashed)++ server.on_download = crash_before+ server.scripted[following] = ["fail"]+ jobs.append(installer.import_model(_SDXL_TURBO_SOURCE))+ installer.wait_for_installs(timeout=10)+ assert jobs[0].errored+ server.on_download = None+ server.take_downloads()+ assert jobs[0]._staging is not None and jobs[0]._staging.tmpdir is not None+ staged = crashed / jobs[0].local_path.relative_to(jobs[0]._staging.tmpdir) / interrupted+ data = server.files[interrupted]+ staged.unlink()+ if case != "vanished":+ staged.with_name(staged.name + ".downloading").write_bytes(data[: len(data) // 2])+ if case.startswith("refused"):+ marker_path = crashed / INSTALL_MARKER_FILENAME+ marker = json.loads(marker_path.read_text())+ for entry in marker["files"]:+ if entry["url"] == _SDXL_TURBO_FILES_URL + interrupted:+ entry["resume_required"] = True+ entry["resume_message"] = "Resume refused by server. Restart required."+ if case == "refused":+ entry["resume_refused"] = True+ else:+ del entry["resume_refused"]+ marker_path.write_text(json.dumps(marker))+ return crashed, staged, data+++ ("case", "expected_message"),+ [+ ("validated", None),+ ("refused", "refused"),+ ("refused_by_an_older_build", "refused"),+ ("unvalidated", "could not be checked"),+ ("vanished", "missing"),+ ],+)[email protected](timeout=30, method="thread")+def test_install_restored_after_a_crash_resumes_only_partials_its_marker_validates(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ case: str,+ expected_message: str | None,+) -> None:+ """The "refused" cases are a part the server already refused to resume, as its marker entry records (an older+ build recorded only the message); its validator still matches, so only that record keeps it from resuming."""+ assert isinstance(mm2_installer, ModelInstallService)+ crashed, _, data = _stage_a_crash_during(mm2_installer, mm2_app_config, sdxl_turbo_server, _CRASHED_PART, case)+ server = sdxl_turbo_server+ interrupted = _CRASHED_PART++ mm2_installer._restore_incomplete_installs()+ restored = mm2_installer.get_job_by_source(_SDXL_TURBO_SOURCE)[-1]+ assert restored._staging is not None and restored._staging.tmpdir == crashed+ mm2_installer.wait_for_installs(timeout=10)++ assert restored.complete, restored.error+ if case == "validated":+ assert server.resumed == [(interrupted, f"bytes={len(data) // 2}-", server.etag(interrupted))]+ else:+ assert server.resumed == []+ # Only the interrupted part is reported; the finished files it skipped, and those never started, are not.+ reported = {str(part.source): part.resume_message for part in restored.download_parts if part.resume_from_scratch}+ if expected_message is None:+ assert reported == {}+ else:+ assert list(reported) == [_SDXL_TURBO_FILES_URL + interrupted]+ assert expected_message in (reported[_SDXL_TURBO_FILES_URL + interrupted] or "")+ assert restored.config_out is not None+ assert (mm2_app_config.models_path / restored.config_out.path / interrupted).read_bytes() == data++[email protected]("case", ["refused", "unvalidated"])[email protected](timeout=30, method="thread")+def test_restore_keeps_a_partial_it_cannot_delete_and_leaves_the_install_paused(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+ monkeypatch: pytest.MonkeyPatch,+ case: str,+) -> None:+ # The partial must restart, but another process holds it open. Startup must neither resume it without a validator+ # nor treat the failure as an install error, which would delete the staging folder.+ assert isinstance(mm2_installer, ModelInstallService)+ staging_dir, staged, data = _stage_a_crash_during(+ mm2_installer, mm2_app_config, sdxl_turbo_server, _CRASHED_PART, case+ )+ partial = staged.with_name(staged.name + ".downloading")+ real_unlink = Path.unlink++ def locked_unlink(path: Path, missing_ok: bool = False) -> None:+ if path == partial:+ raise PermissionError(13, "The process cannot access the file", str(path))+ real_unlink(path, missing_ok=missing_ok)++ with monkeypatch.context() as patch:+ patch.setattr(Path, "unlink", locked_unlink)+ mm2_installer._restore_incomplete_installs()+ mm2_installer.wait_for_installs(timeout=10)++ restored = mm2_installer.get_job_by_source(_SDXL_TURBO_SOURCE)[-1]+ assert restored._staging is not None and restored._staging.tmpdir == staging_dir+ assert restored.status is InstallStatus.PAUSED+ assert json.loads((staging_dir / INSTALL_MARKER_FILENAME).read_text())["status"] == "paused"+ assert partial.read_bytes() == data[: len(data) // 2]+ assert sdxl_turbo_server.take_downloads() == []+ assert sdxl_turbo_server.resumed == []++[email protected](timeout=20, method="thread")+def test_restart_file_after_an_error_also_fetches_every_file_deleted_with_the_staging(+ mm2_installer: ModelInstallServiceBase,+ mm2_app_config: InvokeAIAppConfig,+ sdxl_turbo_server: _RepoFileServer,+) -> None:+ server = sdxl_turbo_server+ server.scripted[_SDXL_TURBO_LAST_FILE] = ["fail"]++ job = mm2_installer.import_model(_SDXL_TURBO_SOURCE)+ mm2_installer.wait_for_installs(timeout=10)+ assert job.errored+ repo_files = server.take_downloads()++ mm2_installer.restart_file(job, _SDXL_TURBO_FILES_URL + _SDXL_TURBO_LAST_FILE)+ mm2_installer.wait_for_installs(timeout=10)++ assert job.complete, job.error+ assert sorted(server.take_downloads()) == sorted(repo_files)+ assert _installed_files(mm2_app_config, job) == set(repo_files)++def test_restore_claims_downloads_done_staging_before_queueing(mm2_installer: ModelInstallServiceBase,mm2_app_config: InvokeAIAppConfig,@@ -3019,7 +3759,7 @@ def test_restart_failed_uses_parts_created_before_download_started(assert job.status == InstallStatus.WAITINGenqueue_remote_download.assert_called_once()- assert enqueue_remote_download.call_args.kwargs["clear_partials"] is True+ assert enqueue_remote_download.call_args.kwargs["restart_from_zero"] == {str(source.url)}@pytest.mark.parametrize("callback_name", ["_download_error_callback", "_download_cancelled_callback"])@@ -4040,15 +4780,17 @@ def test_resume_reports_restart_from_scratch_on_fresh_parts(assert "Partial file missing" in parts[0]["resume_message"]-def test_resume_does_not_report_restart_from_scratch_when_partial_exists(- mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch[email protected]("etag", ['"v1"', None], ids=["validated", "unvalidated"])+def test_resume_reports_restart_from_scratch_only_for_a_partial_it_cannot_validate(+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, etag: str | None) -> None:assert isinstance(mm2_installer, ModelInstallService)source = URLModelSource(url=Url("https://example.com/model.safetensors"))- old_part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors")+ old_part = DownloadJob(source=source.url, dest=tmp_path / "model.safetensors", etag=etag)old_part.bytes = 4old_part.download_path = tmp_path / "model.safetensors"- (tmp_path / "model.safetensors.downloading").write_bytes(b"1234")+ partial = tmp_path / "model.safetensors.downloading"+ partial.write_bytes(b"1234")job = ModelInstallJob(id=4243, source=source, config_in=ModelRecordChanges(), local_path=tmp_path)_stage(job, tmp_path)job.download_parts = {old_part}@@ -4061,7 +4803,14 @@ def test_resume_does_not_report_restart_from_scratch_when_partial_exists(parts = job.model_dump(mode="json")["download_parts"]assert len(parts) == 1- assert parts[0]["resume_from_scratch"] is False+ if etag is not None:+ assert parts[0]["resume_from_scratch"] is False+ assert parts[0]["etag"] == etag+ assert partial.read_bytes() == b"1234"+ else:+ assert parts[0]["resume_from_scratch"] is True+ assert parts[0]["resume_message"]+ assert not partial.exists()def test_404_download(mm2_installer: ModelInstallServiceBase, mm2_app_config: InvokeAIAppConfig) -> None:diff --git a/tests/app/services/shared/database/test_database_startup.py b/tests/app/services/shared/database/test_database_startup.pyindex d104d2fa1a..f9dcc90182 100644--- a/tests/app/services/shared/database/test_database_startup.py+++ b/tests/app/services/shared/database/test_database_startup.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom typing import Optionalimport pytest-from sqlalchemy import URL, delete+from sqlalchemy import URL, create_engine, delete, insert, selectfrom invokeai.app.services.config.config_default import DefaultInvokeAIAppConfig, InvokeAIAppConfigfrom invokeai.app.services.shared.database import database as database_module@@ -22,7 +22,17 @@ from invokeai.app.services.shared.database.startup import (open_migrated_database,redacted_database_url,)-from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import NoImageFiles+from invokeai.app.services.shared.sqlite_migrator.migration_loader import (+ PORTABLE_CUTOVER,+ MigrationBuildContext,+ build_migrations,+)+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import (+ MigrationBase,+ MigrationError,+ PortableMigration,+)+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import UPGRADE_DOCS_URL, NoImageFilesfrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.fixtures.database import external_test_db_url@@ -53,6 +63,35 @@ def test_a_url_is_shown_without_its_password() -> None:assert redacted_database_url("no url at all") == "***"+ ("url", "shown"),+ [+ (+ "mariadb+pymysql://invokeai@db/invokeai?password=s3cret",+ "mariadb+pymysql://invokeai@db/invokeai?password=***",+ ),+ (+ "mysql+pymysql://invokeai:s3cret@db/invokeai?charset=utf8mb4&passwd=0ther",+ "mysql+pymysql://invokeai:***@db/invokeai?charset=utf8mb4&passwd=***",+ ),+ ],+)+def test_a_password_in_the_query_is_masked_too(+ url: str, shown: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch+) -> None:+ # PyMySQL takes `password` and `passwd` from the query as the password.+ assert redacted_database_url(url) == shown++ logger = logging.getLogger("test_startup_redaction")+ # Exercise the real URL parsing and logging without requiring the optional MySQL driver.+ monkeypatch.setattr(database_module, "create_mysql_engine", lambda _url: create_engine("sqlite:///:memory:"))+ with caplog.at_level(logging.INFO, logger=logger.name):+ Database.open_url(url, logger).dispose()+ [message] = [record.getMessage() for record in caplog.records if record.name == logger.name]+ assert message == f"Connecting to database {shown}"+ assert "s3cret" not in caplog.text and "0ther" not in caplog.text++@pytest.mark.parametrize(("reported", "version"),[("8.4.3", (8, 4)), ("10.11.6-MariaDB-1:10.11.6+maria~ubu2204", (10, 11)), ("11.4.2-MariaDB-log", (11, 4))],@@ -212,6 +251,73 @@ def test_a_lock_the_server_released_is_taken_again(other.dispose()+@server_only+def test_updating_an_existing_server_database_warns_that_no_backup_was_made(+ empty_database: Database,+ _external_test_schema: Optional[URL],+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ assert _external_test_schema is not None+ # The test servers keep their own defaults; what is checked here is the warning.+ monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", 1)+ config = _config(tmp_path, db_url=_external_test_schema.render_as_string(hide_password=False))++ with caplog.at_level(logging.WARNING):+ init_database(config, LOGGER, NoImageFiles()).dispose()+ assert [record for record in caplog.records if record.levelno == logging.WARNING] == []++ # A newer version, with a migration this database has not had.+ def with_one_more(context: MigrationBuildContext) -> list[MigrationBase]:+ probe = PortableMigration(id="2099_01_01_probe", depends_on=PORTABLE_CUTOVER, callback=lambda context: None)+ return [*build_migrations(context), probe]++ monkeypatch.setattr(startup, "build_migrations", with_one_more)+ caplog.clear()+ with caplog.at_level(logging.WARNING):+ init_database(config, LOGGER, NoImageFiles()).dispose()++ [warning] = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING]+ assert _external_test_schema.render_as_string(hide_password=True) in warning+ if _external_test_schema.password:+ # The password may also spell the database name (CI uses "invokeai" for both), so look for it where the URL+ # writes it, after the user name.+ credentials = _external_test_schema.render_as_string(hide_password=False).split("://", 1)[1].rpartition("@")[0]+ assert credentials not in warning+ assert "makes no backup of a server database" in warning+ assert UPGRADE_DOCS_URL in warning+++@server_only+def test_a_server_database_a_newer_version_updated_is_refused_with_how_to_go_back(+ empty_database: Database,+ _external_test_schema: Optional[URL],+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ assert _external_test_schema is not None+ monkeypatch.setattr(startup, "MINIMUM_MAX_ALLOWED_PACKET", 1)+ config = _config(tmp_path, db_url=_external_test_schema.render_as_string(hide_password=False))+ init_database(config, LOGGER, NoImageFiles()).dispose()+ with empty_database.begin(write=True) as conn:+ conn.execute(insert(applied_migrations).values(migration_id="2999_01_01_from_a_newer_version"))+ with empty_database.begin(write=False) as conn:+ applied_before = set(conn.execute(select(applied_migrations.c.migration_id)).scalars())++ with pytest.raises(+ MigrationError, match="unknown applied migration IDs: 2999_01_01_from_a_newer_version"+ ) as refused:+ init_database(config, LOGGER, NoImageFiles())++ message = str(refused.value)+ assert "restore the backup you made before upgrading" in message+ assert "InvokeAI does not back up server databases" in message+ assert UPGRADE_DOCS_URL in message+ with empty_database.begin(write=False) as conn:+ assert set(conn.execute(select(applied_migrations.c.migration_id)).scalars()) == applied_before++def _take_when_free(database: Database) -> InstanceLock:# A killed session releases its locks as the server gets to it.deadline = time.monotonic() + 5diff --git a/tests/backend/minimax_h3/test_sampling.py b/tests/backend/minimax_h3/test_sampling.pyindex 84da07bf38..2f389d1ca0 100644--- a/tests/backend/minimax_h3/test_sampling.py+++ b/tests/backend/minimax_h3/test_sampling.py@@ -1,5 +1,8 @@"""Tests for the MiniMax H3 packed-sequence math and denoise-state construction."""+import dataclasses+from collections.abc import Iterator+import pytestimport torch@@ -10,7 +13,16 @@ from invokeai.backend.minimax_h3.packing import (video_latent_num_frames,)from invokeai.backend.minimax_h3.presets import MINIMAX_H3_VIDEO_FRAME_CHOICES, resolve_lowres_canvas_size-from invokeai.backend.minimax_h3.sampling import build_denoise_state, validate_canvas, validate_num_frames+from invokeai.backend.minimax_h3.sampling import (+ MiniMaxH3DenoiseState,+ MiniMaxH3EncodedReference,+ build_denoise_state,+ build_ref2va_denoise_state,+ validate_canvas,+ validate_num_frames,+)+from invokeai.backend.minimax_h3.scheduling_minimax_h3 import MiniMaxH3Scheduler+from invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3RotaryPosEmbedclass TestCanvas:@@ -135,7 +147,7 @@ class TestLowresCanvasResolution:fn(9, 1)-def _build_state(seed: int, with_keyframe: bool = False):+def _build_state(seed: int, with_keyframe: bool = False, device: str = "cpu"):kwargs = {}if with_keyframe:# One keyframe -> rows_per_frame = (4//2) * (4//2) = 4 condition rows of width 96.@@ -151,7 +163,7 @@ def _build_state(seed: int, with_keyframe: bool = False):num_audio_latents=8,num_inference_steps=4,seed=seed,- device=torch.device("cpu"),+ device=torch.device(device),**kwargs,)@@ -222,3 +234,73 @@ class TestDenoiseState:keyframe_anchors=("first",),clean_condition_rows=None,)+++def _build_ref2va_state(device: str) -> MiniMaxH3DenoiseState:+ # One image reference whose (1, 6, 2) latent packs into 3 condition rows at the micro geometry.+ return build_ref2va_denoise_state(+ text_token_tags=torch.tensor([1, 1, 0], dtype=torch.long),+ references=[MiniMaxH3EncodedReference(kind="image", video_rows=torch.zeros(3, 96), latent_shape=(1, 6, 2))],+ num_latent_frames=2,+ latent_height=4,+ latent_width=4,+ num_audio_latents=8,+ num_inference_steps=4,+ seed=0,+ device=torch.device(device),+ )+++_STATE_BUILDERS = {+ "fl2va": lambda device: _build_state(seed=0, with_keyframe=True, device=device),+ "ref2va": _build_ref2va_state,+}++_CUDA = pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA device"))+_MPS = pytest.param(+ "mps", marks=pytest.mark.skipif(not torch.backends.mps.is_available(), reason="requires MPS device")+)+++def _device_tensors(state: MiniMaxH3DenoiseState) -> Iterator[tuple[str, torch.Tensor]]:+ """Every tensor the denoise loop receives. The layout stays on CPU in float64 by design and is skipped."""++ def walk(value: object, path: str) -> Iterator[tuple[str, torch.Tensor]]:+ if isinstance(value, torch.Tensor):+ yield path, value+ elif isinstance(value, (list, tuple)):+ for index, item in enumerate(value):+ yield from walk(item, f"{path}[{index}]")+ elif isinstance(value, MiniMaxH3Scheduler):+ for name, item in vars(value).items():+ yield from walk(item, f"{path}.{name}")++ for field in dataclasses.fields(state):+ if field.name != "layout":+ yield from walk(getattr(state, field.name), field.name)+++class TestDevicePortableState:+ @pytest.mark.parametrize("device", ["cpu", _CUDA, _MPS])+ @pytest.mark.parametrize("builder", sorted(_STATE_BUILDERS))+ def test_no_float64_tensor_reaches_the_device(self, builder: str, device: str):+ # MPS has no float64: any float64 tensor in the state fails the request on Apple Silicon.+ state = _STATE_BUILDERS[builder](device)+ tensors = dict(_device_tensors(state))++ assert {"position_ids", "row_timestep_plan[0][0]", "scheduler.sigmas"} <= tensors.keys()+ assert state.layout.position_ids.dtype == torch.float64+ assert [path for path, tensor in tensors.items() if tensor.dtype == torch.float64] == []+ assert state.position_ids.dtype == torch.float32+ assert state.position_ids.device.type == device++ @pytest.mark.parametrize("device", [_MPS])+ @pytest.mark.parametrize("builder", sorted(_STATE_BUILDERS))+ def test_rope_runs_on_the_state(self, builder: str, device: str):+ state = _STATE_BUILDERS[builder](device)+ rope = MiniMaxH3RotaryPosEmbed().to(device)++ cos, sin = rope(state.position_ids)++ assert cos.shape == sin.shape == (state.layout.sequence_length, 6 * rope.rope_freq_dim)+ assert torch.isfinite(cos).all() and torch.isfinite(sin).all()diff --git a/tests/test_sqlite_migrator.py b/tests/test_sqlite_migrator.pyindex 48f40c4a38..83539a52ab 100644--- a/tests/test_sqlite_migrator.py+++ b/tests/test_sqlite_migrator.py@@ -1,4 +1,6 @@+import loggingimport sqlite3+from collections.abc import Callablefrom contextlib import closingfrom datetime import datetimefrom logging import Logger@@ -565,6 +567,186 @@ def test_migrator_backs_up_db(logger: Logger) -> None:assert backup_db_cursor.fetchone() is not None+def _warnings(caplog: pytest.LogCaptureFixture) -> list[str]:+ return [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING]+++def test_migrating_an_existing_database_warns_with_the_backup_path(+ tmp_path: Path, logger: Logger, caplog: pytest.LogCaptureFixture, no_op_migrate_callback: MigrateCallback+) -> None:+ # The fixture's logger has no parent for caplog's root handler to hear.+ logger.addHandler(caplog.handler)+ db = Database.open_sqlite(tmp_path / "invokeai.db", logger)+ first = Migration(from_version=0, to_version=1, callback=no_op_migrate_callback)+ created = Migrator(db)+ created.register_migration(first)+ created.run_migrations()++ updated = Migrator(db)+ updated.register_migration(first)+ updated.register_migration(Migration(from_version=1, to_version=2, callback=no_op_migrate_callback))+ caplog.clear()+ assert updated.run_migrations() is True+ db.dispose()++ [warning] = _warnings(caplog)+ assert updated._backup_path is not None and updated._backup_path.is_file()+ assert str(updated._backup_path) in warning+ assert "Older versions of InvokeAI cannot use it" in warning+ assert sqlite_migrator_impl.UPGRADE_DOCS_URL in warning+++def test_the_warning_is_logged_before_the_first_migration_runs(+ tmp_path: Path, logger: Logger, caplog: pytest.LogCaptureFixture, no_op_migrate_callback: MigrateCallback+) -> None:+ # A migration that fails, or crashes the process, must still leave the user the backup's path.+ logger.addHandler(caplog.handler)+ db = Database.open_sqlite(tmp_path / "invokeai.db", logger)+ first = Migration(from_version=0, to_version=1, callback=no_op_migrate_callback)+ created = Migrator(db)+ created.register_migration(first)+ created.run_migrations()++ seen_when_migrating: list[str] = []++ def failing_migrate(cursor: sqlite3.Cursor, **kwargs) -> None:+ assert updated._backup_path is not None and updated._backup_path.is_file()+ seen_when_migrating.extend(_warnings(caplog))+ raise ValueError("the migration failed")++ updated = Migrator(db)+ updated.register_migration(first)+ updated.register_migration(Migration(from_version=1, to_version=2, callback=failing_migrate))+ caplog.clear()+ with pytest.raises(MigrationError, match="the migration failed"):+ updated.run_migrations()+ db.dispose()++ [warning] = seen_when_migrating+ assert updated._backup_path is not None and str(updated._backup_path) in warning+ assert "Older versions of InvokeAI cannot use it" in warning+++def test_bootstrapping_and_migrating_a_legacy_database_warns_once_with_the_pre_bootstrap_backup(+ tmp_path: Path, logger: Logger, caplog: pytest.LogCaptureFixture, no_op_migrate_callback: MigrateCallback+) -> None:+ # A database from before the applied migration IDs: legacy rows only.+ db_path = tmp_path / "invokeai.db"+ with closing(sqlite3.connect(db_path)) as conn:+ conn.execute("CREATE TABLE migrations (version INTEGER PRIMARY KEY, migrated_at DATETIME);")+ conn.execute("INSERT INTO migrations (version) VALUES (0), (1);")+ conn.commit()+ logger.addHandler(caplog.handler)+ db = Database.open_sqlite(db_path, logger)+ migrator = Migrator(db)+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))+ migrator.register_migration(Migration(from_version=1, to_version=2, callback=no_op_migrate_callback))++ assert migrator.run_migrations() is True+ db.dispose()++ [warning] = _warnings(caplog)+ [backup] = tmp_path.glob("invokeai_backup_*.db")+ assert str(backup) in warning+ # The backup is of the database before the bootstrap wrote its records.+ with closing(sqlite3.connect(backup)) as conn:+ assert conn.execute("SELECT name FROM sqlite_master WHERE name = 'applied_migrations';").fetchone() is None+++def test_creating_or_reopening_a_database_does_not_warn(+ tmp_path: Path, logger: Logger, caplog: pytest.LogCaptureFixture+) -> None:+ logger.addHandler(caplog.handler)+ db = Database.open_sqlite(tmp_path / "invokeai.db", logger)+ migrations = [Migration(from_version=i, to_version=i + 1, callback=create_migrate(i)) for i in range(0, 3)]+ for _ in range(2):+ migrator = Migrator(db)+ for migration in migrations:+ migrator.register_migration(migration)+ migrator.run_migrations()+ db.dispose()++ assert _warnings(caplog) == []+++def test_migrating_a_memory_database_does_not_warn(+ migrator: Migrator, logger: Logger, caplog: pytest.LogCaptureFixture, no_op_migrate_callback: MigrateCallback+) -> None:+ logger.addHandler(caplog.handler)+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))+ migrator.run_migrations()+ migrator.register_migration(Migration(from_version=1, to_version=2, callback=no_op_migrate_callback))++ assert migrator.run_migrations() is True++ assert _warnings(caplog) == []+++def _record_unknown_applied_migration(cursor: sqlite3.Cursor) -> str:+ cursor.execute(+ "CREATE TABLE applied_migrations (migration_id TEXT PRIMARY KEY, legacy_version INTEGER UNIQUE, "+ "migrated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')));"+ )+ cursor.execute("INSERT INTO applied_migrations (migration_id) VALUES ('2999_01_01_future');")+ return "unknown applied migration IDs: 2999_01_01_future"+++def _record_unknown_legacy_version(cursor: sqlite3.Cursor) -> str:+ cursor.execute("CREATE TABLE migrations (version INTEGER PRIMARY KEY, migrated_at DATETIME);")+ cursor.execute("INSERT INTO migrations (version) VALUES (0), (1), (2);")+ return "unknown legacy migration version: 2"++[email protected]("record_newer_state", [_record_unknown_applied_migration, _record_unknown_legacy_version])+def test_a_database_a_newer_version_updated_is_refused_with_where_its_backups_are(+ tmp_path: Path,+ logger: Logger,+ no_op_migrate_callback: MigrateCallback,+ record_newer_state: Callable[[sqlite3.Cursor], str],+) -> None:+ db_path = tmp_path / "invokeai.db"+ with closing(sqlite3.connect(db_path)) as conn:+ problem = record_newer_state(conn.cursor())+ conn.commit()+ # A backup from an earlier update, which the error must neither name nor touch.+ earlier_backup = tmp_path / "invokeai_backup_20260101-120000.db"+ earlier_backup.write_bytes(b"earlier state")+ db = Database.open_sqlite(db_path, logger)+ migrator = Migrator(db)+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError) as refused:+ migrator.run_migrations()+ db.dispose()++ message = str(refused.value)+ assert problem in message+ assert f"InvokeAI writes one to {tmp_path} as invokeai_backup_<date>-<time>.db" in message+ assert sqlite_migrator_impl.UPGRADE_DOCS_URL in message+ assert earlier_backup.name not in message+ assert sorted(tmp_path.glob("invokeai_backup_*")) == [earlier_backup]+ assert earlier_backup.read_bytes() == b"earlier state"+++def test_a_tool_checking_a_database_a_newer_version_updated_gets_where_its_backups_are(+ tmp_path: Path, logger: Logger, no_op_migrate_callback: MigrateCallback+) -> None:+ db_path = tmp_path / "invokeai.db"+ with closing(sqlite3.connect(db_path)) as conn:+ _record_unknown_applied_migration(conn.cursor())+ conn.commit()+ db = Database.open_sqlite(db_path, logger)+ migrator = Migrator(db)+ migrator.register_migration(Migration(from_version=0, to_version=1, callback=no_op_migrate_callback))++ with pytest.raises(MigrationError, match="unknown applied migration IDs: 2999_01_01_future") as refused:+ migrator.has_pending_migrations()+ db.dispose()++ assert f"InvokeAI writes one to {tmp_path} as invokeai_backup_<date>-<time>.db" in str(refused.value)+ assert sqlite_migrator_impl.UPGRADE_DOCS_URL in str(refused.value)++def test_migrator_makes_no_changes_on_failed_migration(migrator: Migrator, migration_no_op: Migration, failing_migrate_callback: MigrateCallback) -> None: