Fails the build when .github/workflows/actions.lock stops matching the
workflows, or when a locked pin no longer verifies upstream, so a stale or
tampered lockfile cannot go unnoticed between dependency updates.
Mutable action tags are a supply-chain risk: a moved tag runs different code
without a diff. Every workflow action is now pinned through
.github/workflows/actions.lock, and CI verifies the lockfile so an out-of-sync
or tampered one fails instead of running.
* test(ai-native): read access lists in-process in the Windows tests
The owner-only tests read each file's access list back with PowerShell's
Get-Acl. That call failed for every test on the windows-latest CI runner
after #184 merged, while the library code itself was not involved. The
tests now read the owner and list with GetNamedSecurityInfoW, through a
test-only helper in the named unsafe module, and the owner parser no
longer assumes a group section.
* test(ai-native): accept the LA alias for the built-in Administrator
CI runners use the machine's built-in Administrator account (RID 500),
which SDDL writes as LA instead of its full SID. The owner-only tests
compared against the full SID and failed on windows-latest; the files
themselves were correct.
* fix: bound what a provider reply costs once parsed, not only its bytes
A byte cap did not bound memory: a reply of many tiny objects costs about a
hundred times its size as a serde_json Value. craft_ai_http::json::parse
builds the same Value but charges an estimate of each allocation against a
budget and refuses the reply once it runs out.
The OpenAI, Gemini, Vertex, declarative and ComfyUI readers now parse
through it. OpenAI also gets a byte cap per kind of reply (model list
8 MiB, chat 32 MiB, images 128 MiB), a budget per stream line, and the
structured-output re-read keeps the chat budget. Deliberate-bug cases are
in tools/mutation/mutation_reply_parse.py (group rp).
rustix 1.1.5 (through tempfile) has an unsound-code advisory in its xattr functions, which failed the cargo-deny advisories job on main and every open pull request. 1.1.6 fixes it. Nothing in this workspace calls those functions. Lockfile only.
The owner-only tests read access lists back with PowerShell's Get-Acl, which failed on the windows-latest runner after #184. They now read the owner and list in-process (GetNamedSecurityInfoW, test-only, in the named unsafe module), and accept the LA alias that SDDL uses for the built-in Administrator account the runner signs in as.
On Unix, craft-ai-native creates its private files with mode 0600. On Windows they took their folder's access list, which is not private in a folder that CRAFT_AI_DIR names outside %LOCALAPPDATA%.
- Private files and the folders this crate creates get an owner-only access list (the user's SID and SYSTEM) in the call that creates them, so no other account can open them in between.
- Creation does not follow a link planted at the name, and handles paths past 260 characters.
- A leftover temp file is removed and created again, never reused. This also fixes the Unix case.
- The Win32 calls live in crates/ai-native/src/owner_only/win_acl.rs, the workspace's one named unsafe exception. The workspace lint moves from forbid to deny, and tests/unsafe_exception.rs fails if unsafe is allowed anywhere else.
- Volumes without access lists (FAT, exFAT) still save, without one, as documented.
* fix(ai-comfy-env): never write a download through a link at the part-file name
The downloader opened its predictable `<name>.part` file with
`OpenOptions::create().append()/truncate()`, which follows an existing link.
Anything at the part name that is not a plain file with a single name is now
removed before use, and a resume must land on a handle with one name. Off Unix
the link count cannot be read, so a part from an earlier run is cleared and
downloaded afresh instead of being appended to.
* keep resuming a cut download off Unix: open links as themselves on Windows instead of never resuming
Each third-party action that StepSecurity publishes a secure drop-in
replacement for now uses that replacement, pinned to a commit with its
version as a comment. Versions follow what we used: the newest
StepSecurity release in the same major, or the closest major they
publish. dtolnay/rust-toolchain refs that named a toolchain (stable,
nightly, 1.76) become the replacement's `toolchain` input.
* docs: record architecture decisions, one file each
Add docs/adr/ with an index and 26 ADRs for decisions that already shape
the layer, backfilled from the docs and merged pull requests and numbered
by the date each was made. Each has its context, decision, consequences
and a link to the doc or PR that holds the detail.
Follows the docs/adr/NNNN-slug.md layout FilmCraft uses. LAYOUT.md points
to the folder.
* docs(adr): state the limits CodeRabbit found in eleven ADRs
Narrow each claim to what the code does: the TLS test checks one builder
call, consent is scoped by capability not tool, cancelling does not stop
a runner at once, Remove background needs the burn feature and a model
file, an existing agreement can skip re-approval, unknown fields in list
items need a unique identity, two zero token prices give a zero
estimate, the generated Burn module is exempt from Clippy, no shared
passphrase prompt exists yet, Last-Modified is used only with no ETag,
and a proxy resolves the destination on the proxied path.
Adds step-security/harden-runner (audit, pinned to v2.22.4 like
craft-common-actions) as the first step of each job that did not have it,
so every workflow in the org's public repos reports its egress to
StepSecurity. Audit, not block: block-mode allow lists come from each
job's observed traffic.
The Gemini eviction rule moved into registry.rs, and the ComfyUI plain-file
check moved into open_plain_file, so gi's gemini-unread-terminal-evicted and
p4's input-folder-read each matched nothing and checked nothing. Point them
at the current code. Every group now dry-runs with each case on exactly one
target. gi: 2 of 2 caught. input-folder-read stays the recorded Windows-only
equivalent.
Originals are opened without blocking and checked on the open handle, so a pipe or device at a model file's name is refused at once instead of stalling preparation while the model lock is held. A file that cannot be opened is reported as a file-access failure, kept apart from a mismatch in the originals.
Adds a built-in rten runner for image.matte: BEN2 finds the subject, and the small and base ViTMatte models matte its edge in tiles. The three published ONNX files are offered in Set up AI at pinned revisions with their sizes and hashes. The recipe sits after InSPyReNet, so the default Remove background offer does not change.
* fix(ai-media, ai-comfy-env): connect downloads only to addresses a link may reach
* fix(ai-media): give the resolver's test agent the shared settings and name the VPN ranges
The extra agent in the resolver tests skipped the shared TLS and proxy
settings, so the workspace rule that every agent takes them failed. A link that
reaches a shared VPN address (100.64.0.0/10, 198.18.0.0/15) now says which
setup it belongs to and what to turn off, instead of calling it private.
* address review: loopback answers only for loopback links
* address review: drop the nonexistent max_attempts config copy
Built on #170 (retries for provider API calls), which is now on `main`. The diff shows only this change.
## Problem
Hosted results come back as signed links that stop working after a while, and big files are sometimes cut part way.
- A media copy that was cut part way started again from the first byte on every try, so a large video on a poor connection could fail all its tries without ever finishing.
- Nothing knew when a link stops working. A link that had clearly expired was still fetched, tried again and reported as a vague host error, and a failed copy gave the app no way to know how long the kept link would last.
`docs/STATUS.md` listed "expiry tracking" and "resume" as not built.
## Change
- New field `PayloadHandle::expires_at: Option<u64>` (Unix seconds, UTC). This widens the shared contract: it is `#[serde(default, skip_serializing_if = "Option::is_none")]`, so stored and sent payloads without it read as before, and it is left out when unset. `Payload::handle` starts it as `None`.
- `ai-media/src/expiry.rs` reads a link's expiry from its signature, and only when that scheme's signature parameter is present:
- S3 version 4 (`X-Amz-Date` plus `X-Amz-Expires`, with `X-Amz-Signature`);
- Cloud Storage version 4 (`X-Goog-Date` plus `X-Goog-Expires`, with `X-Goog-Signature`);
- S3 and Cloud Storage version 2, and CloudFront (`Expires` as Unix seconds, with `Signature`);
- Azure shared access signatures (`se`, with `sig`).
An `expires` on an unsigned link is ignored. The earliest expiry wins. Anything that does not parse is ignored.
- A link clearly past its expiry (the handle's own `expires_at`, else the signed one) is refused before any request, with no retry, and the message says when it expired. "Clearly" means more than 5 minutes past (`CLOCK_GRACE_SECS`), so a computer whose clock runs a little fast still tries a live link.
- A failed copy keeps the original link, as before, now with `expires_at` set when it is known, and the notice says when the link stops working (unless it already has).
- Resume (`ai-media/src/partial.rs`): a cut download is kept between the tries of one copy only when the host named the file's version, a strong `ETag` or else `Last-Modified`. The next try sends `Range` from the copy's end and that version as `If-Range`, so a host whose file changed sends the whole new file instead. A weak `ETag` is never used. A `206` is taken only when its `Content-Range` starts exactly at the copy's end; anything else, or a `416`, throws the kept copy away and the next try starts over. A piece whose total is over the size limit is refused. The kept copy is the store's temporary file, so a copy that never finishes leaves nothing behind.
- Shortcut, stated in the module header: providers that state a link lifetime in their docs but sign nothing into the link are not covered. Their adapter can set `expires_at` itself when one needs it.
- Kept downloads live only for the tries of one `save` call. Nothing is resumed after the app closes.
## Verification
- New tests: `ai-media/tests/resume.rs` (8), `ai-media/tests/expiry.rs` (7), `ai-media/src/expiry_tests.rs` (10), `partial.rs` (4). Scripted localhost servers only.
- `cargo test -j 8 --no-fail-fast -p craft-ai-media -p craft-ai-core -p craft-ai-client`: 785 passed, 0 failed, across 96 test binaries.
- Deliberate-bug checks: a new `rx` group (14 cases: weak ETag, piece start, `If-Range`, resume without a version, piece limit, `416`, expired link fetched, handle expiry ignored, clock grace, unsigned `Expires`, earliest expiry, expiry attached, notice wording both ways) and `p10` (16 cases, `cut-transfer-not-retried` re-aimed at the new error line). All 30 caught, none survived.
- Every group dry-runs with one target per case except three that are not touched here: `gi` (`gemini-unread-terminal-evicted`) and `p4` (`input-folder-read`), already broken on `main`, and `ca` (`replaced-adapter-keeps-the-old-limits`), which #170's new `standard_senders` line split; it needs re-aiming in #170.
- Not run locally: Clippy, wasm, the full workspace and other systems. Those are left to CI.
- No live service or real download host was called.
## Review fixes (CodeRabbit round 1)
- A body that ends before the end its headers promised (the `Content-Range` end, `Content-Length` or the file's total) is a cut transfer, however cleanly the connection closed. It is kept when it has a version and the next try asks for the rest. A piece longer than its range is thrown away. Nothing is published until the copy is as long as the file.
- A kept copy records the address its bytes came from, after redirects. A `206` from any other address is not joined on, whatever its `ETag`, and the next try starts over.
- An `ETag` is used only when it is a quoted string with no quote inside. Anything else is no version, so a cut download starts over. (Round 2 tightened the date rule; see below.)
- The retry budget counts only the pauses between tries, as `MediaStoreConfig::retry_budget` already said. It used to count transfer time too, so a download cut after 30 seconds was never resumed. `save` now runs its own loop over `Backoff::next_wait`; `Backoff` itself is unchanged.
- The earlier of the handle's own deadline and the signed one is used, both before fetching and in the notice (`expiry::earliest`).
- Every redirect target's signed expiry is checked before it is asked for.
- A result past the per-poll copy limit stays a link, and now carries its known expiry.
- A date the calendar does not have (`se=2026-02-31`) gives no expiry.
- `store.rs` went over 500 lines, so its inline test moved to `store_tests.rs`.
- Tests: 6 more in `resume.rs`, 3 more in `expiry.rs`, 3 more in `expiry_tests.rs`, 2 more in `partial.rs`.
- Deliberate-bug group `rx` grew to 24 cases (malformed ETag, `Last-Modified` without a later `Date`, piece from another address, short body, long piece, piece that skips ahead, budget counting transfer time, handle deadline ignored, later deadline kept, redirect expiry unchecked, impossible date, skipped link losing its deadline). All 24 caught; `p10` 16 of 16. The first run found two survivors (`malformed-etag-used`, `piece-start-unchecked`); each got the missing test.
- `cargo test -j 8 --no-fail-fast -p craft-ai-media -p craft-ai-core -p craft-ai-client`: 799 passed, 0 failed, across 96 test binaries.
- Comments on #170's own files (`client_wait.rs`, `retry.rs`, the Gemini adapter) belong to #170 and are not changed here.
## Review fixes (CodeRabbit round 2)
- Dates go through `chrono`, as `CONTRIBUTING.md` requires. The hand-written calendar code from round 1 is gone; `ai-media` now takes the workspace `chrono` dependency (already used by `ai-core` and `ai-client`). An HTTP date's weekday must match its date.
- `If-Range` takes a date only when the answer has no `ETag` header at all, even one whose bytes are not plain text (RFC 9110, 13.1.5), and only when `Last-Modified` is at least 60 seconds before the response's `Date` (8.8.2.2).
- The whole file's length is kept with the copy once any answer has said it, so a later piece whose total is unsaid (`bytes 40-99/*`) cannot end the file early. A piece with a different total starts over.
- A piece that names another version (a different `ETag` or `Last-Modified`) is not joined on.
- A cut piece that had already sent more than its range is not kept.
- Not done: the suggestion to add a 1.1-second delay to the budget test. The deliberate-bug case `budget-counts-transfer` (1 ms charged) already fails that test, and the delay would slow every run.
- Tests: 4 more in `resume.rs`, 1 more in `partial.rs`; the weak-ETag and Last-Modified tests changed to the RFC rules.
- Deliberate-bug group `rx`: 30 cases, all caught (`opaque-etag-ignored`, `weekday-unchecked`, `other-version-joined`, `known-total-forgotten`, `total-mismatch-ignored`, `overlong-cut-kept`, `date-used-beside-an-etag` added; `impossible-date-read` dropped, since that check is now `chrono`'s). `p10` 16 of 16.
- `cargo test -p craft-ai-media`: 108 passed, 0 failed. Before the last RFC change, core, media and client together gave 804 passed, 0 failed; that change touched only `partial.rs` and one resume test.
## Review fixes (own review, round 3)
- Merged #170's latest (`9d82627`) with a normal merge. `MediaStoreConfig` now takes #170's single `retry: Backoff` field, and the tests use `cfg.retry.*`.
- `save` now runs `Backoff::run`, which counts only pauses since #170, in place of its own copy of that loop. It also gets `run`'s recheck after a pause.
- A kept copy belongs to the address without its query. A link that redirects to a freshly signed URL on every request (new `X-Amz-Date` or signature) now resumes. A piece from another host or path is still not joined on. A host that serves different files on one path by query still answers `If-Range` for the file asked for, so the version keeps them apart.
- When the host's answer does not continue the kept copy, the whole file is asked for at once in the same try, and no pause or try is used. This covers a 416, another version, a piece that does not fit, a changed total, and a piece longer than it said. It can happen at most once per try, because the copy is gone afterwards.
- One time limit covers the whole save: every try, redirect and pause. Each request gets only the time left, and no pause or try follows once the limit has passed. Before this, one `save` could hold `PersistingProvider::poll` for the number of tries times `transfer_timeout` (about 2.5 hours at 5 tries of 30 minutes). `transfer_timeout`'s docs now say this.
- `Partial::validator` is now `Option<String>`, not an empty string. Both places that keep a cut copy go through one check.
- `store.rs`'s error helpers moved to `store_errors.rs`, and the resume test helpers to `tests/resume_support/`, to keep the files under 500 lines.
- Tests: 3 new tests in `resume.rs`: a freshly signed redirect resumes; with two tries, a 416 after a real cut still ends in a saved file; the whole save has one time limit. The versionless test now also checks that nothing is kept between tries.
- Deliberate-bug group `rx`: 35 cases, all caught. New cases: `signed-query-compared`, `start-over-costs-a-try`, `per-try-time-not-shrunk`, `pause-after-the-deadline`, `late-error-not-named`. Re-aimed: `piece-from-another-address`, `if-range-not-sent`, `resumed-without-a-version`, `other-version-joined`, and `budget-counts-transfer` (now in `retry.rs`). `p10`: 16 of 16 caught (gate re-aimed, `cut-transfer-not-retried` now in `store_errors.rs`).
- Every mutation group dry-runs with one target per case except `gi` and `p4`, which were already broken on `main`. `ca` is fixed by #170.
- Doc bar: 318 of 318.
## Checklist
- [x] Tests written first; safety rules have a deliberate-bug check (`tools/mutation/`)
- [x] No secrets in code, tests or logs
- [x] Files stay under 500 lines (`store.rs` 444, `resume.rs` 429, all others under 300)
- [x] Widens the shared contract (`PayloadHandle::expires_at`) and says so above
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Interrupted media downloads can resume when the source confirms the file version; otherwise, the download restarts.
* Media links with recognizable expiry dates are checked before requests. Failed or deferred downloads retain their known expiry, which may appear in failure notices.
* Media downloads now share a time limit across retries and redirects.
* **Documentation**
* Updated hosted-media status information to describe download resumption and expiry handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
* test(ai-openai): bound and linearise the scripted server's header scan
* test(ai-openai): refuse a head whose delimiter arrives past the limit
The scan accepted a delimiter found in the read that crossed the size limit,
so an oversized head was still parsed and answered. Also stop asserting the
read timeout the scripted server's own close can invalidate on macOS.
* test(ai-openai): cover a head whose delimiter arrives past the size limit
Send a complete 70 KiB head in one write so the delimiter lands in the read
that crosses the 64 KiB limit. The scan must drop it there; without the
ordering check the head was parsed and answered.
* fix(ai-core): bound what a template's substitutions may add to a call
* fix(ai-core, ai-declarative): fill a queued call before making room
Filling now has a way to fail on an oversized prompt, and it ran after
`make_room` had already evicted a finished job, so a refused call cost someone a
stored result. Fill first, then make room, then send. A call that does not fit
is caller input, so it is reported as invalid rather than internal, and the
budget's actual rule is spelled out in the test.
* fix(ai-egui): export history without following an existing file at that name
* fix(ai-egui): replace the history export only once the new one is written
The demo removed the previous export before writing the new one, so a failed
write lost both. Write the export to a private temporary file in the same
folder, then rename it over the name: the rename never follows a planted link,
and a failure leaves the old export untouched.
* feat: retry provider API calls where it is safe
One retry rule, craft_ai_core::Backoff, now serves media copies, job
sending and polling, instead of a loop private to ai-media.
- AiClient::start tries a rate-limited send again. A dropped send or a
server error while sending is never repeated: the job may already be
running, and a second send could charge twice.
- Job::wait no longer ends on the first failed poll. A poll that fails
for a reason that can pass (dropped connection, rate limit) pauses and
tries again; five failures in a row, or a minute, ends the wait. A
success resets the run, and the overall timeout still wins.
- AiClient::with_retries sets both rules; Backoff::NEVER turns either off.
- Job::wait moves to client_wait.rs, so client.rs shrinks.
* fix: tighten poll retries and retry refused worker sends
Review fixes for the retry change.
- Job::wait counts the retry budget from the start of the first failed
poll, keeps the whole pause (interval included) inside it, and checks
the timeout after a pause, before another poll starts.
- Provider::submit now states the promise the client's send retry
relies on: RateLimited from submit means nothing was accepted.
- Gemini and OpenAI send from a worker after submit returns, so a 429
there failed the job. Each worker now retries its one refused send
(GeminiConfig/OpenAiConfig::send_retry, default Backoff::STANDARD),
stops once the job is cancelled, and never repeats any other failure.
* fix: a cancel during a retry pause stops the next send
Second round of review fixes.
- Backoff::run asks its retry test again after each pause, so a job
cancelled during the pause is not sent again (Gemini and OpenAI).
- Job::wait checks the timeout before every poll, the first included,
and a run of failed polls that ends past the timeout cancels the job
and records the give-up.
- Provider::submit's promise is worded to what adapters can keep: no
job was created, so nothing is billed for the work; files uploaded on
the way (ArtCraft's input pictures) may stay.
- AiClient::with_retries passes its send rule to the factory's own
Gemini and OpenAI builders (ProviderFactory::set_send_retry), so
Backoff::NEVER turns their worker retry off too. A builder an app
registered itself is left alone.
* test(mutation): re-aim replaced-adapter-keeps-the-old-limits
The factory's register now also clears the standard sender list between
the two lines this case matched, so it had no target.
* fix: refuse caller-cleared job limits as Quota, not RateLimited
The client now sends again after a rate limit from submit. Gemini's full
results registry and ComfyUI's eight-unfinished-jobs limit clear only when
the app polls or collects, so a pause on that same thread freed nothing:
start() stalled about three seconds, then failed with "(after 3 tries)".
Both now refuse as Quota, the provider contract says which kind a local
limit takes, and the history label for Quota reads "out of credit or over
a limit" so a full queue is not reported as no credit. Also moves
run_fill's doc comment back above run_fill.
* chore(mutation): drop the duplicate FACTORY path
* fix: retry budgets count pauses, and a failed wait cancels its job
Review fixes:
- Backoff's budget counts the pauses only. A slow call that fails (a timeout)
no longer uses it up, so the failure retries exist for can be retried.
- Job::wait: the poll interval is the floor of a retry pause but does not
count against the budget, so a long interval still retries a dropped poll.
A wait that gives up because polls kept failing now cancels the job and
records the give-up, as the timeout already did.
- with_factory applies a send rule chosen with with_retries, so the order of
the two calls no longer matters.
- start and start_test say they can block during a rate-limit pause.
- MediaStoreConfig holds one `retry: Backoff` in place of three fields.
- The standard sender list is built in place, not as a const array.
* feat(ai-native): encrypted-file fallback in the standard secret chain
A machine with no OS keychain could not save a key through the standard
setup: AiClient::standard and ConnectionManager::standard layered only the
environment and the keychain, so every save failed with "no secret store".
standard_store(passphrase) now builds environment, keychain, then the
encrypted file at the default location. Without a passphrase the file
layer is a locked stand-in: no file reads as "no key", an existing file
is reported as locked rather than empty, and a save asks for a
passphrase. passphrase_need() tells a host when to ask (create or
unlock). Both standard constructors gain standard_with_passphrase.
Deliberate-bug group kf (7 cases, all caught). The real keychain round
trip passed by hand on Windows; Linux and macOS keychains, a bare Linux
session and a host prompting for the passphrase are not run.
* fix(ai-native): a failed file check counts as a locked file, not a missing one
Path::exists returns false when the check itself fails, such as an
ancestor folder that denies access. The locked stand-in then read a key as
absent, and both it and EncryptedFileStore::delete reported a delete as
done while the key could still be in the file.
Use try_exists. In the locked stand-in and passphrase_need, a failed
check counts as present, so it is reported as locked. In
EncryptedFileStore::delete, it is a storage error. Two new deliberate-bug
cases in kf, both caught (9 of 9).
* docs(ai-native): document the encrypted file store's set
* docs(ai-native): document the encrypted file store's name and get
* docs(ai-native): document the encrypted file store's error mapping and Debug
* fix(ai-client): show why a key save was refused when it needs a passphrase
ConnectionManager replaced every refused key save with the general
"keychain failed, set an environment variable" advice. On a machine with
no keychain, the person never saw that the secret file needs a
passphrase. A credentials refusal (Auth) from the store is now shown as
given; store errors never carry a secret. Other refusals keep the general
advice. New deliberate-bug case in kf, caught (10 of 10).
`AiClient::plan` now works out a `CostEstimate` from the saved model's
`pricing` and the request, so an app can show the price beside the
disclosure before the person agrees. It reads no key and contacts
nothing. `Plan::estimate()` returns it.
The rule lives in `craft_ai_core::cost::estimate`: the per-image price
times the results asked for. A token price above zero gives `None`,
because the reply's token count is unknown before sending. Two stated
zero token prices give zero. A missing price or an overflow gives
`None`, never a guess.
History still records an estimate: the adapter's own figure where it
gives one, otherwise the plan's, including on a refusal before the
adapter is built.
`cost_text` keeps part-cent digits, so 0.039 USD no longer reads 0.03.
FLUX.1 Fill [pro] carries $0.05 per image, from BFL's price page
(cited in the code). Gemini, FLUX 3 and Seedance stay unpriced: their
publishers price by resolution tier or by token.
A Generative fill can now carry optional reference pictures where the
service takes them, reusing InputRole::Reference.
- Gemini and ArtCraft Omni send them after the source and mask, in
request order. FLUX.1 Fill takes none and refuses before consent.
- craft_ai_media::mask::references checks each one before anything is
sent: inline data, 10 MB, format from the bytes, pixel bounds and a
full decode. Omni takes PNG only.
- No reference count of ours; each service enforces its model's limit.
- Gemini holds the whole request body to 20,000,000 bytes, refused from
the input sizes before any picture is decoded, and takes its in-flight
place before building the body.
- A saved Omni connection gains the optional input when the store is
read; the refresh never adds a required input or changes a count.
Closes#125.
Omni generative fill, plus the points left open from #120:
- Gemini job registry: uncollected results forgotten after 1 h; new fills refused while 512 MB of results are held.
- mask::binary reads the mask one row at a time.
- Gemini declares its route support (fill only, one source and mask, at most one prompt, one output).
- Every fill result (BFL, Omni, Gemini) is decoded in full by craft_ai_media::decoded_result: size checked before decoding, JPEG markers walked to the end marker, JPEG and WebP decodes share a 512 MiB budget.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(ai-bfl): FLUX.1 Fill [pro] for image.inpaint (Generative fill)
Adds the flux-pro-1.0-fill model to craft-ai-bfl for image.inpaint with
source, mask and prompt, and lists BFL as a hosted route for the
generative-fill tool.
- Mask: white (or, for a mask with transparency, transparent) marks the
area to fill; BFL is always sent a binary 8-bit grayscale PNG, white =
fill, as its API documents. An empty mask, a non-PNG mask or a mask that
differs in size from a PNG source is refused before sending. Our own
bound: 8,192 px a side, 32 MP (BFL documents none).
- Options: steps (15-50), guidance (1.5-100), seed, safety_tolerance
(0-6), prompt_upsampling, output_format (png/jpeg/webp; png default),
range-checked; anything else is Unsupported.
- Result: downloaded as soon as the task is Ready (BFL links last ten
minutes), only from https *.bfl.ai, without the key, no redirects,
bounded to 32 MiB, type taken from the bytes, returned inline. A dropped
download is a Network error the next poll retries; an expired link, a
non-BFL host or a non-image fails the job.
- Errors: 429 now carries Retry-After; 402 is Quota ("out of credits");
401/403 Auth; moderation statuses fail the job with "content moderated";
"No Card Generated" is a failure instead of an unknown status.
- Regional addresses api.eu.bfl.ai and api.us.bfl.ai are accepted.
FLUX.1 Expand is not mapped: it takes per-side pixel counts that
image.outpaint does not carry.
Tested against scripted servers only (conformance lifecycle, cancel,
unknown job and reject checks included); no real BFL call was made.
* fix(ai-bfl): poll BFL's polling_url and stop waiting on a lost task
BFL's docs say a task submitted to the global api.bfl.ai must be read at
the polling_url from the submit reply, because the global address routes
to several clusters. Reading {base}/get_result instead could answer
"Task not found" forever, which was treated as pending.
- Every BFL job (FLUX 3 and FLUX.1 Fill) is polled at polling_url when it
is https on bfl.ai or a subdomain, default port, no user-info; the key
goes nowhere else and redirects are still not followed. Otherwise the
configured {base}/get_result?id= is used. A loopback API (tests) only
accepts its own origin.
- "Task not found" (status, or a 404 from get_result) fails the job with a
Provider error once it has lasted 10 polls in a row and 60 seconds
(BflConfig::not_found_grace). Any other answer resets the count.
Scripted-server tests cover the polling_url being used, foreign and plain
http polling URLs ignored without the key reaching them, and the
not-found timeout and reset.
* feat(ai-gemini): Gemini API image models for image.inpaint (Generative fill)
Adds craft-ai-gemini: Google's Gemini API (generativelanguage.googleapis.com,
an AI Studio key; not Vertex) through the Interactions endpoint, serving
image.inpaint with source, mask and prompt. Registered in the factory as
"gemini", with a "Google Gemini" preset and a hosted route for the
generative-fill tool.
- Models: Nano Banana 2.1 (gemini-nano-banana-2.1, default), Pro, 2 and 2
Lite; any well-formed gemini-*image* id is also accepted at submit.
- Mask: Gemini takes none. The craft mask (white, or transparent when it
has transparency, = fill) is sent as a second picture, an opaque binary
grayscale PNG, white = fill, with an instruction explaining it and saying
the area may already be blurred out as a placeholder. Prompt-guided
editing: the model may change pixels outside the mask, so the caller
keeps only the masked part. An empty prompt asks for a removal fill.
- Output: JPEG (the only format the endpoint returns), nearest supported
aspect ratio, 1K/2K/4K from the picture's size or the image_size option;
Lite stays at 1K. Anything else in params is Unsupported.
- Errors: 401/403 and a 400 about the API key are Auth, 402 Quota, 429
RateLimited with Retry-After, Google's message kept (key scrubbed, cut to
300 chars). A text-only answer fails the job with the model's words.
- Key in x-goog-api-key only, official address or loopback only, no
redirects, replies bounded to 48 MiB. Testing a connection lists models
(free). Each job runs on its own thread so it can be polled and
cancelled; a cancelled request may still be billed.
Tested against scripted servers only (conformance lifecycle, cancel,
unknown job and reject checks included); no real Gemini call was made.
* feat(ai-client): Plan::provider, for adapter-specific params
* refactor(ai-media): one mask reader for the inpainting adapters
FLUX Fill and Gemini fill each carried the same craft-mask reader, size
check and grayscale PNG writer (SonarCloud: 9.1% duplication on new
code). They now share craft_ai_media::mask (Bounds, inline, png_size,
binary, encode_gray); each adapter keeps only its own limits and error
wording. Behaviour is unchanged and the existing mask tests pass as they
were.
* refactor(ai-media): Bounds names its service and checks sizes
The size check, its error and the input lookup were still the same few
lines in FLUX Fill and Gemini fill. Bounds now carries the service name
and a check() with the error a person reads, and mask::inline takes the
Bounds, so each adapter keeps only its limits.
* fix(ai-gemini): retain terminal jobs until their state is delivered
* fix(ai-features): fill notes say what was run live; Gemini's warning in its preset
The OpenAI and FLUX.1 Fill options said "Built and tested offline only",
but both have been used live from PhotoCraft. Gemini's warning that it
may change the picture outside the selection lived only in the cloud
option's note, which setup and the picker don't show; its preset note
now says it too.
* fix(ai-gemini): hold a permit for the life of each worker thread
MAX_RUNNING counted jobs that were not terminal, but cancel makes a job terminal while its request keeps running. Repeating submit and cancel could put more than 32 requests in flight, for up to the request timeout each.
submit now takes a permit before it accepts a job, and the worker thread holds it until it exits. A worker that never starts gives it back too. No live call was made: the regression test runs against a local listener.
---------
Co-authored-by: scratch <s@s>
A custom connection's test lists no models, so the panel confirmed the
address without calling set_models. The draft still recorded its models
as belonging to the old address, and the save stored none.
ConnectionDraft::confirm_models_for records the tested address without
replacing the models, and refuses an address no longer in the form. The
panel uses it for a custom answer. Two set_models mutation cases are
anchored to that function, since the new method shares its check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A connection form keeps the model list from when it opened. Saving it after
a withdrawal put the withdrawn declared model, ability or input back. The
save now drops every declaration the saved connection no longer has, and
uses the saved spec where the provider now reports it.
Also from review on #157:
- withdrawing only declared inputs is blocked only by a choice whose tool
takes one of them, not by every choice with the same capability
- the refusal names the scope that blocks it
- set_enabled and delete on an unknown id, and clear_binding with nothing
to clear, write nothing
- the module invariants say why an app choice is not checked against the
launcher's own adapters
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- mutation_contract.py names the assignments, refresh and manage paths once
(ASSIGN, REFRESH, MANAGE) instead of repeating the literals.
- panel/probe_tests.rs imports each name from the parent explicitly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A folder stands where the store writes its temporary file, so the write
fails with an I/O error after the change was made in memory. Replaces the
size-limit test, which returned before atomic_write. Mutation case
store-writes-in-place proves the test guards the atomic write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- ModelInfo.tags and STORE-SCHEMA.md name the declared-model, declared: and
declared-input: markers hosts must not show as labels.
- Saved and TestReport describe unavailable choices as gone or no longer able
to do the tool's job.
- refreshed_models says why a model assign_model added survives a save.
- PLATFORM-CONTRACT.md names assign_model, withdraw_model and
model_choice_state as the host path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A declared input whose ability a refresh drops keeps its tag, and comes
back when a later refresh reports the ability again. Withdrawing finds a
declared input by its tag alone.
- ConnectionDraft records the models the saved connection listed when the
form opened it (opened_with). Saving keeps a stored model the form never
saw, with its declarations; a model the form removed is still removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pads the store so the assignment's rewrite goes over the size limit after
the change was made in memory, and checks the file's exact bytes stay.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Move refreshed_models, carry_declared, UnavailableChoice and
unavailable_choices into assignments/refresh.rs (re-exported unchanged),
keeping assignments.rs under 500 lines; one known_tool lookup is shared.
- unavailable_choices also reports a choice whose model stays listed but lost
the capability or an input its tool needs; the choice is kept.
- Split the refresh tests into tests/model_refresh.rs over a shared
tests/support/assignment_world.rs fixture; retarget mutation cases.
- Document every touched function.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-ups on #157:
- assign_model and model_choice_state refuse a route the adapter declares
unsupported, as choose does; an adapterless provider is still allowed.
- withdraw_model checks the tool definition under the lock, so a replaced
custom tool cannot take back the new one's choice.
- An input a person adds to a reported ability is tagged, put back on refresh,
and withdrawn on its own.
- save merges a stale or tested form's model list with the person's
declarations while the provider and address are unchanged.
- The panel keeps a custom connection's declared models when its test answers
with a probe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
write_choice now ends with Ok(()) and maps errors through Stop::Refused,
so v1 choose-writes-nothing and v3 choose-skips-the-check had no target.
Both match once again and both are caught.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A host wrote a model's ability and the tool's binding as separate steps, so
withdrawing an ability could leave a selected tool with no eligible model.
ToolDesk now assigns and withdraws both under one store lock. A declared
ability carries a tag, so a provider's own ability is never removed, and a
refresh keeps what a person declared. Withdrawing refuses while another
binding needs the ability. A refresh or save reports a choice whose model
has gone and keeps it; another model is never chosen as a repair.
Store changes that can be refused now use try_update, so a refusal leaves
the file's exact bytes rather than rewriting them.
Fixes#124
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The core and Rust blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. The repository notes below them are unchanged. The house-rules workflow checks the copy.
Review follow-up on #158, as Jeremy decided.
- `RouteQuery` carries outputs, streaming and whether the request has
options. Plan and start fill them from the request; status and the picker
ask about one output, no streaming and no options. The list check refuses
options (none of those adapters maps them yet) and checks outputs and
streaming against the listed model; Vertex takes one output, no streaming
and no options.
- This app's own paths (choices, picks, bind) leave out or refuse a provider
this build has no adapter for. `choose`, the suite default the launcher
sets, stays open, because the launcher may set up a model that only some
apps can run.
- local_routes: the LightCraft override is bound by a client that has a
Candle adapter, as a real LightCraft build does.
- Mutation cases for each new guard; `inputs-not-checked` re-aimed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up on #158.
- The list check counts each input role against the listed model's limit,
as `submit` does, so two prompts for a one-prompt model are refused at plan.
- BFL, Seedance, ArtCraft Omni and Vertex each expose `address_allowed`, which
their constructors use; the support check applies it, so a saved address
the adapter would refuse is reported before consent.
- `start` runs the route check again before the key is read, because a plan
can come from another client of the same app.
- The last success must be at the connection's current address
(`Disclosure::destination_for`, shared with consent and history).
- A refused `choose` uses `try_update`, so the store is not rewritten. #157
makes the same change.
- Tests: a real `last_success_ms` value, a panicking builder for the status
check, a catalogue-recommended refused model in `picks`, and a plan-level
Mask request. Shared fixtures moved to tests/support/route_fixture.rs.
- Mutation cases for each guard; `v1`, `v3` and `sd` cases re-aimed at the
current code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A saved model could read as Ready while its adapter refused it before
sending anything, so a person agreed to send data for a job that could
never start.
An adapter can now state its own limits to the factory, with no key read,
no provider built and nothing contacted. Omni, BFL, Seedance and Vertex
state theirs; any other adapter stays Untested, never Supported. Status and
plan refuse a known refused pairing before consent, the picker stops
offering it, and the chosen model is left as it is. route_facts keeps saved,
executable and last real success as separate facts.
The check lives in the client, so the core Provider contract does not widen.
Fixes#123
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The three tests added for the review moved into shared_nested_fields.rs so
they reuse its store fixture and helpers instead of copying them; SonarCloud
counted the copy as duplicated new code. The mutation cases point at the
moved tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up on #156.
- A file item that a newer build gave an `id` (a binding known here only by
`role`) is now indexed under every identity field it holds, and each written
item is looked up by its own identity, so its unknown fields survive.
- A written identity that appears twice is left as written, like a duplicate
in the file, instead of both items copying one old item's fields.
- STORE-SCHEMA.md: a new list field needs no identity; identity matters only
for fields added to items of an existing list.
- Docs on the touched functions and tests; three mutation cases point at the
new tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>