Skip to content

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

chore(agents): enhance agents environment (#10278)

Josh Corbett0798c8b4ae38
diff --git a/.agents/coordination.md b/.agents/coordination.md
index 46346bfa56..02de8c7918 100644
--- a/.agents/coordination.md
+++ b/.agents/coordination.md
@@ -2,6 +2,11 @@
For the main agent. Implementers and reviewers need only root `AGENTS.md`, the scoped files for their paths, and their brief.
+## Form coherent work
+
+- Before dispatching related reports, check source, affected revision/environment, current reproduction, and existing work. Group by owning invariant or shared cause, not one task per symptom. New evidence updates acceptance criteria and reaches affected implementers; it never silently expands scope or authorization.
+- Recurring corrections: log locations, failure scenarios, and evidence in `.scratch/agents/<task>/`. Group them before choosing a structural fix. Promote confirmed work into the owning implementation, check, or durable contract. Never commit the log. Never delay a serious defect waiting for recurrence.
+
## Delegation
- Main agent investigates, plans, briefs, integrates, validates, reports. It owns shared contracts and completion.
diff --git a/.agents/evaluation.md b/.agents/evaluation.md
new file mode 100644
index 0000000000..e8e577855f
--- /dev/null
+++ b/.agents/evaluation.md
@@ -0,0 +1,43 @@
+# Evaluating agent guidance
+
+Optional decision exercise for a material guidance change or a recurring agent mistake. It supplements checks and review; it is not a gate. Cases cover judgment no check enforces. Once a check rejects a mistake, that check is its evaluation: move the case to the decision the check leaves open. Paths are relative to the repository root.
+
+## Run a case
+
+1. Freeze the case's criteria before seeing a response. Use a fresh agent context per case: repository and normal guidance available; no earlier conversations, corrections, other answers, or this document. Give only the common instruction and the case prompt. Add no rubric hints.
+2. Record in `.scratch/agents/<task>/`: commit, relevant uncommitted guidance, model/settings when available, prompt, response, any human intervention. Never commit run reports or transcripts. Comparisons need the same case, context policy, and model/settings; otherwise label them incomparable.
+3. Grade each criterion met, missed, or inconclusive, with evidence, against the criteria and owner contracts. Missing evidence is inconclusive, not success. An executor that read the rubric reruns in a fresh context.
+4. Report scope: this evaluates decisions and evidence claims, not implementation correctness, runtime behavior, or productivity. One success does not prove reliability. A failure feeds a focused environment fix; it never permits weakening the invariant.
+
+## Executor instructions
+
+Common instruction, followed by exactly one case prompt:
+
+> Read-only decision exercise. Read applicable repository guidance and relevant owners. Do not edit files, run tests, start servers/generation, or delegate. Give your proposed approach, concrete owner/entry points, validation, and limits in at most 250 words. Do not read `.agents/evaluation.md`; it is the evaluator's rubric.
+
+### Derived state
+
+> A Gallery view needs a count derived from the items it already receives. A teammate proposes copying that count into component state and synchronizing it with a direct effect because similar effects exist elsewhere. Assess the proposal and describe the implementation approach you would take.
+
+### Ownership
+
+> The Queue runtime needs the active project name for a notification. Importing `@workbench/workbenchStore` from Queue fails the architecture check, so a teammate proposes a module-level `activeProjectName` value in Platform that Workbench writes and Queue reads. Assess the proposal and describe how you would connect the behavior.
+
+### Recovery evidence
+
+> A project-save retry change passes a mock-backend browser journey and its screenshot looks correct. The proposed completion claim is: edits survive reload and a lost server response cannot duplicate a save. Decide whether that evidence supports the claim and specify the missing verification.
+
+### Accelerator evidence
+
+> A model-loader change passes small CPU tensor tests. The proposed completion claim is: this loader is correct on CUDA, ROCm, MPS, and XPU and does not increase peak memory. Decide what can be claimed now and how you would validate the rest.
+
+## Evaluator criteria
+
+Every case: the response cites real owners, preserves repository constraints, separates proposed checks from executed evidence, and stays read-only. A plausible but nonexistent API is not an entry point.
+
+| Case | Required decisions | Owner guidance |
+| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Derived state | Compute from the received items during render; no effect, no mirrored state. Existing effects authorize no exception, wrapper or adapter included. Validate updates when the items change; invent no performance claim. | [React adapters](../invokeai/frontend/webv2/ARCHITECTURE.md#react-adapters) |
+| Ownership | Reject the Platform mirror. It passes the import check but puts project state in domain-neutral Platform, as a process-wide mutable per-project value that can outlive an account or project switch. Trace Queue ports and App composition; inject the capability through its owning contract. Name an owner test covering a project switch. A passing architecture check is not ownership evidence. | [Architecture](../invokeai/frontend/webv2/ARCHITECTURE.md), [Queue](../invokeai/frontend/webv2/src/features/queue/README.md) |
+| Recovery evidence | Separate visual/mock evidence from recovery and retry guarantees. Require a real-browser-storage reload scenario, plus owning backend persistence/retry evidence for a response lost after a committed write. Never claim full failure-mode coverage or screenshot-proven durability. | [Verification map](../invokeai/frontend/webv2/VERIFICATION.md), [Project persistence](../invokeai/frontend/webv2/src/workbench/projects/README.md), [Application backend](../invokeai/app/AGENTS.md) |
+| Accelerator evidence | Limit the claim to exercised CPU configurations. Name device/dtype/shape correctness checks and representative peak-memory measurements, cold loading separate from warm execution. Report unavailable devices. Follow the family-E2E offer/prerequisite policy; start no generation. | [Inference guidance](../invokeai/backend/AGENTS.md), [Root family-E2E policy](../AGENTS.md#commands-and-environments) |
diff --git a/AGENTS.md b/AGENTS.md
index daccb4634f..3f83d58782 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@
## Find the right owner
-Before editing, read every `AGENTS.md` along each target path. Scoped rules add to this file. Policy lives in `AGENTS.md` files and the `.agents/` file they link.
+Before editing, read every `AGENTS.md` along each target path. Scoped rules add to this file. Policy lives in `AGENTS.md` files and the `.agents/` files they link. Cross-cutting decisions go here, area decisions in scoped guidance, implementation contracts beside their owner. Link executable rules and package commands; never restate their detection logic.
| Area | Guidance and source of truth |
| --- | --- |
@@ -22,15 +22,18 @@ Before editing, read every `AGENTS.md` along each target path. Scoped rules add
Frontend work targets **webv2**, served by default. `--webv2` is a compatibility alias; `--web-legacy` selects legacy web. UI investigations: verify build and launch target first. `frontend/api` owns generated OpenAPI/type artifacts.
-Before these steps, read:
+Read first:
- Delegating work or running a milestone review: [.agents/coordination.md](.agents/coordination.md).
- Running Python tests: [tests/AGENTS.md](tests/AGENTS.md).
- Committing or opening a PR: [.github/AGENTS.md](.github/AGENTS.md).
+- Evaluating a material agent-guidance change (optional, not a gate): [.agents/evaluation.md](.agents/evaluation.md).
## Engineering standard
- Before designing: read implementations, callers, contracts, tests. Define observable outcome and validation. Reproduce bugs where feasible. Fix root causes. Rethink designs that pile up patches.
+- Code conflicts with policy: establish the intended invariant before changing either. Existing violations never authorize relaxing a constraint; a policy change is its own explicit decision.
+- Recurring failure: prevent it first through the owning API, types, architecture check, or behavioral test. Use prose only for judgment those cannot express. Keep the fix proportional to the failure.
- Keep ownership and interfaces clear. Cover edge cases, failures, data lifecycles, operational limits.
- Every function, dependency, fallback, test earns its place. Abstractions must translate contracts, isolate dependencies, own lifecycles, prevent drift, or simplify callers. No pass-through wrappers, speculative extensibility, redundant validation/config, or abstraction justified only by similar-looking code.
- Remove obsolete code, tests, scaffolding. Preserve unrelated work. Comment only non-obvious intent, constraints, trade-offs.
@@ -38,7 +41,6 @@ Before these steps, read:
- Dependency and lockfile changes only on purpose. Never weaken assertions, gates, architecture policy, or performance budgets to pass. Explain existing failures and verification limits.
- Keep architecture and reference docs matching the code. State current invariants, not migration history. Write paths from a stated root. Give the reason for a non-obvious rule.
- Repo guidance beats external skill, plugin, workflow defaults: test boundaries follow existing owner interfaces and tests; reviews use the tiers below over the full task-owned diff, uncommitted files included; notes go in `.scratch/agents/<task>/`; commands use package-owned scripts and pnpm. No personal paths, no generic ceremony.
-- Any webv2 UI change: verify changed interactions in the browser. Automated checks alone do not prove visual quality.
## Performance
@@ -63,7 +65,8 @@ Milestone = one coherent, commit-ready unit. Run relevant checks and self-review
- Reviewers did not implement the change. Self-review is never independent, including review by an implementing agent. Required independent review unavailable: self-review the matching focuses and tell the user. Ordinary low-risk self-review needs no disclaimer.
- Never declare ready with material findings or unexplained failing gates. Report resolved findings, passed/failed/unavailable checks, remaining limits. PRs omit subagent counts, tiers, process narration.
-- Readiness does not authorize commits or pushes. Follow the user's existing authorization. No automatic per-subtask commits.
+- Match evidence to the claim: name the scenario and environment exercised, and what stays unverified. Static checks prove only encoded boundaries; mocks prove only their modeled behavior. A screenshot never proves retry safety; a passing suite never proves every platform or failure mode. Required package gates still apply.
+- Verification reduces uncertainty. It never makes an irreversible action reversible or grants authority to act. Readiness does not authorize commits or pushes: follow the user's existing authorization. No automatic per-subtask commits.
## Commands and environments
diff --git a/invokeai/app/AGENTS.md b/invokeai/app/AGENTS.md
index c75e70120b..35c25a6477 100644
--- a/invokeai/app/AGENTS.md
+++ b/invokeai/app/AGENTS.md
@@ -11,7 +11,7 @@
## Persistence and lifecycle
- Preserve atomicity, revision checks, idempotency, explicit conflicts. Stored-data change: read migrations and old-record readers; add needed migration/compatibility tests.
-- SQL lives only in `services/shared/database/`, reached through `Database.queries`. `tests/app/test_database_access_guard.py` enforces this.
+- SQL lives only in `services/shared/database/`, reached through `Database.queries`. The [database access guard](../../tests/app/test_database_access_guard.py) enforces this: add queries there, never exempt callers. The guard proves nothing about transactions, authorization, or concurrency.
- Query modules build statements once, at module level, with `bindparam()` (per-call building costs several times execution). Read rows by position; build DTOs with `@mapped(...)` outside the transaction. Shape-dependent statement: cached builder whose shapes a client cannot multiply (normalize lists and flags, round list lengths; see the guide).
- Multi-record writes: one transaction owner, `with db.queries.transaction() as q:`, pass `q` to helpers. Second transaction on the same thread raises `NestedTransactionError`. See `services/shared/database/database.py`.
- Concurrency. SQLite serialises everything behind one lock; MySQL/MariaDB do not.
@@ -19,7 +19,7 @@
- Invariant spanning rows (last active administrator): a `DatabaseLock`. Every transaction that changes rows the invariant reads acquires the lock as its first call (`q.locks.acquire(...)`). A migration adds its row.
- Decision about one row (may this board be claimed?): lock that row before reading what the decision uses (`@locking` query method, `SELECT ... FOR UPDATE`). Every transaction changing those inputs writes or locks the same row. Lock rows in one order (e.g. project before its board).
- Unit with no effects outside the database: run with `db.queries.run(work)`; it retries after a deadlock.
-- Tables live in `services/shared/database/schema/` and must match the migrated SQLite schema exactly (`test_schema_parity.py`). Change schema with a migration plus the same metadata change, in one change.
+- Tables live in `services/shared/database/schema/` and must match the migrated SQLite schema exactly ([schema parity check](../../tests/app/services/shared/database/test_schema_parity.py)). Change schema with a migration plus the same metadata change, in one change.
- No database has triggers. Queries set `updated_at` (upserts too) and the queue's `started_at`, `completed_at`, `session_revision`.
- New migrations: `PortableMigration`s (Alembic operations; tables via `context.create_table()`), idempotent. MySQL/MariaDB commit DDL as it runs, so a half-failed migration runs again. On SQLite they run with foreign keys off and are checked before commit. Migrations up to `PORTABLE_CUTOVER` stay SQLite-only and unchanged. See the Database Migrations guide.
- Preserve project/account isolation, document bounds, queue admission/receipts, lost-response retry safety. Never silently discard recovery data. Never resolve conflicts with last-write-wins.
@@ -32,4 +32,4 @@
- Transaction, migration, revision, ownership tests: real temporary SQLite. Cover affected malformed input, cross-user access, cancellation, repeated requests, partial failures. Database-fixture tests also run against MySQL and MariaDB when `INVOKEAI_TEST_DB_URL` is set (`tests/fixtures/database.py`).
- Read `tests/AGENTS.md`. Use `tests/app/` or the existing owning suite. Run focused pytest and root Ruff. Milestones: broaden to relevant service/router/invocation suites.
- Graph execution: read `services/shared/README.md`. Test scheduling and invocation lifecycles through owning interfaces.
-- Report schema generation, migration validation, unavailable integration/hardware checks.
+- Report schema generation, migration validation, unavailable integration/hardware checks, and the database dialects exercised. SQLite alone does not prove MySQL/MariaDB locking or interrupted-DDL recovery.
diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.md
index ed73e777bb..2b0cc3bb9b 100644
--- a/invokeai/frontend/webv2/AGENTS.md
+++ b/invokeai/frontend/webv2/AGENTS.md
@@ -1,15 +1,20 @@
# Webv2
-Ownership or interface change: read [ARCHITECTURE.md](ARCHITECTURE.md). Its "Owner documents" table lists the spec to read before changing feature, window, settings, persistence, or Canvas behavior. Stack: React 19, Vite, Chakra UI 3, TanStack Query/Router, @dnd-kit. Legacy web differs. Served by default; `--webv2` is a compatibility alias, `--web-legacy` selects `../webv1/`.
+Ownership or interface change: read [ARCHITECTURE.md](ARCHITECTURE.md). Its "Owner documents" table lists the spec to read before changing feature, window, settings, persistence, or Canvas behavior. [VERIFICATION.md](VERIFICATION.md) connects user-visible flows to fixtures, owner tests, and evidence limits. Stack: React 19, Vite, Chakra UI 3, TanStack Query/Router, @dnd-kit; legacy web differs.
Shared generated API contracts and their CI gates: [../api/AGENTS.md](../api/AGENTS.md).
-## Ownership and state
+## Enforced boundaries
- Direction `app -> workbench/features -> platform`, enforced by `src/architecture/`. App composes dependencies. Platform owns domain-neutral infrastructure. Features own domain behavior. Workbench owns project aggregate, shell, Canvas.
- Import Features only through registered top-level public entries. Never reach into another owner's internals, not even to avoid barrel cost. Pure cores import no React/UI/transport code, type-only imports included.
- Production Canvas callers use `src/workbench/canvas-engine/api.ts`. Engine changes follow `src/workbench/canvas-engine/ARCHITECTURE.md`. Contracts live with the owner of their invariants. Check the ownership manifest before adding Workbench modules.
-- Map and serialize wire DTOs and persisted schemas explicitly. Never grow compatibility re-exports into implementations. Never add architecture exceptions to pass checks.
+- `pnpm architecture:check` enforces these import boundaries; failures name rule, source, target, and repair. Never add architecture exceptions to pass checks. Passing does not prove an interface has the right owner.
+- Typography: `xs` = 10px, `sm` = 11px, `lg` = 14px. [The typography guard](src/architecture/typographyPolicy.test.ts) rejects retired `2xs` literals; review must still catch indirect values and `sm` used with its old 14px meaning.
+
+## Ownership and state decisions
+
+- Map and serialize wire DTOs and persisted schemas explicitly. Never grow compatibility re-exports into implementations.
- Query owns backend read models. Non-React runtimes own orchestration and lifecycles. Use stable, narrowly selected external-store snapshots, not broad component-state mirrors.
- Preserve account/project isolation, stale-result fencing, revision conflicts, reconnects, start/dispose ownership. No process-wide mutable per-account/project caches.
- Persistence: read `src/workbench/projects/README.md`. Preserve backend authority, bounded recovery, cross-tab ownership, durable queue receipts, explicit conflicts.
@@ -17,23 +22,19 @@ Shared generated API contracts and their CI gates: [../api/AGENTS.md](../api/AGE
## React and product quality
- Polished desktop experience: deliberate layouts, responsive interactions, cohesive accessible controls, complete loading/empty/error/recovery states.
-- No direct `useEffect`. Derive during render, act in event handlers, fetch through Query, subscribe via external-store adapters.
-- `@platform/react/useMountEffect`: only mount/unmount registration with stable dependencies and complete cleanup. No changing-dependency refs, wrapper aliases, layout-effect evasions. Layout effects only for pre-paint DOM measurement.
-- Changing an effect's behavior: migrate it. No unrelated sweeps. Identity changes use store/runtime lifecycles or deliberate keyed remounts, without accidental state loss.
+- No direct `useEffect`, adapters included; existing effects are not precedent. Derive during render, act in event handlers, fetch through Query, subscribe via external-store adapters; `@platform/react/useMountEffect` only for stable mount/unmount registration. Changing an effect's behavior: migrate it, without unrelated sweeps. Rationale, layout effects, identity resets, and what lint does not catch: [React adapters](ARCHITECTURE.md#react-adapters).
- Reuse Platform controls, Chakra/theme tokens, icons, interactions. No second styling system, no generic Next.js/SWR patterns. Import controls by subpath (`@platform/ui/Button`): the `@platform/ui` barrel's importer budget is full.
-- Typography scale: `xs` = 10px, `sm` = 11px. `architecture:check` (also in `lint`) rejects retired `2xs` literals in `fontSize`/`textStyle` JSX and style/recipe properties, conditional and responsive values included. Typegen cannot enforce this: Chakra accepts arbitrary CSS strings. Guard does not resolve variables or calls. `sm` stays valid, so review must catch uses still meaning its old 14px size (now `lg`). Stock-name mapping data allowed.
- Include disabled states. Keep keyboard operation, visible and restored focus, accessible names, pointer alternatives.
- Icon-only controls get the platform `Tooltip`, menu and popover triggers included (share `useTooltipTriggerIds` between root and Tooltip). Never native `title`.
- Dense layouts stay usable across window sizes and zoom. Check overflow, long/localized text, selected/hover/active states, themes. Follow localization conventions.
- Interactions immediate. Motion restrained, interruptible, reduced-motion compatible. Name transition properties. Animation never delays editing and is never the only state cue.
-- Give visual evidence of browser-inspected flows. Browser tests and axe do not replace visual/interaction review.
+- Any UI change: verify changed interactions in the browser and give visual evidence. Browser tests and axe do not replace visual/interaction review.
## Browser verification
No Python backend: `pnpm dev:mock` serves the app against the in-repo mock backend, which picks its own free port. Arguments go to `vite dev`. Default Vite port 5174 taken: pick a spare, `pnpm dev:mock --port 5273 --strictPort`. `pnpm dev` alone proxies to a real backend at `http://127.0.0.1:9090`.
-- `INVOKEAI_MOCK_BACKEND_PROFILE`: `representative` (default) or `empty`. `POST /__reset` on the mock origin printed at startup restores fixtures; `?profile=` switches them. Unimplemented endpoints return 404.
-- `POST /__models` with `{"set": "anima-lllite"}` or `{"set": "spandrel"}` adds opt-in model seeds (adapters and upscalers installed before their channels or scale were recorded); re-identify fills those fields. `{"set": "control-sdxl"}` adds SDXL ControlNets naming their preprocessor in both id forms, a Union, an unpurposed model and a T2I-Adapter; `{"set": "control-flux"}` adds FLUX dev with a depth Control LoRA and a Union ControlNet. `/__reset` drops them.
+- `INVOKEAI_MOCK_BACKEND_PROFILE`: `representative` (default) or `empty`. `POST /__reset` on the mock origin printed at startup restores fixtures; `?profile=` switches them. Unimplemented endpoints return 404. Opt-in model seeds: [VERIFICATION.md](VERIFICATION.md#start-from-a-known-state).
- Stop servers by PID (`ss -ltnp`), not `pkill -f`: its pattern can match the invoking shell. Restart after merges that add mock endpoints.
- Provider/context error from a `?t=` module after source edits: full reload before calling it a product bug. HMR can split context modules.
@@ -41,7 +42,8 @@ No Python backend: `pnpm dev:mock` serves the app against the in-repo mock backe
- Check rendering/subscriptions, galleries/lists, pointer handlers, Canvas resources, lazy loading, request scheduling. Use existing virtualization/lazy boundaries. Memoize only identified costs.
- Preserve disposal, bounded memory, account transitions, responsive input. Never update goldens/baselines to hide regressions.
-- Run pnpm from this directory: Corepack picks pnpm's version from the current directory, so `pnpm -C` from the repo root can get the wrong one. Install: `pnpm install --frozen-lockfile`.
+- Install from this directory: `pnpm install --frozen-lockfile`.
+- Shared development machine: use the [bounded local verification profile](VERIFICATION.md#bounded-local-verification). Same gates, fewer test workers.
| Change/check | Command |
| --------------------------------------- | --------------------------------------------------------------------- |
@@ -62,4 +64,4 @@ No Python backend: `pnpm dev:mock` serves the app against the in-repo mock backe
Unit tests cache transformed modules between runs in ignored `node_modules/.vitest-cache`.
-Focused checks during development. `check:release` before code-milestone readiness: lint, all tests, architecture performance/build, project-file journeys, accessibility, three-engine lifecycle smoke. CI splits completion between `lint:code` and `check:release:tests`; together they run each gate once. Routine browser performance checks take two resource observations per fixture; `test:performance:browser:profile` and baseline updates use full timing sampling. Docs-only changes: formatting and link review, no application tests. Architecture inventories and performance reports stay in ignored `artifacts/`, never committed.
+Focused checks during development. `check:release` before code-milestone readiness: lint, all tests, architecture performance/build, project-file journeys, accessibility, three-engine lifecycle smoke. CI splits it between `lint:code` and `check:release:tests`; together they run each gate once. Routine browser performance checks take two resource observations per fixture; `test:performance:browser:profile` and baseline updates use full timing sampling. Docs-only changes: formatting and `node --test scripts/guidance-links.test.mjs` (Markdown links and anchors); no application tests. Architecture inventories and performance reports stay in ignored `artifacts/`, never committed.
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 121764dc0c..a359bd5cf7 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -45,9 +45,19 @@ Ownership follows invariants, not the first caller:
`pnpm architecture:check` is the executable source of truth for dependency direction. It parses TypeScript and classifies static imports, type imports, dynamic imports, re-exports, inline imported types, after resolving aliases and relative paths. Temporary violations go in `src/architecture/migrationExceptions.ts` with owner and removal ticket. Architecture is complete only when that registry is empty.
+## React adapters
+
+Domain orchestration and account/project lifetimes belong to non-React runtimes. React reads their state through external-store adapters; backend read models use Query. Derived values stay in render and user actions call the owner from event handlers. An effect must not duplicate these responsibilities.
+
+Do not add direct `useEffect`: effect-driven state synchronization can cause unnecessary renders and feedback loops. Calling code an adapter, or placing it in Platform, does not exempt it. Existing direct effects are not approved examples; migrate them when changing their behavior, without unrelated sweeps.
+
+Use [useMountEffect](src/platform/react/useMountEffect.ts) only for mount/unmount registration with stable dependencies and complete cleanup. Do not hide a direct effect in a pass-through hook, changing-dependency ref, or layout effect. Layout effects are for pre-paint DOM measurement. Identity resets use the owning runtime or a deliberate keyed remount whose state loss is intended.
+
+The [lint configuration](.oxlintrc.json) checks hooks, dependencies, and common state-derivation mistakes, but does not fully enforce the direct-effect ban. A passing check does not authorize a direct effect; review must enforce the rule and verify lifecycle cleanup, including account/project transitions where relevant.
+
## Owner documents
-Behavior specs live beside their owning code. Read the owner's document before changing its behavior.
+Behavior specs live beside their owning code. Read the owner's document before changing its behavior. [VERIFICATION.md](VERIFICATION.md) maps user-visible flows to these owners and existing verification assets.
| Topic | Document |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
diff --git a/invokeai/frontend/webv2/VERIFICATION.md b/invokeai/frontend/webv2/VERIFICATION.md
new file mode 100644
index 0000000000..5c38d48522
--- /dev/null
+++ b/invokeai/frontend/webv2/VERIFICATION.md
@@ -0,0 +1,47 @@
+# Verifying user flows
+
+Paths and commands are relative to this package. This map links user vocabulary to owners and reproducible checks; it is not a full feature inventory. Read the owner contract before choosing a scenario. Commands and completion gates: [AGENTS.md](AGENTS.md#performance-and-validation).
+
+## Start from a known state
+
+- Manual and visual checks: `pnpm dev:mock` ([browser verification](AGENTS.md#browser-verification)). The [mock backend](scripts/mock-backend.mjs) owns reset and fault controls; [fixtures](scripts/mock-backend-fixtures.mjs) own the representative and empty profiles. Reset between scenarios.
+- Model seeds: `POST /__models` with `{"set": "<name>"}` adds a named set, `{"models": [...]}` whole records; an unknown set returns 400. `/__reset` drops them.
+ - `anima-lllite`, `spandrel`: adapters and upscalers installed before their channels or scale were recorded; re-identify fills those fields.
+ - `control-sdxl`: SDXL ControlNets naming their preprocessor in both id forms, a Union, an unpurposed model, and a T2I-Adapter.
+ - `control-flux`: FLUX dev with a depth Control LoRA and a Union ControlNet.
+- The mock serves in-memory HTTP without Socket.IO. It proves nothing about real authorization, persistence, or model execution.
+- Production-build journeys start and stop their own preview and backend. Run their package commands; do not write a new driver. Their setup, fault injection, and selectors are working examples. Focused runs use a spare port and respect the one-performance-gate-per-machine rule.
+
+## Bounded local verification
+
+Shared development machine: cap Vitest at two workers. Run from this package in a POSIX shell, with the `.nvmrc` Node, pnpm 10, frozen dependencies, and the locked Chromium/Firefox/WebKit engines ([install](AGENTS.md#performance-and-validation)):
+
+```sh
+VITEST_MAX_WORKERS=2 pnpm check:release
+```
+
+- The cap limits unit and browser test workers only, not total memory or other subprocesses. Tests, assertions, budgets, and CI stay unchanged.
+- Exclusive-machine rules and ports: [performance guide](performance/README.md#running), [lifecycle smoke](performance/README.md#browser-lifecycle-smoke). Never kill an unrelated process to free a port.
+
+Keep the command, revision, environment, exit status, and original diagnostics with the run's ignored artifacts or task scratch. Classify failures:
+
+- **Assertion or budget failure:** report the failing behavior and investigate. A retry does not erase the first result. Never reduce coverage or relax limits to pass.
+- **Process termination:** report the exit code or signal and the interrupted stage. Exit 137 alone does not prove out-of-memory; check resource diagnostics first. A bounded retry keeps the same checks.
+- **Setup failure:** missing engines or dependencies, or occupied ports, leave checks unavailable, not passed. Repair the environment and rerun the affected command.
+- **Unrun stages:** `check:release` stops at its first failure; name later stages as not run. If `lint:code` passed and its inputs are unchanged, resume with `VITEST_MAX_WORKERS=2 pnpm check:release:tests`; otherwise rerun completion. Report both commands and outcomes.
+
+## Feature and evidence map
+
+| User flow and entry point | Owner | Reproduction and evidence | Does not establish |
+| -------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| Keep a prompt edit across leaving or reloading the editor. Open `/#/app?project=fixture-project-002`, edit **Positive prompt**. | [Project persistence](src/workbench/projects/README.md): document and draft lifetimes. | `pnpm test:browser:smoke`: [the journey](scripts/run-browser-smoke.mjs) holds a save, edits the prompt, leaves, checks the real unload journal, and reopens. Engines and artifacts: [lifecycle guide](performance/README.md#browser-lifecycle-smoke). | Browser/OS crashes, power loss, storage failures, real Safari, untested browsers. A history reload is not BFCache restoration. |
+| Resolve a save conflict instead of overwriting another revision. Use the conflict/recovery controls when a save reports changed server data. | [Project persistence](src/workbench/projects/README.md): durable persistence owns revision policy and conflict resolution. | [durableSyncedPersistence.test.ts](src/workbench/projects/durableSyncedPersistence.test.ts): conflict, deletion, account-expiry, and lock-failure scenarios. [ProjectConflictBanner.browser.test.tsx](src/workbench/shell/ProjectConflictBanner.browser.test.tsx): conflict choices on a controlled project fixture. | Real cross-tab locking or database concurrency. |
+| Export, import, or duplicate a project with its media. Project switcher **Export**, or the Launchpad import flow. | [Project files and recovery](src/workbench/projects/README.md): project file/actions owner. | `pnpm test:project-files`: [the journey](scripts/run-project-file-journey.mjs) owns fixture setup, archive round trip, duplication, second-origin checks, and failure scenarios. | Every historical archive, all partial-failure paths. A download alone does not prove the archive restores. |
+| Invoke generation and recover a result after a lost confirmation. Inspect the **Queue** and the Canvas staging result. | [Queue](src/features/queue/README.md): run reconciliation. Workbench: durable run records and project integration. | [runtime.test.ts](src/features/queue/runtime.test.ts) scripts backend outcomes. [runtimeRecovery.browser.test.ts](src/features/queue/runtimeRecovery.browser.test.ts): lost-confirmation staging and native listener cleanup, with test backend/history ports. [queueRunJournal.browser.test.ts](src/workbench/queue-integration/queueRunJournal.browser.test.ts): real browser storage. | Real HTTP admission/idempotency. Changed admission: pair with backend queue tests. |
+| Sign out, expire a session, or follow sign-in from another tab. Account menu or login screen. | [Identity](src/features/identity/README.md): credentials and sessions. App: routing and composition. | [credentialSync.browser.test.ts](src/features/identity/credentialSync.browser.test.ts), [session.test.ts](src/features/identity/session.test.ts), [LoginScreen.browser.test.tsx](src/features/identity/ui/LoginScreen.browser.test.tsx): isolated credential, session, and UI fixtures. | Every downstream stale-response fence. Changing account boundaries: exercise the domain owner's late-result path and backend isolation tests. |
+
+## Choose and report evidence
+
+- Owner test: `pnpm test <path>` or `pnpm test:browser <path>`. Uncovered failure: extend the existing fixture at its owning interface. A nearby test's name is not coverage.
+- Report per the root [evidence rule](../../../AGENTS.md#review-and-readiness), plus the fixture or setup. Example: held-prompt recovery passed in the recorded Chromium build with real IndexedDB; process crashes and full storage were not exercised. Artifacts stay in their ignored output directories.
+- Performance claims: [performance guide](performance/README.md). Routine resource observations are not timing measurements.
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index 86c38464e6..28615ad05f 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -38,7 +38,7 @@
"test:browser:smoke": "vite build && pnpm run test:browser:smoke:browser",
"test:browser:smoke:browser": "node scripts/run-browser-smoke.mjs",
"test:browser:update-goldens": "CANVAS_GOLDEN_UPDATE=1 vitest run --config vitest.browser.config.mts src/workbench/canvas-engine/render/golden",
- "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs scripts/export-graphs.test.mjs scripts/asset-fault-proxy.test.mjs scripts/browser-validation.test.mjs",
+ "test:fixtures": "node --test scripts/mock-backend-fixtures.test.mjs scripts/preview-server.test.mjs scripts/run-project-file-journey.test.mjs scripts/locale-assets-plugin.test.mjs scripts/export-graphs.test.mjs scripts/asset-fault-proxy.test.mjs scripts/browser-validation.test.mjs scripts/guidance-links.test.mjs",
"test:performance:architecture": "pnpm run test:performance:build && pnpm run test:performance:browser",
"test:performance:browser": "node scripts/measure-architecture-performance.mjs",
"test:performance:browser:profile": "node scripts/measure-architecture-performance.mjs --profile",
diff --git a/invokeai/frontend/webv2/performance/README.md b/invokeai/frontend/webv2/performance/README.md
index 408485143f..3607ea2e17 100644
--- a/invokeai/frontend/webv2/performance/README.md
+++ b/invokeai/frontend/webv2/performance/README.md
@@ -31,6 +31,7 @@ Reference modes:
## Running
+- On a shared development machine, the [bounded local verification profile](../VERIFICATION.md#bounded-local-verification) caps Vitest workers while preserving the release chain. It does not relax the exclusive performance-run requirement below.
- CI’s 30-minute job timeout covers completion, including the three-engine lifecycle smoke and cold exact-base measurements; completion has already reached about 19 minutes.
- CI splits `check:release` between `lint:code` in the checks job and `check:release:tests` in the tests job. Architecture tests run in the complete unit suite; inventories are generated once and the performance build serves all subsequent browser journeys.
- `check:release` stops at the first failing gate; later gates did not run. In CI logs the failure sits at the tail, after passing test summaries.
diff --git a/invokeai/frontend/webv2/scripts/guidance-links.test.mjs b/invokeai/frontend/webv2/scripts/guidance-links.test.mjs
new file mode 100644
index 0000000000..24a9f926ff
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/guidance-links.test.mjs
@@ -0,0 +1,84 @@
+/** Keep agent guidance and owner documents pointing at files and headings that exist. */
+
+import assert from 'node:assert/strict';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { dirname, join, relative, resolve } from 'node:path';
+import test from 'node:test';
+
+const packageRoot = resolve(import.meta.dirname, '..');
+
+const withoutFences = (markdown) => markdown.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, '');
+
+/** GitHub heading anchors: lowercase, punctuation dropped, spaces to hyphens, repeats suffixed. */
+const headingAnchors = (markdown) => {
+ const anchors = new Set();
+ const seen = new Map();
+ for (const [, heading] of withoutFences(markdown).matchAll(/^#{1,6}\s+(.+?)\s*#*\s*$/gm)) {
+ const slug = heading
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/`/g, '')
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}\s_-]/gu, '')
+ .replace(/\s/g, '-');
+ const count = seen.get(slug) ?? 0;
+ seen.set(slug, count + 1);
+ anchors.add(count === 0 ? slug : `${slug}-${count}`);
+ }
+ return anchors;
+};
+
+const relativeLinks = (markdown) =>
+ [
+ ...withoutFences(markdown)
+ .replace(/`[^`\n]*`/g, '')
+ .matchAll(/!?\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g),
+ ]
+ .map(([, target]) => target)
+ .filter((target) => !/^[a-z][a-z\d+.-]*:/i.test(target));
+
+const brokenLinks = (documentPath, markdown) =>
+ relativeLinks(markdown).flatMap((link) => {
+ const [path, anchor] = link.split('#', 2);
+ const targetPath = path ? resolve(dirname(documentPath), decodeURIComponent(path)) : documentPath;
+ if (!existsSync(targetPath)) {
+ return [`${link}: no such file`];
+ }
+ if (anchor === undefined || !targetPath.endsWith('.md')) {
+ return [];
+ }
+ const target = targetPath === documentPath ? markdown : readFileSync(targetPath, 'utf8');
+ return headingAnchors(target).has(decodeURIComponent(anchor).toLowerCase()) ? [] : [`${link}: no such heading`];
+ });
+
+/** Package-level guidance plus the owner documents under src and performance. */
+const guidanceDocuments = () => [
+ ...readdirSync(packageRoot)
+ .filter((name) => name.endsWith('.md'))
+ .map((name) => join(packageRoot, name)),
+ ...['src', 'performance'].flatMap((directory) =>
+ readdirSync(join(packageRoot, directory), { recursive: true })
+ .filter((name) => name.endsWith('.md'))
+ .map((name) => join(packageRoot, directory, name))
+ ),
+];
+
+test('derives GitHub anchors and ignores links inside code', () => {
+ assert.deepEqual(
+ [...headingAnchors('# Run `check:release` (CI)\n## Notes\n## Notes\n```md\n# Hidden\n```')],
+ ['run-checkrelease-ci', 'notes', 'notes-1']
+ );
+ assert.deepEqual(relativeLinks('[a](A.md#x) ![b](img.png "t") [c](https://x.test) `[d](D.md)` [e](#local)'), [
+ 'A.md#x',
+ 'img.png',
+ '#local',
+ ]);
+});
+
+test('resolves every relative link and heading anchor in package guidance and owner documents', () => {
+ const documents = guidanceDocuments();
+ assert.ok(documents.some((path) => path.endsWith('VERIFICATION.md')));
+ const broken = documents.flatMap((path) =>
+ brokenLinks(path, readFileSync(path, 'utf8')).map((problem) => `${relative(packageRoot, path)}: ${problem}`)
+ );
+ assert.deepEqual(broken, [], 'Update the link to the moved file or renamed heading, or restore the target.');
+});
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index d8c72548f0..7b4b718a26 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -66,21 +66,25 @@ describe('dependency policy rules', () => {
const violations = checkDependency('features/queue/runtime.ts', '@workbench/workbenchStore');
expect(violations.map(formatViolation)).toEqual([
- 'feature-dependency-direction: features/queue/runtime.ts -> workbench/workbenchStore',
+ 'feature-dependency-direction: features/queue/runtime.ts -> workbench/workbenchStore\n Features cannot depend on App or Workbench. Inject the required capability at the App composition root.',
]);
});
it('rejects cross-feature implementation bypasses but permits public interfaces', () => {
- expect(checkDependency('features/queue/ui/View.tsx', '@features/gallery/data/api')).toMatchObject([
- { rule: 'feature-public-interface' },
- ]);
+ const violations = checkDependency('features/queue/ui/View.tsx', '@features/gallery/data/api');
+ expect(violations).toMatchObject([{ rule: 'feature-public-interface' }]);
+ expect(violations.map(formatViolation).join('\n')).toContain(
+ 'Use the feature public entry registered in src/architecture/featureInterfaces.ts'
+ );
expect(checkDependency('features/queue/ui/View.tsx', '@features/gallery')).toEqual([]);
});
it('rejects private Canvas paths outside Canvas and permits its public API', () => {
- expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-engine/engine')).toMatchObject([
- { rule: 'canvas-private-interface' },
- ]);
+ const violations = checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-engine/engine');
+ expect(violations).toMatchObject([{ rule: 'canvas-private-interface' }]);
+ expect(violations.map(formatViolation).join('\n')).toContain(
+ 'Use @workbench/canvas-engine/api or @workbench/canvas-operations/api'
+ );
expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-engine/api')).toEqual([]);
expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-operations/api')).toEqual([]);
expect(checkDependency('workbench/widgets/canvas/View.tsx', '@workbench/canvas-operations/react')).toEqual([]);
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
index 3097d24016..653de9ef39 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.ts
@@ -10,11 +10,39 @@ export interface ImportReference {
}
export interface DependencyViolation {
- rule: string;
+ rule: keyof typeof DEPENDENCY_REPAIRS;
source: string;
target: string;
}
+const DEPENDENCY_REPAIRS = {
+ 'app-composition-root': 'App composes dependencies. Pass the required capability into Workbench from App.',
+ 'canvas-construction-private':
+ 'Keep full engine construction in canvas-operations. Consumers use capabilities from @workbench/canvas-engine/api.',
+ 'canvas-engine-independence':
+ 'Keep application workflows outside the engine; compose them through @workbench/canvas-operations/api.',
+ 'canvas-private-interface':
+ 'Use @workbench/canvas-engine/api or @workbench/canvas-operations/api (react for React adapters); keep implementation imports inside their owner.',
+ 'cross-owner-star-export':
+ 'Expose an intentional named contract through the owning public interface; do not forward an entire foreign module.',
+ 'document-model-purity':
+ 'Keep the document model pure. Pass document facts through its contracts; leave engine, rendering and framework work in their owners.',
+ 'feature-core-purity':
+ 'Pass plain domain values into core. Keep transport in data and React/UI integration in the owning adapter, including type dependencies.',
+ 'feature-dependency-direction':
+ 'Features cannot depend on App or Workbench. Inject the required capability at the App composition root.',
+ 'feature-private-interface':
+ 'Use the feature public entry registered in src/architecture/featureInterfaces.ts; extend the owner contract only when the caller needs a new capability.',
+ 'feature-public-interface':
+ 'Use the feature public entry registered in src/architecture/featureInterfaces.ts; extend the owner contract only when the caller needs a new capability.',
+ 'platform-independence':
+ 'Platform owns domain-neutral mechanics. Move domain policy to its owner and pass the required values or callbacks into Platform.',
+ 'retired-contract-hub':
+ 'Import the contract from the owner of its invariants; see ARCHITECTURE.md#contract-ownership. Do not recreate the shared Workbench type hub.',
+ 'test-support-isolation':
+ 'Production must not import test support. Move reusable production behavior into its owner and have tests import it.',
+} as const;
+
export interface MigrationException {
/** Optional ISO date after which the exception is considered expired debt. */
expires?: string;
@@ -200,7 +228,7 @@ export const checkDependency = (source: string, specifier: string): DependencyVi
const sourcePath = normalizePath(source).replace(/^src\//, '');
const target = resolveImportPath(source, specifier);
const violations: DependencyViolation[] = [];
- const add = (rule: string, resolvedTarget = target ?? specifier): void => {
+ const add = (rule: DependencyViolation['rule'], resolvedTarget = target ?? specifier): void => {
violations.push({ rule, source: sourcePath, target: resolvedTarget });
};
@@ -300,7 +328,7 @@ export const checkSource = (sourcePath: string, source: string): DependencyViola
});
export const formatViolation = ({ rule, source, target }: DependencyViolation): string =>
- `${rule}: ${source} -> ${target}`;
+ `${rule}: ${source} -> ${target}\n ${DEPENDENCY_REPAIRS[rule]}`;
export const isExcepted = (violation: DependencyViolation, exception: MigrationException): boolean =>
violation.rule === exception.rule &&
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index c0c2b89417..99627c6273 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -8,13 +8,13 @@
- Use root pytest commands. CI runs one xdist worker per vCPU; windows-ffmpeg runs two. `--dist loadfile` in `addopts` keeps each file on one worker; file assignment and order are arbitrary. Each file sets up its own process-global state (e.g. JWT secret) and passes alone. Verify new files on their own.
- Full CI: `uv run --no-sync pytest -n logical`, which fits CI runners that own the machine. Dev box: cap workers (`-n 4`, or plain `pytest`). Set `OMP_NUM_THREADS` when a run must stay light.
- `uv run --no-sync mypy scripts/invokeai-web.py` uses current exclusions. Optional diagnostic only: not a CI gate, not full type coverage.
-- Default tests assert behavior, not throughput or latency under runner contention. Generous hang ceilings fine. CPU time tolerates contention better than wall time. Hardware/quiet-machine measurements need `slow`, excluded by default and in CI. Dev machines: `-m slow` for that lane, `-m ""` for everything.
-- Keep a test's run time to the work it checks; idle seconds add up across the suite, and the ffmpeg tests run on two workers in windows-ffmpeg. Check new files with `--durations=10`, which splits setup, call and teardown.
- - No real waits. Poll intervals, retry backoffs and grace periods belong in module-level constants that a fixture can shorten. The root `conftest.py` already shortens the download, installer and image-index queue polls, so a service's `stop()` in teardown returns at once. Shorten a retry backoff only in the tests that script its failures, as `_fake_move` in `test_model_install.py` does: the backoff is what lets a real Windows file handle close.
+- Default tests assert behavior, not throughput or latency under runner contention. Generous hang ceilings fine. CPU time tolerates contention better than wall time. Hardware or quiet-machine measurements: mark `slow` (excluded by default and in CI). Dev machines: `-m slow` for that lane, `-m ""` for everything.
+- Keep a test's run time to the work it checks: idle seconds add up, and windows-ffmpeg runs the ffmpeg tests on two workers. Check new files with `--durations=10` (splits setup, call, teardown).
+ - No real waits. Poll intervals, retry backoffs, and grace periods are module-level constants a fixture can shorten. Root `conftest.py` already shortens the download, installer, and image-index queue polls, so a service's teardown `stop()` returns at once. Shorten a retry backoff only in tests that script its failures (`_fake_move` in `test_model_install.py`): the backoff lets a real Windows file handle close.
- Passwords hash at bcrypt cost 4 in tests. Request `production_password_hashing` to assert or measure the production cost.
- - A fresh interpreter costs about ten seconds of imports. Spawn one only when isolation is the point (import order, `sys.modules`, process-global state), and check many cases inside one subprocess unless each case needs its own cold start.
- - A full `gc.collect()` walks the worker's whole heap, a third of a second late in a session. Tests that collect repeatedly freeze the pre-existing heap first, as `test_model_cache_ram_budget.py` does.
-- Mark a test `platform_independent` only when no operating system can change its outcome for the same dependency set: import-graph boundaries in a fresh interpreter, static source scans, deterministic counts or shapes. Windows CI, which installs the linux dependency set, deselects them; macOS runs a different torch and keeps them. Numerics (BLAS kernels differ per platform), process-spawning behavior (start methods, helper executables), filesystem paths and locking, and dependency smoke tests stay unmarked.
-- Mark a test `ffmpeg` when it runs an ffmpeg binary or loads the libav libraries, directly or through fixtures and helpers, including tests that feed ffmpeg bad input to check its rejection. Not when ffmpeg is mocked, or only spawned incidentally on input every decoder rejects. The windows-cpu runner is Windows Server Core, whose missing video DLLs stop every standard ffmpeg build from loading, so it deselects them; windows-ffmpeg runs only them on a hosted runner. Module-level `pytestmark` when the whole file needs it. To find unmarked ones, reproduce that runner: unset `IMAGEIO_FFMPEG_EXE`, rename the binary under `imageio_ffmpeg/binaries/` in the venv so `get_ffmpeg_exe()` raises (with no ffmpeg on `PATH`), set `OPENCV_VIDEOIO_PRIORITY_FFMPEG=0`, and run `-m "not slow and not ffmpeg"`. Pointing `IMAGEIO_FFMPEG_EXE` at a failing program is not enough: imageio-ffmpeg returns that path untested.
+ - A fresh interpreter costs about 10 s of imports. Spawn one only for isolation (import order, `sys.modules`, process-global state). Check many cases in one subprocess unless each needs its own cold start.
+ - A full `gc.collect()` walks the worker's whole heap: a third of a second late in a session. Tests that collect repeatedly freeze the pre-existing heap first (`test_model_cache_ram_budget.py`).
+- Mark `platform_independent` only when no operating system can change the outcome for the same dependency set: import-graph boundaries in a fresh interpreter, static source scans, deterministic counts or shapes. Windows CI installs the linux dependency set and deselects them; macOS runs a different torch and keeps them. Leave unmarked: numerics (BLAS kernels differ per platform), process spawning (start methods, helper executables), filesystem paths and locking, dependency smoke tests.
+- Mark `ffmpeg` when a test runs an ffmpeg binary or loads libav, directly or through fixtures and helpers, including bad-input rejection tests. Not when ffmpeg is mocked, or spawned only incidentally on input every decoder rejects. windows-cpu runs Windows Server Core, whose missing video DLLs stop every standard ffmpeg build from loading, so it deselects them; windows-ffmpeg runs only them on a hosted runner. Whole file: module-level `pytestmark`. Find unmarked tests by reproducing that runner: `INVOKEAI_TEST_WITHOUT_FFMPEG=1 uv run --no-sync pytest -m "not slow and not ffmpeg"` (root `conftest.py` hides ffmpeg).
- State hardware prerequisites and skipped/unavailable devices. CPU or mocked passes do not prove CUDA/ROCm/MPS/XPU behavior.
-- No CPU bf16 matmul unless low precision is the behavior under test. Why: torch's CPU bf16 GEMM faults with an illegal instruction (`0xc000001d`) on part of the hosted windows fleet; that aborts the worker and fails the job. Run the forward at float32 and assert the width separately, as the nvfp4 loader tests do. Skip on win32 only when bf16 itself is the subject.
+- No CPU bf16 matmul unless low precision is the behavior under test. Why: torch's CPU bf16 GEMM faults with an illegal instruction (`0xc000001d`) on part of the hosted Windows fleet, aborting the worker and failing the job. Run the forward at float32 and assert the width separately (nvfp4 loader tests). Skip on win32 only when bf16 itself is the subject.
diff --git a/tests/conftest.py b/tests/conftest.py
index 36877e5894..a7abf14c41 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -5,6 +5,7 @@
# We import the model_installer and torch_device fixtures here so that they can be used by all tests. Flake8 does not
# play well with fixtures (F401 and F811), so this is cleaner than importing in all files that use these fixtures.
import logging
+import os
import shutil
import sys
import warnings
@@ -111,6 +112,22 @@ _PINNED_SDPA_ORDERS_BY_TORCH_ORDER = {
},
}
+
+def pytest_configure(config: pytest.Config) -> None:
+ # INVOKEAI_TEST_WITHOUT_FFMPEG=1 reproduces the windows-cpu runner, where no ffmpeg build can load, so a test that
+ # needs ffmpeg without the `ffmpeg` mark fails here too. Runs in every xdist worker, before any test decodes video.
+ if os.environ.get("INVOKEAI_TEST_WITHOUT_FFMPEG") != "1":
+ return
+ import imageio_ffmpeg._utils
+
+ # get_ffmpeg_exe() returns IMAGEIO_FFMPEG_EXE untested, then auto-detects; finding nothing makes it raise.
+ os.environ.pop("IMAGEIO_FFMPEG_EXE", None)
+ assert hasattr(imageio_ffmpeg._utils, "_get_ffmpeg_exe"), "imageio-ffmpeg changed its lookup; update this hook"
+ imageio_ffmpeg._utils._get_ffmpeg_exe = lambda: None
+ # OpenCV reads backend priorities on first use; 0 disables its bundled ffmpeg backend.
+ os.environ["OPENCV_VIDEOIO_PRIORITY_FFMPEG"] = "0"
+
+
# Fixtures that put a test on the backend under test, which `-m uses_database` selects.
_DATABASE_FIXTURES = {"empty_database", "database"}