* Use craft-heif from craft-libs; remove crates/heif
PhotoCraft's HEIF decoder had drifted from LightCraft's by about 700 lines;
both now use craft-heif (storytold/craft-libs#784), built from LightCraft's
copy. HEIC colours now follow the HEVC VUI's range and matrix and libheif's
chroma upsampling. 8-bit files still open as 8-bit documents; a colour
description the VUI specifies now tags the image as an nclx did.
The codecs -> heif standalone exception ends with the local crate, and the
HEIF nextest step drops -p photocraft-heif, which no longer exists.
* Pin craft-heif to the merge of storytold/craft-libs#794
* heif: count the decoder's 16-bit buffer against max_alloc
* heif: match Apple's chroma upsampling; pin craft-heif to storytold/craft-libs#799
* heif: free the decoder's buffer before the HDR conversion and count that conversion's peak
* heif: hold the canvas the decoder really allocates to max_alloc
Fixes#8860
The Export As preview showed text in the wrong font when the PSD's font isn't installed, even though the canvas and the exported file looked fine.
The preview shrinks a copy of the doc with Image Size, and Image Size re-drew every text layer from its text, falling back to the default face when the font was missing. The same thing happened on any non-100% export and on Image › Image Size itself.
Now when the image is resized, text in a missing font keeps its own pixels (resized) instead of being re-drawn. Text in installed fonts still re-draws sharp as before.
**Test:** open `corpus/photoshop/text/point-fonts-mixed-runs.psd` (on a machine without Arial/Georgia/Times/Courier), press Ctrl+Alt+Shift+W, and the preview now matches the canvas.
Added a regression test too.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Text layers with unavailable fonts now retain their existing appearance when resizing images or applying arbitrary rotation, rather than losing or changing their cached pixels.
* Text using an installed font continues to be re-rendered during these operations, preserving the expected behavior.
* These improvements apply to 8-, 16-, and 32-bit documents, including text layers nested within groups.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary
The Home screen's Recent cards and rows opened their file with `open_path` directly, so the automation gate that File › Open Recent goes through (`menus::invoke`) never ran. A client confined to its automation roots could set `fileHandling.recentFiles` (an allowed preference) and `ui.click` a recent entry to open a file outside the read root. File › Open Recent already refuses the same file for automation input.
The Home list is the first entries of File › Open Recent's list, so an entry is Open Recent's item `i` (its index in `recent_files`). Synthetic input that opens a Home recent entry (grid card or list row) is now judged as `file.openRecent.{i}` through the same `automation_command` gate, and a refusal is reported like a failed open. A user's own click still opens the file. The file that opens is the clicked entry's own path.
- `crates/ui-egui/src/home_recent_ui.rs`: `open_recent_gate` checks the gate before `open_path` in `show_home_recent` (upstream moved the Home recent list here from `canvas/start_screen.rs` in #7231; this PR was merged with that change).
- `crates/ui-egui/src/home_recent_gate_tests.rs`: regression test `synthetic_click_on_a_home_recent_row_is_judged_as_open_recent`. The menu route is refused, a synthetic click on the entry opens nothing and reports `file.openRecent.0`, and a user's click on the same entry opens the file.
Closes#9773
## Tests
- CI runs the new test and the existing Home recent tests.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Recent-file clicks made during desktop automation now follow the configured authorization rules. Disallowed opens are blocked and reported in the status area, while regular user-initiated clicks continue to open files.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary
A client confined to its automation roots could write an action without running it: `actions.load {data}`, or `actions.insert` of any step. It could also bind the action to a key. None of that touches a file, so the policy allows it. Playback is gated by `Session::authorize`, which is installed only while automation drives the app. So when the user later pressed the key, or played the action from the panel, its file steps ran with the user's access, outside the roots. On 0.16.0 a planted open-and-save-a-copy action ran on one real keypress.
- **The mark:** `Action` gets an `automation` flag, persisted with the action list. It is set when an action is loaded, recorded, or has steps inserted, deleted, moved or toggled while `Session::authorize` is installed. It is also set when a step is journaled into the user's recording while `Session::authorize` is installed: an engine command a control client runs, a shell save or view step, or a call to an action (`actions_cmds::note_automation_step`). A background job keeps its request's origin: `dispatch` records on the job whether its request ran under a gate when it is admitted, and `apply_job` uses that, not the gate of whichever caller polls or waits on the job, and only for the recording that owns the step (`actions_cmds::note_step_origin`).
- **The gate:** `Session` gets `automation_gate`, the desktop's automation policy. `PhotocraftApp::new` fills it from `Services::automation_authorize`.
- **Playback:** engine playback (`actions.play`) and shell playback (`actions::play`) install that gate for a marked action that plays with none installed. Its steps, nested calls and the commands they run on their own behalf all meet the policy. A paused step dialog's command is judged under the same gate, and on resume each marked action takes its gate again, so its callers and the rest of a set keep their own gate.
- **Unchanged:** the user's own actions, and sets the user loads through Load Actions…, keep the user's access.
Not covered: File › Automate › Batch and droplets take a copy of the steps rather than the action, so they don't see the flag. That needs the Batch dialog to carry the action's origin, a separate change.
Closes#9782
## Tests run locally
- New `actions_cmds::tests::actions_automation_wrote_keep_its_gate_when_the_user_plays_them` (engine). A set loaded and a step inserted under an automation gate are refused when played without one, directly and through a nested call. The user's own action runs, a set the user loads is not marked, and the gate is removed after playback.
- New `actions::tests::a_users_key_plays_an_action_automation_wrote_under_its_gate` (ui-egui). A marked action bound to F9 and dispatched as the user's key press has its `file.openAs` step refused, and the refusal is reported.
- New `actions::tests::a_kept_gate_does_not_carry_into_the_rest_of_a_set_after_a_pause` (ui-egui). A set the user plays pauses at a marked action's step dialog; after OK the user's own action later in the set runs with the user's access.
- New `actions_cmds::tests::a_step_automation_runs_into_the_users_recording_keeps_its_gate` (engine, run by CI). The user records; a `file.new` run under a client's gate and a call to an action the client plays mark the recorded action, which is refused when played ungated. The user's own recording stays unmarked and plays.
- `a_kept_gate_does_not_carry_into_the_rest_of_a_set_after_a_pause` now also refuses the marked action's tail step `a2` and checks it is refused after OK (run by CI).
- New `jobs::tests::a_job_a_gated_client_starts_into_a_recording_keeps_its_gate_when_applied_ungated` (engine). A gated client starts a Gaussian Blur job during the user's recording; the gate is removed before `wait_job`; the recorded action is marked and, played ungated, its step is refused by `automation_gate`.
- New `jobs::tests::a_users_job_applied_while_a_gated_client_waits_stays_the_users` (engine). The user's job applied while a gated caller waits stays unmarked and plays; a gated client's job applied during a recording started after it does not mark that recording.
- The two `jobs::tests` above and the merge of `main` (commit 842ea34b4) were not built or run locally; CI runs them.
- `cargo test -p photocraft-engine --lib actions_cmds`: 33 passed. `cargo test -p photocraft-ui-egui --lib -- actions:: shortcut_dispatch`: 71 passed.
- With the kept gate switched off (`kept_gate` returning `None`), both new tests fail.
- `cargo fmt`.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Automation authorization remains in effect when automation-created or edited actions are replayed, including through shortcuts and nested actions.
* Actions loaded by automation retain their authorization policy during playback, while user-created and user-loaded actions remain distinct.
* **Bug Fixes**
* Playback no longer loses automation authorization when an action runs later. If a step is denied, it is not performed, and the temporary authorization check is cleared after playback.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Imported documents need durable conversion evidence and native pixel operations before XCF conversion can produce editable PhotoCraft data. This adds bounded document/report types, lossless pattern construction and `.pcraft` persistence, plus native HDR, percentile, noise, convolution, Average, coverage and matting kernels and checked Smart-filter mixing. Runtime color models/depths are retained; source attachments remain inert. Native SVG operations retain parsing, lowering, rendering and parser-tree destruction on one bounded worker, including nested resources; WebAssembly reports a controlled error for depths requiring native isolation.
Native filter corrections cover matte black points and signed HDR, extent-wide Smart-filter coverage, flat-image identity Auto Levels, opaque FillHoles capability, exact unselected channel preservation, coverage-preserving Average selection and bounded pattern expansion. Checked Smart-filter mixing rejects nonfinite native F32 samples, preserves unchanged Normal pixels without regenerating CMYK separations, and recovers representable alpha mixtures after an overflowing difference. HDR blend overflow retries use cold F64 arithmetic while retaining ordinary finite results and integer-depth behavior. Both opaque and alpha-bearing F32 mask recovery retain signed/HDR colors.
Stored pattern declarations remain lossless and inert. Dense PSD/PAT/ASL pattern export now checks dimensions and one shared plane-allocation budget before conversion. PAT/ASL report conversion errors; PSD/PSB report named omission warnings. Matching raw PSD pattern blocks remain verbatim. CMYK offsets retain the established brightness convention.
Command registration, XCF decoding and frontend workflows follow in dependent parts. The contributor entry is the author's existing chosen entry.
<!-- native-foundations-fixes-20261107:start -->
Small noise, convolution and point-operation edits admit their clipped work area on large owners while retaining output/workspace limits and whole-owner FillHoles bounds. HDR toning retains skipped transparent native samples. Normal Smart-filter strength interpolates stored CMYK/Lab/ink planes with premultiplied coverage, preserving unchanged channels. Bitmap Custom Pattern reads compact patterns in bounded row bands and ranks the complete map once. Embedded SVG isolation failures propagate independently of strict mode; ordinary invalid images can still be omitted, and private native parses share the complete-operation worker. The import-report regression now primes the layer blob cache and requires its specific limit diagnostic.
<!-- native-foundations-fixes-20261107:end -->
<!-- adversarial-5810371597:start -->
Import-report accounting uses portable fixed costs. HDR scene means use F64. Bitmap pattern ranking preflights a 256 MiB input/order/output budget, uses fallible allocation and heap-scratch-free sorting. Average uses the supplied image domain and retains one global mean across output tiles. Non-Normal Smart-filter coverage is classified once across the complete mixing extent. A fallible filter dispatcher and engine error conversion preserve checked native diagnostics and cancellation. Smart-filter engine integration remains in part 5 (#11032).
<!-- adversarial-5810371597:end -->
## Six-part series
Each branch is hosted in Terra854/photocraft, and every PR targets storytold/photocraft:main. Merge in the order below. Later drafts currently show cumulative diffs while prerequisites are unmerged; their descriptions link to isolated comparisons. Rebase each part onto current upstream main after its prerequisites merge, including squash-merge ancestry, and rerun affected checks before requesting review.
| Part | Upstream PR | Fork branch | Scope |
| --- | --- | --- | --- |
| 1 | [#11009](https://github.com/storytold/photocraft/pull/11009) | xcf-support-v2-01-import-data | Document/native-format data and pixel foundations |
| 2 | [#11029](https://github.com/storytold/photocraft/pull/11029) | xcf-support-v2-02-decoder | Bounded transport/records, precision, metadata, editable text and paths |
| 3 | [#11030](https://github.com/storytold/photocraft/pull/11030) | xcf-support-v2-03-effects-core | Native effect frames and primary tone/color/spatial/resource/transform adapters |
| 4 | [#11031](https://github.com/storytold/photocraft/pull/11031) | xcf-support-v2-04-effects-graphs | Remaining adapters, bounded graph lowering, coverage installation and source evidence |
| 5 | [#11032](https://github.com/storytold/photocraft/pull/11032) | xcf-support-v2-05-engine | Native commands, import preparation, historical choices, editing and persistence workflows |
| 6 | [#11033](https://github.com/storytold/photocraft/pull/11033) | xcf-support-v2-06-frontends | Desktop/web UI, CLI/MCP, translations, GPU diagnostics and qualification/docs |
The full integration remains preserved on `xcf-support-v2`; original #7098 remains available for reference.
## Validation
<!-- main-catchup-0d08cb7dd:start -->
Updated to upstream `main` at `0d08cb7dd` and restacked all six branches. Part 1 is `640a01f43`; full integration is `24cd17301`. The final six-part tree exactly matches the full integration tree.
The merge preserves both upstream's new tests/crop translations and the XCF historical-open tests/report labels. The automation adapter now preserves import-source protection across multiple granted read roots: relative source names cover every matching candidate so newly shadowing files cannot expose the original to overwrite, while absolute source names remain precise. Existing ordered reads and implicit-save provenance are retained. Read-only import source identity is kept independently of whether its library root grants an implicit Save target. Focused regressions cover source aliases, removed files, denied candidates, changing root precedence, and read-only library imports; the Windows escape fixture also uses a real junction when symlink privileges are unavailable. The new upstream UI import fixture also uses the native import outcome type.
Local validation passed affected host all-target checks, core and native frontend/automation unit and integration suites, forced-Vulkan GPU unit and integration suites, pinned IO corpora, strict all-target Clippy, formatting, layering, panel command dispatch, WASM, adversarial command tests, and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. The first two PR boundaries also passed independent all-target engine checks. Tests used the pinned craft-fonts input, four Rayon workers, serial tests for large fixtures and opt-level=0 for engine/UI test glue; pixel/format crates retained their repository settings. Quick mode uses small documents and does not enforce full-size budgets. The part 1 push triggered fresh [CI](https://github.com/storytold/photocraft/actions/runs/42885527754) and [SonarCloud](https://github.com/storytold/photocraft/actions/runs/42885527740) runs. After upstream approval, CI passed the Linux gate, Windows unit/integration tests, no-HEIF tests, pinned corpora and web build. SonarCloud's instrumented archive, coverage shards and actual scan remain skipped behind its token guard; its outer green status does not mean coverage ran. Catching up with main therefore retriggered normal tests but did not remove that SonarCloud skip. Older validation below remains evidence for its explicitly named earlier commits.
<!-- main-catchup-0d08cb7dd:end -->
<!-- average-no-extent-4517477902:start -->
Average no-extent follow-up at part 1 `f8ddb626f` (full integration `882def329`), carried through all six branches. The checked Average dispatcher now uses the requested `area` when no owner extent is supplied; an explicit extent retains its existing clipping behavior. Other filters, the Average pixel kernel and resource admission are unchanged.
The new regression fails against the preceding revision and passes with the fix. It covers `apply`, one-pixel explicit tiling, and the cancellable tiled API at 8/16/32-bit, signed/HDR colors, hidden RGB, native alpha preservation, unchanged source data and pixels outside the requested area. Validation passed the algorithm unit/integration suite (935 tests; 27 existing ignored), strict all-target algorithm Clippy, formatting, layering, WASM (24 crates plus HEIF), and independent all-target engine checks of the first two PR boundaries. The broader suites below remain evidence for their named earlier commits and were not rerun for this dispatcher-only follow-up.
<!-- average-no-extent-4517477902:end -->
<!-- review-20261110:start -->
Review follow-up at part 1 `a3144d559` (full integration `b5fd3e211`), carried through all six branches. Average admits long thin regions within its existing pixel/workspace budgets, clamps finite selection coverage, and uses owner extents for off-canvas replay. HDR Toning also adapts over the owner extent. Pattern GPU uploads now use bounded bands; the warning-free `document_to_psd` API returns `Result` on pattern export failure and reuses prepared pattern blocks. Warning-enabled exports retain explicit omission warnings.
Five filter regressions fail against the previous revision and pass with the fixes. Local validation passed 1,597 algorithm/compositor/GPU tests with Vulkan, all 129 GPU integration tests separately on DX12 with FXC (the app uses FXC when no bundled DXC is present), a separate forced DX12 pattern upload/readback test, 1,144 IO unit and 675 pinned IO integration tests, 10 affected engine tests, strict all-target Clippy, formatting, layering, WASM and quick CPU performance checks. The first two PR boundaries passed independent all-target engine checks. This Intel driver's DX12/DXC configuration rejects the unchanged `fs_adjust` pipeline (`0x80070057`); DX12/FXC and Vulkan both pass. The full workspace suite was not rerun; earlier broad evidence below remains tied to its named commits. Quick performance mode does not enforce full-size budgets.
A separate 24 MP signed/HDR RGBA32F public Average-kernel probe retained exact mean RGB and original alpha. Three alternating runs had medians of 1,274.713 ms before and 1,259.885 ms after; this small difference is within run variation and is not a speedup claim.
The Minor/Poor-tradeoff report-deserialization finding remains open and documented. Encoded records are capped at 32 MiB and individual arrays are bounded, but compact targets can still amplify transient decoded memory before aggregate validation rejects the report. Early shared-budget deserialization is not implemented in this follow-up.
<!-- review-20261110:end -->
<!-- main-catchup-7c64653d5:start -->
Updated to upstream `main` at `7c64653d5` and restacked all six branches. Part 1 is `cbf068d5f`; full integration is `206f71012`. The full integration tree exactly matches part 6.
The merge retains main's alpha-preserving Average behavior with bounded checked processing, and uses it consistently for XCF coverage conversion and native replay. Historical XCF normalization and import preparation now run through main's resumable Place flow and Open as Smart Object; regression tests cover source byte order and native Edit Contents. XCF report/filter labels also cover the seven languages main promoted to menu-complete status.
The current tree passed affected host all-target checks, core/IO, GPU, engine and frontend suites, strict all-target Clippy, formatting, layering, panel command dispatch, WASM and the web build, adversarial command tests, pinned IO corpora and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. The first two PR boundaries also passed independent all-target engine checks. Tests used CI-pinned craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, four Rayon workers, serial tests for RAM-heavy suites and opt-level=0 for engine/UI test glue; pixel and format crates kept repository settings. Quick performance mode uses smaller documents and does not enforce full-size budgets. Older measurements below remain evidence for their named earlier commits.
<!-- main-catchup-7c64653d5:end -->
<!-- percentile-owner-4502952267:start -->
Percentile owner-bounds follow-up at part 1 `93946db04` (full integration `f7264af14`): nonempty owner bounds now supply edge samples without a dense whole-owner admission check. The unchanged preflight still bounds clipped output, padded halo, workspace and CPU work; dense-image adapter limits remain in place. Two new regressions failed with `InvalidGeometry` before the fix and pass afterward, covering small edits on 81 MP and wider sparse owners, clamped-edge oracles, fractional selections, source preservation, clipped requests, invalid domains, oversized output, work limits and cancellation.
This follow-up passed 903 algorithm tests (887 unit + 16 integration; 27 existing ignored), all-target strict algorithm Clippy, formatting, layering and WASM (24 crates plus the HEIF configuration). Only sampling-bound admission changed; percentile processing and resource-preflight code are byte-for-byte unchanged. The broader qualification below remains tied to its explicitly named earlier commits; the full workspace suite was not rerun for this one-file follow-up.
<!-- percentile-owner-4502952267:end -->
<!-- native-foundations-validation-20261107:start -->
The production fixes at part 1 `c16e274b8` (full integration `6f8349cd5`) passed 7,245 affected algorithm/compositor/document/engine/native-format/IO tests across 46 binaries, with 65 existing ignored tests, plus doctests, affected all-target strict Clippy, layering, WASM, adversarial command tests, formatting and the pinned IO corpus (1,107 unit + 661 integration tests, 26 existing ignored). The final diagnostics regressions also passed independently on the foundation and full integration branches. The first PR passed an independent all-target engine check. Tests used four Rayon/test workers and the existing CI font pin; engine test glue used opt-level=0, and the foundation-only diagnostic probe also used opt-level=0 for its algorithm dependency. The full integration tree exactly matches the final sixth branch.
Paired 24 MP release probes used three timed repetitions per version after warm-ups, alternating order, matching inlining controls, opaque parameters and a current public-API control, with four Rayon workers. Timings are completed operations on this host.
| Probe | Before (ms) | After (ms) | Public API (ms) |
| --- | ---: | ---: | ---: |
| HDR toning | 830.3 | 834.4 | 791.2 |
| Rgb-Normal | 1070.5 | 1069.3 | 1079.7 |
| Cmyk-Normal | 683.0 | 669.7 | 691.5 |
| Rgb-Multiply | 1103.1 | 1303.3 | 1297.5 |
The extent-wide coverage prepass adds 200.2 ms (18.2%) in the alpha-preserving Multiply case. This is the measured cost of applying one consistent coverage rule; the Normal RGB/CMYK controls remain near baseline.
The uniform HDR probe's middle-gray output changed from 0.200004 to 0.180000 (target 0.18); the public control agrees. Mixer probes check native colors and alpha at sampled positions. The quick CPU application harness also completed; its saved cross-machine comparison was skipped, and quick mode does not apply full-size budgets. No budgets or baselines changed.
<!-- native-foundations-validation-20261107:end -->
Earlier validation of full integration `c003e3f50`, before these follow-up fixes, completed the upstream `main` catch-up at `c101cbfb7` on 2026-11-07. The cumulative series passed affected host all-target checks, foundation and IO suites, GPU, engine and frontend suites, strict Clippy, layering, WASM, adversarial command tests, formatting, pinned IO corpora and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. Local tests used CI-pinned craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, four Rayon workers and temporary opt-level=0 overrides for engine/UI test glue; pixel and format crates retained repository settings. The full UI library passed 5,330 tests, and the final dialog-dispatch cleanup passed 945 focused dialog tests.
The decoder and engine PR boundaries also passed independent all-target checks. The full `xcf-support-v2` integration tree matches the final sixth branch exactly. SVG stack regressions retain their 512 KiB caller, isolated complete native lifecycle and 100 retained group levels.
The matched performance figures below were measured before this main integration; the HDR recovery arithmetic and bounded tile implementation are preserved.
Forward filter-mask mixing retains its existing four-buffer allocation optimization and arithmetic. Its matched 24 MP RGBA32F probes measured opaque pixels at 392.410→182.842 ms, semitransparent pixels at 383.321→179.916 ms, and signed HDR pixels at 373.696→183.903 ms (five-run medians, 50–53% faster).
Inverse filter-mask recovery now processes at most eight native tiles in parallel, with four reusable scratch buffers per slot and ordered surface publication. Small inputs, one-worker operation and WebAssembly use the same serial tile helper. All F64 and integer pixel arithmetic is unchanged. Bitwise regressions compare full/partial/missing tiles, negative coordinates, differing defaults and hidden/zero-alpha outputs across 30 format combinations; an explicit one-worker/two-worker comparison checks both execution paths.
Matched 24 MP HDR inverse-recovery public-API probes measured 166.972→90.565 ms (opaque, 45.8% faster), and 433.325→130.707 ms (semitransparent, 69.8% faster). Five-run medians use four Rayon workers on this host; all runs assert recovered HDR samples at three positions. The existing F64 precision and HDR saturation bounds are preserved.
Mask recovery retains signed/HDR colors, extreme finite values, subnormals and exact full coverage. The PSD/PSB regression uses a real blur on spatially varying HDR pixels and partial masks; raw exported channels must match the unmasked filter result, and reimported Smart caches must match independently authored masked values.
The prior quick CPU application harness completed. Its saved cross-machine baseline comparison was skipped, so the paired public-API measurements above provide the direct before/after evidence. No performance budgets or baselines changed.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added image adjustments and filters for averaging, channel noise, convolution, percentile effects, alpha and coverage editing, black matte removal, HDR toning, and automatic tone, contrast, and color correction.
* Added Smart-filter blending controls for opacity and blend modes.
* Import-conversion information is preserved when saving and reopening documents.
* **Improvements**
* Improved handling of deeply nested SVGs and large patterns, with bounded pattern processing and warnings when pattern export is not possible.
* Improved stability when blending extreme HDR values and applying filters to HDR images.
* Improved transparency handling for channel-selective filters and added clearer feedback when image processing or export cannot be completed.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary
`photocraft-cli mcp --bridge` sent the control token in clear as its first frame, to whatever had accepted the connection: a `[::1]` listener reached through a `localhost` lookup, or any process holding `127.0.0.1:<port>` while the app was not listening. This PR fixes both cases:
- **Literal loopback only.** `BridgeClient` parses its address into a socket address and connects to it. Only `127.0.0.1:<port>` and `[::1]:<port>` are accepted. `localhost:<port>` means `127.0.0.1:<port>` (what the desktop app binds) and is never looked up.
- **Challenge authentication.** The bridge authenticates with `auth.challenge {clientNonce}` → `{serverNonce, serverProof}` → `auth {proof}`. Both proofs are HMAC-SHA256 keyed by the token over both nonces, each under its own label. The client checks the server's proof before it sends its own and never falls back to sending the token. The token never crosses the wire, so a listener that is not the app gets only a random nonce.
- **One shared server implementation.** `security::ServerHandshake` replaces `authentication_reply`, and both the desktop control server and `photocraft-cli serve` use it. The servers still accept the one-frame `auth {token}`, so existing scripts and older clients keep working. A repeat `auth.challenge` after authenticating gets "already authenticated", like a repeat `auth`.
- HMAC comes from RustCrypto's `hmac` 0.12 with `sha2` 0.10 (`sha2` was already in the lockfile). The proofs are compared without an early exit.
- `docs/control-protocol.md` documents the handshake, the exact HMAC message, and the bridge's address rules. The book's protocol summary is updated too.
Compatibility: a new bridge needs an app from the same release. Against an older app it fails with "refused challenge authentication … the control token was not sent". It does not downgrade.
Known limit: the channel is plain TCP with no TLS, so nothing binds the handshake to the connection. A party sitting between a bridge and a real app could relay the handshake without learning the token. On loopback that needs it to hold the port the bridge dials while the app listens on another, which the literal-address rule above narrows. Older clients that still send `auth {token}` keep their old exposure until they upgrade.
Closes#9777
## Tests
New in `crates/automation/tests/it/bridge_token.rs`:
- `localhost_reaches_the_ipv4_app_not_an_ipv6_listener`: a listener on `[::1]:P` gets no connection, and the app on `127.0.0.1:P` does.
- `a_listener_that_is_not_the_app_never_receives_the_token`: on both loopbacks, a listener that stays silent, refuses, or fakes the challenge receives only the challenge frame, never the token. The error says why.
- `the_bridge_authenticates_to_the_headless_server_by_challenge`: end to end against `rpc::serve_tcp`. A wrong token is refused before its proof is sent.
Unit tests: the handshake in both directions, and that wrong, missing or replayed proofs, the token after a challenge, a second challenge and malformed nonces are all refused (`security.rs`). `loopback_socket` address parsing (`bridge.rs`). The desktop server answering a challenge, then dispatching (`control_server.rs`). The existing bridge and MCP fakes now run the real `ServerHandshake`.
Run locally (Windows 11, targeted tests only):
- **Fail before.** I put upstream's `crates/automation/src/bridge.rs` (the old client) back and ran `cargo test -p photocraft-automation --test it bridge_token`: **3 failed**. The `[::1]` listener received `{"method":"auth","params":{"token":"<the token>"}}`, a `127.0.0.1` listener received the raw token, and the headless test got "authentication required" instead of the refusal. The original audit tests (`audit_nv6_bridge_sends_token_to_ipv6_impostor`, `audit_nv6_bridge_sends_token_to_any_ipv4_holder`) fail the same way on upstream/main.
- **Pass after.**
- `cargo test -p photocraft-automation --lib --test it -- bridge security tcp`: 23 + 21 passed. This covers the new tests, the existing bridge, MCP-bridge, security and serve TCP tests, and the legacy-token tests that still pass unchanged.
- `cargo test -p photocraft control_server`: 6 passed, including the new challenge test. The legacy-token tests still pass.
- `cargo clippy -p photocraft-automation --all-targets -- -D warnings`: clean.
- `cargo fmt`: clean.
- `Cargo.lock` adds only `hmac` 0.12.1, plus `subtle` under `digest` (already in the lock). Checked with `cargo metadata --locked`.
Not run here: the full gate (`cargo xtask ...`, the workspace-wide tests, wasm, clippy on the desktop app crate). That is left to CI.
API note: the workspace-internal `security::authentication_reply` is replaced by `ServerHandshake::reply`, which returns an `AuthStep`.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Security**
* Control connections support challenge-response authentication, verifying possession of the configured token without sending it. Token-in-frame authentication remains available for scripts.
* The MCP bridge accepts literal loopback addresses and maps `localhost` directly to IPv4 loopback. It rejects servers that refuse or cannot complete challenge authentication.
* **Bug Fixes**
* Rejected authentication exchanges close the connection; successful authentication allows requests to proceed.
* **Documentation**
* Control protocol and bridge authentication behavior are documented.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary
Closing a dirty document opens the unsaved-changes prompt. Save there writes the document back over its own file, just like File › Save, but when automation answered the prompt (a control request's `ui.dialog.confirm` on `discard`, or synthetic input) it was judged only for the command it held back (`file.close`, which the desktop policy allows). A client confined to its roots could therefore write an open document over its own file outside the write root, even though `file.save` is refused for it.
The prompt now checks the automation policy for `file.save` before saving, whenever a control client answers it (`ui.dialog.confirm`, with or without a session gate installed) or the input is synthetic, the same way `dialogs::confirm` judges file-writing handlers (ebdddbe1f). A refused Save returns an error naming `file.save` (or shows it in the status bar for synthetic input), writes nothing, and leaves the prompt and the document open. A user's Save is unchanged.
- `crates/ui-egui/src/dialogs/discard_ui.rs`: `apply` returns a `Result` and knows whether a control client gave the answer, and Save goes through the new `authorize_save` first. A control answer counts as automation even when the services carry only the `automation_command` callback, so `control::handle` installs no session gate. `authorize_save` judges `file.save` with the installed session gate (or the services' `automation_authorize`) and with the `automation_command` callback. With neither available it refuses the Save instead of running it unchecked. `answer_control` returns the refusal, and the drawn prompt reports it in the status bar (for synthetic input the `ui.key` reply stays `ok: true` like every synthetic input's; the refusal shows in `ui.inspect`'s `status`/`statusError` and the prompt stays listed).
- `crates/ui-egui/src/control/tests.rs`: regression tests `automation_saving_from_the_unsaved_changes_prompt_is_judged_as_file_save` (a control request and synthetic input are refused: nothing is written, and the prompt and document stay; a policy that allows `file.save` lets both write and close; a user's Save still writes and closes) and `automation_saving_from_the_unsaved_changes_prompt_needs_a_policy_to_judge_it` (gate only, command callback only, and no policy at all, each through a control request and synthetic input: refused naming `file.save`, nothing written, prompt and document kept).
Closes#9766
## Tests run locally
- `cargo test -p photocraft-ui-egui --lib -- automation_saving_from_the_unsaved_changes_prompt discard_ui:: automation_confirming_a_file_writing_dialog`: 60 passed, 0 failed (the new test plus the existing `discard_ui` tests and the disk-change prompt precedent).
- Without the `discard_ui.rs` change the new test fails: the control request's Save wrote the document's own file outside the root (`synthetic=false: nothing is written: [...\outside\x.psd]`).
- `cargo fmt -p photocraft-ui-egui`.
- The follow-up commits 1743a3240 (control answer judged without a session gate) and 20f08b919 (tests split, allowing-policy case) were not built locally; CI is their test.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Save requests from automation are checked for authorization before the document is written. If authorization is denied or unavailable, the document is not saved, and the unsaved-changes prompt remains open.
* Errors from rejected Save requests are displayed, including when requests come through a control interface or synthetic input.
* Synthetic Save input is refused when no authorization policy is available.
* Authorized, user-triggered saves continue to save the document and close the prompt.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
## Summary
`decode_deep` (deep OpenEXR, `deepscanline` / `deeptile`) admitted the data window at four bytes a pixel per channel, then built 24 bytes a pixel of bookkeeping that `max_alloc` never saw: a `u32` count per pixel, per-chunk `Vec<usize>` pixel indices and `Vec<u32>` prefix tables kept until the second pass, and the returned `u64` index. A 4096x4096 deep file of 65 to 300 KB held 384 MiB live under a 64 or 128 MiB budget and returned `Ok`.
This change:
- keeps one per-pixel structure, the cumulative `u64` index the result returns anyway (`DeepImage::counts`, 8 B/px plus one entry), allocated fallibly and **charged against `max_alloc` before anything else is allocated**;
- has each chunk record only its block bounds, parses the count tables straight into that index, and places each block row's samples as one contiguous range in the second pass (a block row is a run of consecutive raster pixels), so no per-chunk per-pixel vectors remain;
- admits the count tables (with their scratch copies) and the sample buffers against what the index leaves of the budget, so the live total stays within `max_alloc`;
- requires the offset table to list exactly one chunk per block (a duplicate or missing chunk was already malformed), so `seen` and the chunk list stay proportional to the offset table in the file rather than to the header's geometry;
- allocates the sample channels fallibly (`alloc_zeroed`) instead of with `vec!`.
Existing tests that pin exact budgets (`deep_tile_count_table_is_admitted_against_max_alloc`, `clipped_count_tables_include_scratch_in_the_budget`, `raw_count_tables_need_no_scratch_even_with_compression`) now add the index's size to their boundaries; their table-and-scratch semantics are unchanged.
Closes#9785
## Tests
- New `deep_exr::deep_bookkeeping_is_charged_against_max_alloc` (`crates/codecs/tests/it/deep_exr.rs`): a synthetic 256x256 one-channel deep image without samples, scan lines and one tile, NONE / RLE / ZIPS. Under a four-byte-a-pixel budget both `decode_deep_exr` and `decode_with` must return `LimitExceeded`; it decodes at exactly index + count table (+ scratch) and fails one byte below.
- Before the fix: **fails** (`tile None, compression 0: a four-byte-a-pixel budget gave Ok(65537)`).
- After the fix: passes.
- Allocation audit (counting global allocator; local only, not committed since it needs `unsafe`), 4096x4096, one float channel, ZIPS, zero counts:
| File | max_alloc | Before | After |
|---|---|---|---|
| deepscanline, 307,525 bytes | 64 MiB | `Ok`, peak 384 MiB (24.0 B/px), largest request 128 MiB | `LimitExceeded` (index needs 134,217,736 bytes), peak 0 MiB |
| deeptile, 65,597 bytes | 128 MiB | `Ok`, peak 384 MiB (24.0 B/px), largest request 128 MiB | `LimitExceeded` (index needs 134,217,736 bytes), peak 0 MiB |
- `cargo test -p photocraft-codecs --test it -- deep exr`: 81 passed.
- `cargo test -p photocraft-codecs --lib exr`: 3 passed.
- `cargo clippy -p photocraft-codecs --lib --tests -- -D warnings`: clean.
- `cargo fmt -p photocraft-codecs -- --check`: clean.
## Not covered
- The second pass still holds one chunk's decompressed sample data (and its byte-split scratch copy) next to the sample buffers; each is bounded by the samples already admitted, but the sum is not charged as one total.
- `flatten` (the flat `decode` path) admits its output and display-stage buffers one at a time while the deep image is still live.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* Improved handling of deep EXR images when memory limits are configured. Decoding now accounts for additional sample-count data when checking available memory, and rejects inputs whose required allocations exceed the limit.
* Improved validation of deep-image count tables, including tables associated with tiled images.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Fixes#9440Fixes#9787Fixes#9535
## Cause
Saving to a mapped SMB drive on Windows publishes the file, then `AtomicFs::sync_dir` fails with `ERROR_INVALID_FUNCTION` (os error 1): the share cannot flush a directory handle. Since #8034 (for #7858) every Windows flush failure fails the save, so the document stays dirty and the save looks failed even though the file is in place. Unix already treats "directory flush unsupported" as done (`dir_synced`, #5420); Windows had no equivalent.
## Fix
`dir_synced`/`dir_sync_unsupported` now exist on all platforms and, on Windows, count `ERROR_INVALID_FUNCTION` (1), `ERROR_NOT_SUPPORTED` (50) and `ErrorKind::Unsupported` as "cannot flush directories". `atomic_write` and the bundle store use it before `publication_error`. `ERROR_ACCESS_DENIED`, I/O errors and everything else still fail the save, so the #7858 protection stays for real failures.
## Tested locally
`cargo fmt --all`; `cargo clippy -p photocraft-format --lib --tests -- -D warnings`; `cargo test -p photocraft-format --lib atomic` (includes new `windows_unsupported_directory_flush_codes_are_classified`). Not replayed on a real SMB share. The full gate was left to CI.
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **Bug Fixes**
* On Windows, saves now succeed when directory flushing reports that the operation is unsupported, including during bundle publication and directory saves. This applies to unsupported-operation errors such as `ERROR_INVALID_FUNCTION` and `ERROR_NOT_SUPPORTED`. Other directory-flush errors, including access denied, continue to cause the save to fail and be reported.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Keep all 34 catalog deletions; sync crop options and fill rasterization text via craft-i18n 4a642c06dbcb8172f307f827c1167cd5dd8ac341. Adapt the fill prompt catalog test to embedded catalogs and preserve both parity-document updates.