mirror of
https://github.com/storytold/craft-ai-integrations.git
synced 2026-11-23 21:00:43 +01:00
fc0399bc9a87bf6f4cfbe63e8f6d4a6735f5c294
66
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
db30646d9d |
fix(ai-client): ask before running a ComfyUI workflow with add-on steps not known to stay local (#191)
* 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(ai-client): ask before running a ComfyUI workflow with add-on steps not known to stay local A connection to ComfyUI on this computer is local, but an imported workflow can pass the picture and prompt to an add-on step that sends them to another host. Such workflows ran with no consent prompt. ai-comfyui now keeps a short list of ComfyUI's own steps that keep data on this computer (local_steps.rs). When the chosen library workflow uses any other step, the plan marks the job as possibly leaving the computer and names those steps in the new Disclosure::unknown_steps, so the existing consent path asks. An agreement records the steps it named and covers only those, so a workflow that adds a step asks again. start re-reads the workflow and refuses if its steps changed since the plan. Nothing is refused outright: a workflow with add-on steps still runs once the person agrees. The shared disclosure_lines adds a plain line naming the steps, and the adopting guide says what apps show. * fix(ai-comfyui): agree to a workflow's exact step names, shorten only the label Step names were cleaned and cut to 80 characters before consent and the changed-workflow check compared them, so two steps sharing their first 80 characters looked like one. unknown_steps now returns the exact names; the consent line in ai-egui cleans and shortens them for display only. * fix(ai-client): check workflow consent for every provider spelling * fix: freeze approved workflows and scope consent grants --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a717de4a88 |
fix(ai-media, ai-engine-candle): cap Extended XMP fragments before every JPEG decode (#187)
* 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(ai-media, ai-engine-candle): cap Extended XMP fragments before every JPEG decode The JPEG decoder re-scans every Extended XMP fragment collected so far after each header segment, so a file made of thousands of tiny fragments costs it quadratic time. rten already refused more than 1,024 fragments; the returned- picture check in ai-media and the candle engine did not. The fragment counter moves from rten into craft-ai-core (`jpeg` module), the one crate all three decoders already depend on. rten, candle and `decoded_result` (which also checks Gemini reference pictures) now refuse an over-cap file before the decoder or the shared decode budget is reached. Tests build a file one fragment over the cap for each decoder, and the new `jx` mutation group drops each caller's check and breaks the counter. * fix(ai-core): count every Extended XMP namespace, not only those a header walk reaches The decoder runs in a lenient mode that skips stray bytes between header segments and keeps parsing Extended XMP fragments. The header walk stopped at the first stray byte, so a file with one stray byte before an over-cap fragment chain passed the guard and still reached the quadratic work in the rten and candle engines. The count is now every occurrence of the Extended XMP namespace anywhere in the file. The decoder only keeps a fragment whose APP1 body starts with that namespace, so the count can never be lower than what it collects. Each decoder test now also puts a stray byte before the fragments. rten and candle check that the at-cap file with the stray byte still decodes (so the decoder does skip it) and that the over-cap one is refused. ai-media already refused the stray byte in its end-marker walk, before the decoder. |
||
|
|
f7229caf41 |
fix(ai-core): ask before sending a key over plain http to a server on this computer (#192)
* 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(ai-core): ask before sending a key over plain http to a server on this computer A connection to a server on this computer is local, so it needed no consent. But over plain http the key, prompt and pictures go to whichever program holds that port first, and on a computer shared by several accounts that can be another person's program. Checking who owns the listening socket needs platform calls this library cannot make without unsafe code. Disclosure::for_request now marks a request remote when its connection has a key and a plain-http address, so the existing consent path asks once for that app, address and capability before the key is read or anything is sent. Over https, or with no key, a server on this computer still needs no consent. Data-described services with a local base and a key are covered the same way. * fix(ai-core): say on the consent screen that the saved key goes too, and why Raising the locality made the prompt appear but it listed only the request's data. Disclosure gains key_in_clear (never the key), and disclosure_lines adds a plain line saying the saved key is sent unencrypted to whichever program uses that address, which on a shared computer may be someone else's. |
||
|
|
fdf02b3b47 |
feat(ai-engine, ai-client): show, unload and limit models kept in memory (#179)
* feat(ai-engine): show, unload and limit models kept in memory The built-in engine kept every model it loaded until the app closed, with no way to see or free that memory. `EngineProvider` now: - lists loaded models with roughly what each holds (`loaded_models`); a runner reports its own figure through `LoadedModel::memory_bytes`, else the weights file size stands in, marked as an estimate, and the figure is read again after each run; - unloads one model or all (`unload`); a model in use finishes its job and is let go of as it leaves the slot, so nothing is interrupted and no request is lost; - unloads models idle for a given time (`unload_idle`), a call the app makes, with no timer; - with `with_free_memory`, refuses in plain words a load that will not fit, before anything loads (`ModelRunner::memory_needed`, default the file size). Deliberate-bug group `mm`: 13 cases, all caught. Part of #178. Reading free memory per platform and the AiClient wiring follow separately. * fix(ai-engine): close the unload hand-off window and guard the free-memory reader - A job now lets go of the model's slot while it still holds the residency lock, so an unload can no longer see a job that has left but still holds the slot and defer the unload to the next job. - A free-memory reader that panics fails that job with an internal error instead of unwinding through the worker, which left the job unfinished. - The fake runner can be held inside its run, so tests that look at a running job no longer depend on timing. Deliberate-bug group `mm`: 14 of 14 caught. * feat(ai-client): list and free models the built-in engines keep in memory Apps reach the built-in engines through AiClient, which had no way to see or free the models they keep loaded. The factory now keeps each engine's provider cache by engine name, and the client offers: - `loaded_models()`: each loaded model with its engine, connection and rough size; - `unload_model(connection, model)`, `unload_all_models()` and `unload_idle_models(time)`; - `with_free_memory(read)`, which reaches every engine provider at load time, including providers built before the reader was set, and survives `with_factory` in either order. Registering or unregistering an engine name drops its cache, so a replaced engine's models are no longer listed. Deliberate-bug group `cm`: 6 of 6 caught. Part of #178. Builds on #179. * fix(ai-client): keep a replaced engine provider listed and freeable When a connection changed while a job still held its old provider, the cache replaced it and the old model dropped out of `loaded_models()` and could not be freed. A replaced provider is now asked to unload at once (its running job finishes first) and stays listed until its models are gone. The cache stays shared by clones of one factory, so clients built from it share one loaded copy instead of loading the weights twice. The doc comment on `loaded_models` now says so, and a test pins it. Deliberate-bug group `cm`: 8 of 8 caught. * fix(ai-engine, ai-client): a replaced provider keeps nothing its queued jobs load A job queued on a provider before its connection changed could load the model after the client replaced that provider, leaving a model nobody could list or free. `EngineProvider::retire` now makes every job let go of its model as it finishes, and the client keeps a retired provider listed while it is busy or still holds a model. The mid-job test now uses different file sizes for the old and new model, so it tells them apart. Deliberate-bug groups: `mm` 15 of 15, `cm` 8 of 8. * fix(ai-client): keep a replaced provider listed throughout the swap The replaced provider now moves to the retiring list before the cache lock is released, so a listing taken during the swap never misses it. A new test changes the connection while the old job is still loading and a second job waits behind it: both old jobs finish and let go of what they loaded, and only the new model is left to free. The fake runner can now pause a load. Deliberate-bug group `cm`: 9 of 9 caught. * fix(ai-client): keep a retired provider listed while anything still holds it A caller that got a provider just before its connection changed could submit through it after a listing had already dropped the retired provider, so the model that job loaded was out of sight while it ran. A retired provider is now kept while any other reference to it exists, as well as while it is busy or holds a model. A test holds the old provider across the swap, lists, then submits through it and checks the model is listed and freeable. Deliberate-bug group `cm`: 10 of 10 caught. * test(ai-client): drop an unused import from the loaded-models tests * fix(ai-engine, ai-client): set memory aside for loads under way Two loads judged at once both counted the same free memory. Each admitted load now sets its need aside until its load ends, and every built-in engine of a client shares one count. A replaced provider is retired after the cache lock is released, and a provider replaced during a listing is listed once. |
||
|
|
be236d570b |
feat(ai-client): keep a run record as evidence of a real run (#177)
* feat(ai-client): keep a run record as evidence of a real run AI-17, first slice. `RunRecord` turns a finished job and its plan into one JSON line: app, tool, capability, provider, connection, model, destination, the kinds and sizes sent (as the consent screen shows them), parameter names, start time and duration, outcome, error kind and wording, notices, usage, and each result's type, size and SHA-256. It keeps no prompt, no result bytes and no link, since a hosted link can carry a signed token. `to_json_line` refuses a line that contains any secret it is given, so a key that slipped into an error message never reaches the file. The `live_openai` example takes `--record <file>` and appends the line for its run. No live run was made: tests use a scripted localhost server and the mock provider. Deliberate-bug group `rr` (10 cases) catches all 10. * docs(ai-client): say a timed-out wait leaves no run record Job::wait returns an error on a timeout, so RunOutcome::Unfinished only comes from a Finished the caller built from a job that had not ended. Reword the variant's doc and the test that covers it. * fix(ai-client): clean run-record messages and catch escaped keys Error and notice text is cleaned when the record is built: the secrets given to RunRecord::new, the request's own text inputs and any word that looks like an address are replaced. The record never holds a key, so serialising it by any route is safe. to_json_line also refuses a line holding a secret in its JSON-escaped form, so a key with a quote or a backslash cannot slip past the check. * fix(ai-client): remove a key inside the request text with the whole text scrub replaced secrets before it looked for the request text, so a key inside the prompt broke the prompt's match and left the words around it in the record. Secrets and request texts are now all found in the original message and overlapping matches are removed together. The module doc no longer claims that serialising a record by any route is safe: only its messages are cleaned, so records are written with to_json_line. * fix(ai-client): remove overlapping repeats of the request text match_indices skips overlapping occurrences of the same text, so request text such as "private private" inside "private private private" left part of itself behind. Every occurrence is now found, overlapping ones included, and the spans merge as before. * fix(ai-client): leak-check the run record and saved image in live_openai The final leak check only read folders, so the --record file and the image written by 'image <out.png>' were never read back. It now reads single files as well as folders, and both are added to the list. * fix(ai-client): clean parameter text and escaped forms from run records Error and notice text is now also cleaned of the request's text parameter values, nested ones included, and of every key and text in its JSON-escaped form. live_openai refuses a record path that is also the image output, and its leak check fails when a written file cannot be read instead of reporting clean. Group rr gains four cases; 24 of 24 caught. * fix(ai-client): find links in the original text of a run-record message Links were removed after keys and request text, so request text inside a link split the address and kept the rest of it, signed token included. Link spans are now found in the original text and merged with the others; a merged stretch is named key, then link, then request text. Also collapses the nested if Clippy flagged in live_openai. Group rr: 24 of 24 caught. * docs(ai-client): keep two recorded live runs as evidence live_openai gains an omni mode (one nano_banana image from a fixed prompt through the saved ArtCraft Omni connection) and --connection to pick one saved connection by id. Omni has no free key test, so its saved model list is used as it stands. docs/evidence/live-runs.jsonl keeps two records from 11/11/2026: an OpenAI text run refused with 429 (no API credit) and an Omni image run that succeeded with one image/png link. STATUS.md says what each shows and what it does not. * fix(ai-client): clean returned text and escaped links from run records Error and notice text is now also cleaned of what the run returned (each text result and the whole streamed text), read as [result text removed], and of links written with JSON-escaped slashes. The live_openai docs no longer promise a hash for a returned link. Group rr: 27 of 27 caught. * fix(ai-client): protect the shared store from live example outputs * fix(ai-client): keep record lines whole and resolve parent folders in live_openai A record appended to a file that ends without a newline now gets one first, so two records never share a line; append_line moves to its own module with tests. The output preflight compares names with each parent folder resolved, so a linked folder or '..' cannot hide that the record and the image are one file. * fix(ai-client): keep only the adapter's own words of a run record's messages Two ways a record could still hold what the person sent or received: adapters cut long upstream messages at 300 or 360 characters, so a prompt echoed back arrived cut part-way and never matched whole; and a failed Gemini image run put the model's own text reply in its error, which was never an output and so never removed. Error and notice text now keeps only the adapter's lead. What follows the first ": " is where adapters quote the service or model, so it becomes "[detail removed]", and an error records its length and hash. Before the cut, any stretch of 16 or more characters taken from a request or returned text is removed too. The record version goes to 2, since `message` changed meaning and `detail` is new. The example's record file is now written with one write per line, so two runs appending at once cannot split a record. * fix(ai-client): recheck image aliases after recording runs * test(ai-client): keep the locked-output check true on every Windows machine Whether a file held with no sharing still has a readable identity differs between Windows installs: it does on some, and the CI runners refuse it. The test asserted one outcome, so it passed locally and failed in CI. It now checks the invariant that holds either way: an unreadable identity is refused up front, a readable one fails at the write, and the locked file and the shared store are never changed. --------- Co-authored-by: FredApps <FredApps@users.noreply.github.com> |
||
|
|
98d7664a04 |
feat(ai-client): AppTools lists and runs a tool, so no app writes its own job loop (#180)
* feat(ai-client): AppTools lets any app list every tool and its status in one call Reads the shared store under the app's own id. Read only: no key read, nothing sent or written. A tool with no choice is Unavailable with a reason; an unknown id is Unavailable, never another model. * fix(ai-client): AppTools lists custom tools and states honestly what a status check reads A tool someone declares in the shared store was invisible to report(), status() and role(), so the foundation could not show a tool people build themselves. They are now listed after the catalogue's. role() returns an owned Role because a custom tool is read from the store on each call. The invariant said no key is read. status() asks the key store whether a key is saved for a keyed connection, which can reach the system keychain. The doc comment and the adopting guide now say so, and advise calling report() when a menu opens, not every frame. * style(ai-client): rustfmt app_tools * feat(ai-client): AppTools plans and runs a tool, so no app writes its own job loop request(tool), plan(tool, request) and run(&plan, &ledger) cover the plan, start, wait and collect steps, with canceller() reaching the running job from any thread. Consent stays the app's own step between plan and run. Every app runs a chosen model the same way; only what it does with the outputs differs. Tested with a stand-in engine: plan then run for two app ids, a request carries the tool's capability, an unchosen or unknown tool is a sentence, and cancel reaches a hanging job and is harmless with nothing running. * fix(ai-client): one cancel reaches every waiting job; a job past its wait is cancelled; run_for Review of the run API found three gaps. Two runs at once on one AppTools made the first to finish hide the second from cancel; jobs are now tracked by number and one cancel reaches all of them. A job still running when the wait timed out was left running; it is now cancelled. Three minutes is too short for video, so run_for takes the app's own limit. Struct and module docs now say AppTools also plans and runs. * docs(ai-client): document the app_tools test stand-in * test(ai-client): deliberate-bug group 'at' for AppTools; drop a redundant cancel Eleven cases, all caught. The first run found a test gap (repeated cancels hid that one cancel reached only the first of two jobs), fixed by cancelling once. It also showed that the cancel added to run_for after a timeout was redundant: Job::wait already cancels when its limit passes. The earlier commit message claiming a job was left running at timeout was wrong; the redundant line is removed and a comment says where the cancel happens. New tests: a finished job removes only itself, and a failed model is an error with its own message. * fix(ai-client): AppTools reports a job that will not stop, keeps text replies - A cancel or a wait that ends without the job ending asks the job to stop. When the service refuses, the sentence says it may still be running; Canceller::cancel now returns that sentence instead of nothing. A poll that cannot pass also asks the job to stop, which Job::wait did not. - A streamed text reply is returned as one text output, not dropped. - An online job is looked at once a second; a local one still every 15 ms. - An unreadable shared store shows its own reason, not "not part of the suite". - Canceller::waiting says how many jobs are waiting; tests use it instead of sleeps. - The wait-limit test fails in seconds when the limit is ignored, so its mutation no longer relies on the runner's timeout. Six new deliberate-bug cases in group `at`. * fix(ai-client): a cancel no longer reads a finished job's result away; a zero wait starts nothing - Canceller::cancel reports a refused cancel as it is and no longer reads the job, since that read could take the result from the run still waiting for it. - run_for refuses a limit of zero before starting a job nobody could watch or stop. - Docs: status checks that a key is saved (the keychain may prompt); AppTools is the standard way to run a tool, role() and client() the lower-level path. - Two new deliberate-bug cases in group `at` (19 in all). * docs(ai-client): status checks that a key is saved; only start uses it * docs(ai-client): start reads the key to use for the job * fix(ai-client): a wait with no limit runs the job instead of panicking after it started `Job::wait` added the timeout to `Instant::now()`, which panics for `Duration::MAX`, the usual "no limit". `run_for` had already started the (possibly paid) job, so it was left running unwatched and stayed in the list a Stop reaches. The deadline is now added with `checked_add`, a longer wait is capped at ten years, and the job leaves the running list through a drop guard so an unwinding wait cannot leave it behind. |
||
|
|
0d76ea02a0 |
feat(ai-mcp, ai-agents): one MCP gateway to every Craft app, and the agents switch in one crate (#197)
Adds craft-ai-mcp as an MCP gateway to the Craft apps' own MCP servers, and craft-ai-agents, which reads and writes the launcher's app list (apps.json) and answers whether agents may use an app. - The gateway starts each listed app as <app>-cli mcp, lists, searches, describes and calls its tools, and asks the launcher's switch before and after every call. Turning agents off stops the app servers it started. - A long call holds only its own app; listing, searching and describing never wait for it. - A list that is missing, broken or of another version counts as agents turned off. Started from #154. Part of #195. |
||
|
|
6edeedce6f |
docs: record architecture decisions, one file each (#182)
* 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. |
||
|
|
6507c6f42c |
feat(ai-engine-rten): BEN2 + ViTMatte for Remove background (#167)
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. |
||
|
|
74ae1745e1 |
feat(ai-media): resume cut downloads and track link expiry
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 --> |
||
|
|
32c6553c31 |
feat: retry provider API calls where it is safe (#170)
* 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. |
||
|
|
803473e7a0 |
feat(ai-native): encrypted-file fallback in the standard secret chain (#175)
* 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). |
||
|
|
2988987c1a |
feat: show a cost estimate on the plan, before consent (#168)
`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. |
||
|
|
29297b2fbe |
feat: reference pictures through the Generative fill routes (#165)
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. |
||
|
|
3ba1ddb764 |
fix(ai-artcraft): support Omni generative fill (#122)
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> |
||
|
|
323b2a3d9f |
Generative fill: FLUX.1 Fill and Gemini for image.inpaint (#120)
* 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>
|
||
|
|
7f3108d0be |
docs: reserved model tags, unavailable choices and the assignment host path
- 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> |
||
|
|
ca2a43fd30 |
fix(ai-native): match list items on the identity this build writes
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> |
||
|
|
439c4e789b |
fix(ai-native): keep newer fields at every depth of the shared store
Each app pins its own revision and they all share one file. A write kept unknown top-level fields but dropped nested ones, so an older app could silently remove what a newer app or the launcher saved, including a built-in model's local_file. SharedStore now compares the file on disk with what this build gets by parsing and serialising it, and carries over anything it has no type for. List items match by identity, so reordering is safe and a removed item takes its unknown fields with it. docs/STORE-SCHEMA.md says when a change needs a SCHEMA_VERSION bump. Fixes #155 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
baed1adcff |
feat(ai-comfyui): map a start image for video.generate workflows (#102)
* feat(ai-comfyui): map a start image for video.generate workflows Wan 2.2 TI2V and I2V graphs load their first frame through LoadImage. A video.generate workflow mapped only its prompt, so every job reused the image name saved in the graph (#48). - Workflow::import_video_from_image (workflow/video.rs): one LoadImage source binding, checked like a selection source: the image field of a LoadImage, not the prompt field, feeding the output. - Workflow::info: Source accepted and required once bound. Without the binding a video.generate workflow stays prompt-only. render_with_source accepts video.generate. - ComfyProvider::submit: the start image goes through read_role (declared type against the bytes, upload limit, local regular files only), /upload/image, render_with_source, then /prompt. The image.inpaint path without the mask. - WorkflowSpec::to_workflow: a stored video.generate file may declare a source; a mask is refused. - p4: start-image-sent-unchecked, the start image read straight from the request and uploaded. Tests, tests/video_start_image.rs, scripted servers: - the_start_image_is_uploaded_before_the_graph_is_queued: inline PNG and a local JPEG file; one upload before /prompt, the returned name in the LoadImage field. - a_video_workflow_with_a_start_image_refuses_a_request_without_one: Source required in models(); no request reaches ComfyUI. - a_start_image_that_is_not_the_image_it_claims_is_never_uploaded: the inpaint byte cases plus a file over the limit; no upload, no /prompt, no file content in the error. Catches the p4 case. - a_stored_video_workflow_keeps_its_start_image: library save and load. - a_start_image_binding_must_be_a_connected_image_loader: mask, text field, unconnected loader. - a_video_workflow_without_the_binding_stays_prompt_only: no upload, saved name kept, Source refused. Red on main: the four tests that need the binding fail at import; the two guards pass. On the branch, each part undone alone fails its test: the provider branch (upload test), Source required (refusal test), the stored spec (library test). p4 start-image-sent-unchecked is caught. * refactor(ai-comfyui): share source mappings and media test helpers * docs(status): note that ComfyUI inputs accept local file handles * test(ai-comfyui): reject a start-image binding to a missing node --------- Co-authored-by: scratch <s@s> Co-authored-by: Jeremy <jeremy8776@gmail.com> |
||
|
|
074871deae |
fix(ai-client): show a local file's measured size in the consent prompt (#121)
* fix(ai-client): show a local file's measured size in the consent prompt A `file:` handle carries the size the app claims, and the disclosure repeated it, so an understated or missing size reached the prompt as if it were known. `plan` now looks at the file: a regular file on this machine shows its length on disk, and one that cannot be looked at shows no size. Other handles and inline data are unchanged. * fix(ai-client): discard claimed sizes for malformed file handles * fix(ai-client): show no size for any handle address that does not parse The fallback guessed the scheme of an unparsable address by splitting on the first colon, which misses spellings the URL parser accepts (padding, tabs or newlines inside the scheme in a deserialized request). The uploaders read handles with the same parser, so an address it rejects can never be read and its claimed size is never checked. Drop the guess and show no size whenever parsing fails; parsed file addresses are measured and other schemes keep their size, as before. The size test fixture now builds its store from JSON and gains a test that a replanned file shows its current size. * chore(mutation): name the ai-client paths the contract cases repeat --------- Co-authored-by: scratch <s@s> Co-authored-by: Jeremy <jeremy8776@gmail.com> |
||
|
|
14a7fb8696 | fix(ai-client): bind sample approval to reviewed disclosure (#117) | ||
|
|
e8f320321a |
feat(ai-engine-burn): InSPyReNet for Remove background, built in only (#112)
* feat(ai-engine-burn): InSPyReNet for image.matte (Remove background) A second model on the Burn engine: `inspyrenet` answers `image.matte` from the picture alone, a grayscale PNG at the picture's size (white is the subject, soft along hair and fur). `remove-background` has had no local model; this is one. - Network: InSPyReNet with the Swin-B backbone, written by hand in Burn after the MIT reference code. Module names follow the PyTorch keys, so the published .safetensors loads by name through Burn's PyTorch adapter. A load that leaves a weight unset, fails one, or finds a foreign tensor is refused in plain words. - Any picture size: full resolution up to 1280 px on the long side; above that a reflect-padded square reduced with antialiased Lanczos-3, the matte enlarged back and refined at full resolution with a colour guided filter on the tiles near the edge (the Gyre approach), then a 0.2 fringe shrink. - Weights: 1038lab/inspyrenet inspyrenet.safetensors at a pinned revision, checked tensor for tensor against the author's ckpt_base.pth. Checked on one Windows machine (release): every stage against transparent-background's PyTorch code (worst relative difference 3.2e-5 on the processor, 2.4e-4 on the card, no pixel changing side); the shared conformance suite; on a real PNG the mask is byte-identical to the same port in PhotoCraft. Four new deliberate-bug cases in `be`, all caught. Not done: a catalogue recipe (a recipe names a ComfyUI workflow today), clean timings, macOS and Linux runs, a run through an app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(ai-features): a recipe that is built in only, InSPyReNet for Remove background `LocalRecipe::comfyui` (default true) marks a recipe ComfyUI runs. With false it is only its built-in routes: never a ComfyUI setup option, plan, install offer or connection, and engine advice does not list ComfyUI for a tool without a ComfyUI recipe. `Feature::comfyui_recipes()` gives those recipes; `engine_recipe`, `plan_native`, `setup_offer_native` and `enable_native` are unchanged. `remove-background` gets one such recipe: InSPyReNet on Burn, the pinned `inspyrenet.safetensors` (1038lab/inspyrenet @ 0f594663, 367,120,444 bytes) in the folder `inspyrenet`, so Set up AI offers one checked download and no ComfyUI. Tests: the catalogue, setup options, plans and offers (`ai-features/tests/built_in_only.rs`), registration and advice (`ai-client/tests/built_in_only.rs`), and through `AiClient` on Burn (`ai-client/tests/burn_matte.rs`, the real run ignored). Mutation group `bo`: 8 of 8 caught. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tools): retarget two `lc` mutation cases at the ComfyUI recipe lookups `unrunnable-recipe-accepted` and `second-recipe-takes-plain-id` searched for the `feature.locals` lookups in `ai-client/src/local.rs`, which now go through `Feature::comfyui_recipes()`. Same mutations, new targets; group `lc`: 21 caught, one known equivalent. Every case in `GROUPS` again has exactly one target (640 checked). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(ai-engine-burn): InSPyReNet runner checks around a stand-in, readout without panic CI has no graphics card, only a software renderer (lavapipe, WARP), and the engine takes it. There the tiny network was too slow for the conformance suite's poll limit, and on lavapipe the readout failed. Unoptimised, Burn's processor backend takes minutes for the same network. - The loaded model runs the pipeline around a `Predict`: the network, or in tests a stand-in, as the SAM 2.1 tests here use a fake backend. The conformance suite and the mask test use the stand-in (debug: the crate's unit tests in about 18 s). - The tiny network still runs through load and run on the processor in an ignored release test (about 4 s). The runner's device choice is a field, so tests can name the processor. - The prediction is read with `try_into_data`, so a device that fails while running is an error, not a guarded panic. - docs/BURN-ENGINE.md: the test split and that a software renderer counts as a card. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(ai-engine-burn): InSPyReNet moves to the processor when the card fails A card can answer the engine's probe and still fail on the network: on CI a software renderer (lavapipe) failed while reading the answer back. The first failure on a card that is not a cancel now builds the network again on the processor from the same file, runs that picture again there with a notice, and stays on the processor (`inspyrenet/fallback.rs`). A network loaded on the processor in the first place has nothing to move to. Tests with stand-ins: a working card is kept; a failing one moves once and stays; a cancel is not a failure; a rebuild that fails is the answer. Mutation group `be`: three new cases, all seven InSPyReNet cases caught. A real photo on the card still runs on the card. docs/BURN-ENGINE.md: the move, and the client run's picture is 2848 x 4272, not 3101 x 1613. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(ai-engine-burn): the move to the processor stays only after a rebuild that worked The rebuild is tried once. If it fails, its error is the answer and later pictures go to the card again, as `a_rebuild_that_fails_is_the_answer` already pins. The module docs and docs/BURN-ENGINE.md said the model stays on the processor without that condition. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(ai-engine-burn): retry a failed InSPyReNet load on the card on the processor The move to the processor covered failures while predicting, not a load on the card that fails. `load_or_processor` now retries such a load on the processor, unless the file itself is not the checkpoint (`Unsupported`), which is refused at once rather than read a second time. A network loaded on the processor in the first place is loaded once. Tests: a card that loads keeps the network; one that fails loads on the processor; a bad file is not read twice; on the processor there is one load. Mutation group `be`: two new cases, all nine InSPyReNet cases caught; every case in the checker has one target (645). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style(ai-engine-burn): method references in the guided filter, one name for the fallback path Three SonarCloud findings on #112: two closures in `guided.rs` become method references, and the mutation cases name `inspyrenet/fallback.rs` once. No change in behaviour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: imperator <imperator.maximus@gmail.com> |
||
|
|
bcec558fb6 |
fix(ai-engine-burn): run the processor fallback on every core with SIMD (#113)
The crate turns off Burn's default features, which also dropped `rayon` and `simd`: burn-ndarray was built with `std` only, so the processor fallback ran on one core with scalar maths. Turning both on gives burn-ndarray `multi-threads` and `simd`. Measured on the InSPyReNet network (640 x 333 picture, processor, i5-12600KF, release): 22.8 s -> 6.2 s, masks identical to one pixel by one level. SAM 2.1's processor timing was not re-measured; the doc says so. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
60b84aed84 | fix(ai-client): keep linked model folders out of downloads (#109) | ||
|
|
6f7078666a | test(ai-engine): cover queued cancellation and clarify widget qualification (#106) | ||
|
|
0e55340771 |
Migrate shared AI widgets to egui 0.37 (#105)
* refactor(ai-egui): migrate shared widgets to egui 0.37 * egui037: qualify shared AI widgets and downstream dependency pins * docs(ai-egui): record the committed migration qualification * fix(ci): provide Vulkan snapshots and allow pinned fork sources * test: make cancellation-before-load coverage deterministic |
||
|
|
e2c23c1c2b | path for developer AI suggestions- #103 | ||
|
|
7be5af833f |
feat(client): status, picker, route notes and engine advice agree with what the default route can do (#94) (#100)
* feat(client): one start button for setting up a built-in model, with no tick box unless a licence needs one (#94) Part of #94, slice 1 of 3. The shared pieces for a one-click setup existed but nothing joined them. - NativeRoute/NativeSetupPlan::needs_agreement: the licence tick shows, and a download waits for it, only when a file's licence needs agreement. SAM 2.1 needs none. - SetupSession::start/next_task/blocker: one button that checks complete files on disk or downloads, and says why it does nothing (SetupBlock). - FolderDesk::ensure_default(_at): takes the suggested folder only when none is chosen. The widget offers it (UseSuggestedFolder) instead of dead-ending at "Choose a model folder". - ToolDesk::adopt(&CheckedNative): only checked files, binds only if no choice exists, and returns the choice it kept. - Docs: the flow in use-in-your-app, LAYOUT lists the Burn crates, STATUS row. - Mutation group fr (6 cases, 6 caught); two older cases re-aimed at the changed code. Checked: fmt, strict clippy and tests for craft-ai-features, -client, -egui and -comfy-env (473 passed, 2 ignored), wasm check for craft-ai-features, every mutation group --dry clean, group fr run for real, documentation 14/14. Scripted tests only: no real download, no model run through it, no app has mounted it, no macOS or Linux run. * feat(client): try a built-in selection model with a click, and fail a selection that chose nothing (#94) Part of #94, slice 2 of 3 (stacked on slice 1). The launcher's try-it sample for Select subject sent only a description. The default built-in route (SAM 2.1 on rten) refuses descriptions and selects by clicking, so the sample failed on the default route. - sample_request_for(feature, built_in): for image.segment with a built-in route, one click on the middle of the test disc and no description. Everything else is the plain sample. - ToolDesk::start_sample: picks the sample from the tool's current choice (a built-in engine the tool's recipe lists gets the click; ComfyUI and hosted routes keep the description). - ToolDesk::finish: a selection that ran but reports matched: false is a failed test. - Docs: step 5 of the set-up flow, STATUS row. - Mutation group fr gains 2 cases (8 in all, 8 caught). Checked: fmt, strict clippy and tests for craft-ai-features, -client, -egui and -comfy-env (478 passed, 2 ignored), wasm check for craft-ai-features, group fr run for real, documentation 34/34. Scripted tests and a fake provider only: no real model, no app, no macOS or Linux run. * feat(client): status, picker, route notes and engine advice agree with what the default route can do (#94) Part of #94, slice 3 of 3 (stacked on slices 1 and 2). - AiClient::status: a built-in model whose weights file has gone is not Ready. - The picker lists such a model once, as one to set up again, not also as a ready one. - NativeRoute::note: the setup option, the picker row and its description say the built-in SAM 2.1 route selects by clicking on the picture, instead of offering a prompt it refuses. - NativeRoute::fast_on_processor (rten, one Windows machine, about 35 ms a click, not a benchmark): engine advice gives it Pace::Processor, not "slow", and ranks it level with a card engine, so the recipe's first engine is the suggestion with or without a graphics card. - Mutation group fr gains 6 cases (14 in all, 14 caught); the Burn route case is re-aimed. Checked: fmt, strict clippy and tests for craft-ai-features, -client, -egui and -comfy-env (483 passed, 2 ignored), wasm check for craft-ai-features, every mutation group --dry clean, group fr run for real. Documentation 66/67; the one flagged is an untouched neighbour of a doc line. Scripted tests only: no real download, no model run through it, no app, no macOS or Linux run. * fix(client): one real start button, a failed check falls through to download, folder order (#98 review) Fixes the CodeRabbit findings on #98 that held up. - The setup widget showed "Check existing files" and "Download model files" side by side when complete files were on disk, so a person could start a download instead of the check. It now draws one start button from SetupSession::next_task and blocker, and its click calls SetupSession::start. The licence tick shows only when the next task is a download. - After a failed check, start kept choosing the check again, so files that did not match were a dead end. The session now remembers the folder that failed and downloads next; a different folder, or a different target, is checked again. - FolderDesk::ensure_default needed the computer's suggested folder even when the person had already chosen one. It now looks at chosen folders first. - The adopting guide told a host to call ensure_default before drawing the first screen, which makes the folder before the person accepts it. It now says to call it only on their yes. Checked: fmt; strict clippy; client tests and egui tests pass except the existing panel::a_dead_server_is_reported flake, which passed 3 of 3 alone; docs bar 38/38; mutation group fr 11/11 caught. Group nw had a case aimed at the old two-button code; it is re-aimed and caught. * fix(client): the sample copies only the small result outputs, not whole pictures (#99 review) finish cloned every output to read the selection result, copying large inline pictures and videos. It now copies only inline JSON, the form of a selection result. Behaviour is unchanged, so no test can see the copy; the existing sample tests still pass. Checked: fmt, strict clippy, client tests (309 passed), docs bar 64/64, mutation group fr 13/13. * fix(client,engine-candle,features): a selection sample needs its result, Candle sends it, small card pace (#100 review) Fixes the CodeRabbit findings on #100. - A segmentation sample passed when the route returned a mask and no Found result. The contract gives every route both, so the sample now fails with "did not say whether it selected anything". Other tools are unchanged. - Candle SAM 3 returned only a mask, which would now fail that test. It sends the Found result too (matched with its score, or nothing found when the model gave no prediction). - A processor-quick engine whose matching card is too small was called slow. It is now judged by the processor, as the card is not needed. - The adopting guide said every built-in selection model rejects words. It now says the sample uses a click, which every built-in route reads, and names the new rule. Docs bar: undocumented neighbours of the changed hunks are documented, the chain walked up to the first documented function (tests/engine.rs helpers and tests, three Candle runner methods). Checked: fmt; strict clippy (features, client, engine-candle); tests (features, client, candle lib: 440 passed); wasm check of craft-ai-features; docs bar 124/124; mutation group fr 22/22 caught, with three new cases. Not run: the live Candle test (needs the SAM 3 weights), so Candle sending Found is covered by a unit test of the result, not by a real run. * fix(client): only the connection this suite saves gets the click sample (#99 review) start_sample treated any connection whose provider is a built-in engine's name as built in. A custom connection that reuses the name `rten` may serve a model that needs a description, and the click-only request is refused by the planner before it is sent. The click sample now needs the engine's own saved connection id as well. Others keep the description sample. Checked: fmt, strict clippy, client tests (310 passed), docs bar 65/65, mutation group fr 14/14 caught (one new case; 'sample-ignores-the-route' re-aimed at the changed line). * fix(egui): show suggested folder before creating it The suggestion action creates the folder. Display its actual path first, and hide the action if no suggestion can be made. Keep the native path helper available in the egui library, not only its tests. Checked: fmt, strict clippy, 492 focused tests, wasm, 24/24 first-run mutations, docs 134/134. * fix(egui): keep the folder suggestion idle-only and test no suggestion The suggestion now waits for an active check to finish. Tests guard systems without a suggested path and exercise a busy session with discovered read-only files. Checked: 493 affected tests, fmt, strict clippy, wasm, 25/25 first-run mutations, docs 135/135. * fix(client): recover from bad files in a new approved folder A failed check now blocks reuse of the rejected directory and the previously shown destination. The person chooses a fresh folder, and the worker creates its model directory only if absent. The old files remain untouched, even if the newly approved directory appears before the worker begins. Scripted transfer and retry regressions: 388 affected tests, fmt, strict clippy, wasm, 15/15 first-run mutations, docs 49/49. Four unrelated native-feature mutations survive on upstream main too. * fix(client): explain why a fresh model folder could not be made Preserve the atomic create and distinguish an occupied destination, a missing approved parent and permission denial. Red regressions cover missing and occupied paths, and a mutation checks the message. Checked: 390 affected tests, fmt, strict clippy, wasm, 16/16 first-run mutations, docs 66/66. * fix(client): try another model under the built-in connection with words The sample picked a click whenever the connection was the one this suite saves for the engine, without checking the model. Connection management can put another model under that id, one that wants a description, and the click sample then failed for the wrong reason. Match the model the engine's recipe names as well. --------- Co-authored-by: scratch <s@s> |
||
|
|
fe5748da8d |
docs(adopting): guides for using, declaring and serving AI tools (#93)
* docs(adopting): guides for using, declaring and serving AI tools, with every code block run as a test * docs(adopting): address review: keyed register example, cancel that may be unsupported, indented fences, guide tests in the README * docs(adopting): cancel may be unsupported in the provider table and app guide; a job may end straight from Queued --------- Co-authored-by: scratch <s@s> |
||
|
|
1a02afd6be |
feat(client): offer SAM 2.1 on Burn as an optional engine after rten (#91)
* refactor(engine-rten): let another engine reuse the SAM 2.1 request handling Loaded, Backend, Prediction, read_prompt, prompt_points and best_proposal become public. Visibility only: the click and box mapping, the picture kept between requests, the empty-mask answer and the size checks then live in one place for every SAM 2.1 engine. * feat(engine-burn): crate shell and the script that generates the SAM 2.1 architecture tools/burn/generate_sam21.py checks the two published ONNX files against the pinned size and SHA-256, runs the pinned burn-onnx 0.22.0 (an example of craft-ai-burn-setup), applies the five asserted fixes, drops the generated loaders that panic on a bad file, splits by submodule so every file is under 700 lines, formats and writes. --check proves the tree is what the script produces. REVISION must equal the saved-weights cache revision. Cargo.lock additions are Burn with wgpu and ndarray (generated). * feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer Brings in craft-ai-burn-setup (feature `conversion`): checks the two published ONNX files by size and SHA-256, converts them to Burn weights with the pinned burn-onnx 0.22.0, and keeps one checked, locked, shared copy. Nothing is hosted or downloaded. Mutation group bp (10 cases). Cargo.lock additions are the optional burn-onnx tree (generated). * feat(engine-burn): GENERATED SAM 2.1 tiny architecture (30 files) Output of tools/burn/generate_sam21.py, revision sam21-tiny-burn-0.22.1-onnx-0.22.0-v1, from the published encoder.onnx and decoder.onnx with burn-onnx 0.22.0 and its five asserted fixes. Do not review line by line; rerun the script with --check instead. Longest file 699 lines. Marked linguist-generated. * feat(engine-burn): SAM 2.1 runner for image.segment on Burn Sam21Runner (engine burn, model sam21) over the generated architecture. The request handling, picture kept between requests, empty-mask answer and click/box mapping are the shared Loaded from craft-ai-engine-rten, so only the model run lives here. Weights load through BurnpackStore and come back as errors; every call into the generated code is guarded against panics. Graphics card when one answers, else the processor. An .onnx file is answered with 'prepare it first', not a guess. 16 unit tests on a fake backend: click and box mapping, empty mask, short mask, a failing model, shared conformance run with Cancel, damaged and truncated files. * test(engine-burn): live comparison with rten, and the shared revision check The ignored live test runs the real SAM 2.1 files through rten (published ONNX) and Burn (weights prepared on this computer) on the astronaut sample: one click and a box, best-mask IoU, timings, and a truncated prepared file refused. The revision test fails when the generator, the compiled architecture and the saved-weights cache key disagree. * test+docs(engine-burn): mutation group be, weight-loading tests and the Burn engine guide Group be: 15 cases, one target each, all caught (saved-weights marker, load completeness, panic guard, answer length, best proposal, file names, declared card makers, the revision shared by script, architecture and cache key, the catalogue route and the .bpk binding rule). fully_applied is split out so the load checks can be tested without the store's own refusals. Group nf's onnx case follows the rewritten extension check. docs/BURN-ENGINE.md: how to regenerate, the five fixes, the revision bump rule, limits. * feat(engine-burn): CRAFT_AI_BURN_DEVICE=cpu forces the processor, and the processor path is measured * feat(engine-burn): prepare the saved copy when loading from the downloaded ONNX files The host step: given the downloaded encoder.onnx with decoder.onnx beside it, the runner calls craft-ai-burn-setup (exact source bytes checked, reused when already saved) and loads from the burn-prepared folder beside the model folder. Behind the default 'prepare' feature; mutation group be gains two cases (17/17); docs say what is measured. * feat(client): optional burn feature and a catalogue route for SAM 2.1 on Burn craft-ai-client gains the cargo feature burn (ProviderFactory::standard() then knows the engine). SAM 2.1's recipe lists a burn NativeRoute after rten, with the same two published ONNX files (one download for both, nothing converted is hosted). rten stays first and the default. The binding accepts the prepared .bpk file. Engines now list rten, burn, candle; the tests that assumed the Burn slot had no files, or that no built-in engine exists whatever cargo features are on, say what they mean. burn_engine.rs runs two apps through the client with the real prepared files (ignored). * fix(burn-setup): sweep the scratch folders a killed run left, and keep craft-ai-features a dev dependency CodeRabbit on #89: tempdir_in(cache) folders hold the two source copies (about 130 MB) and were removed only by Drop, so a killed app leaked them for good. They now carry the cache key and a role in their names, and after the key's lock is taken the same key's leftovers are removed (other keys' folders, the lock file and links are left alone). Red first: leftovers_of_a_killed_run_are_swept_for_this_key_only. Mutation cases burn-killed-run-leftovers-kept and burn-sweep-takes-other-keys, both caught. craft-ai-features is only used by a unit test, so it moves to dev-dependencies. * fix(engine-burn): review findings on #90 CodeRabbit: the generator now refuses an unknown option (a mistyped --chek used to select the run that rewrites src/model; red first: tools/burn/test_generate_sam21.py failed to import parse_args); the preparation live test needs the prepare feature and is ignored by default; the refusal test no longer leaves burn-prepared/<key>.lock in the shared system temp folder (the model folder is nested one level inside the test's own folder; confirmed the old layout leaked it on this PC); docs, STATUS and the mutation README no longer describe the client feature and catalogue route, which arrive in the next PR, as available. * docs(client): say the Burn route and client feature exist, and what the status line really covers CodeRabbit on #91: the STATUS row said the host step was not built. Given the downloaded encoder.onnx the runner prepares the saved copy itself on first load; the row now says that, names the limits (no progress or Cancel during that load, no app run through the shared binding, no live run on macOS or Linux) and LOCAL-BURN-PREPARATION.md no longer calls engine registration separate work. Also restores the client feature and catalogue route in the docs and rustdoc that the #90 review fix had marked as planned, and the three mutation-README claims for them. * fix(burn-setup): sweep only the scratch folders, not a renamed copy of the key's folder CodeRabbit on #89 (second round): sweep_stale removed every folder starting with <key>., so a damaged copy a person renamed to <key>.backup would be deleted on the next preparation. It now matches only <key>.work., <key>.conv. and <key>.out., the names the scratch folders are made with (one constant for both). Red first: the sweep test gained a <key>.backup folder that must survive. Mutation group bp 13/13 caught, including the new case burn-sweep-takes-a-renamed-copy. * test(burn): the generator's usage errors must exit with code 1 CodeRabbit on #90 (second round): the parse_args tests asserted only SystemExit, which a SystemExit(0) would also satisfy. They now assert the code. Checked against a mutant that exits 0: 6 failures. * fix(engine-burn): a damaged saved copy says it is damaged and where it lives CodeRabbit on #90 (third round) pointed out that a saved copy with a bad manifest or weights fails the same way on every retry, behind the message 'could not be read or written. Try again.' It proposed deleting the copy. The rule that a derived copy is refused, never repaired or deleted for the person, stays (#89 and its tests pin it); the dead end was the wording. craft-ai-burn-setup now answers every unusable saved copy with DAMAGED_COPY (remove it, prepare again, no 'try again'), and the Burn engine adds where it lives: the burn-prepared folder beside the model folder. Tests written first (they did not compile without DAMAGED_COPY and explain): a damaged copy of three kinds gets that answer and is left untouched; the engine explains it and passes other errors on. Mutation: bp 2 new cases and be 1 new case, all caught. * fix(burn-setup): a missing or unreadable saved weight is a damaged copy too CodeRabbit on #90 (fourth round): hash_file(...)? on a saved encoder.bpk or decoder.bpk that is gone returned the generic 'try again' error before the damaged-copy branch could run. It now maps to DAMAGED_COPY. Red first: the damaged-copy test gained 'missing encoder' and 'missing decoder' cases and failed with the old message. New mutation case burn-missing-saved-weight-answered-with-try-again; the saved-hash case was re-aimed at the new line. bp 16/16 caught. * fix(burn-setup): a manifest that cannot be opened or read is a damaged copy too CodeRabbit on #91 (round 5): File::open and read_to_end on an existing manifest returned the generic 'try again' error, so the engine gave no deletion guidance. Both now map to DAMAGED_COPY. Red first: a_manifest_that_cannot_be_opened_is_a_damaged_copy (Windows: another handle holds it exclusively; Unix: mode 0, ending quietly where permissions are not enforced) failed with the old message. The Unix variant was not run here. New mutation case burn-unopenable-manifest-answered-with-try-again; bp 17/17 caught (Windows). * test(burn-setup): write the Unix permission as octal (clippy::non_octal_unix_permissions, CI only) --------- Co-authored-by: scratch <s@s> |
||
|
|
fdad29cdd4 |
feat(engine-burn): run SAM 2.1 for image.segment on Burn (#90)
* refactor(engine-rten): let another engine reuse the SAM 2.1 request handling Loaded, Backend, Prediction, read_prompt, prompt_points and best_proposal become public. Visibility only: the click and box mapping, the picture kept between requests, the empty-mask answer and the size checks then live in one place for every SAM 2.1 engine. * feat(engine-burn): crate shell and the script that generates the SAM 2.1 architecture tools/burn/generate_sam21.py checks the two published ONNX files against the pinned size and SHA-256, runs the pinned burn-onnx 0.22.0 (an example of craft-ai-burn-setup), applies the five asserted fixes, drops the generated loaders that panic on a bad file, splits by submodule so every file is under 700 lines, formats and writes. --check proves the tree is what the script produces. REVISION must equal the saved-weights cache revision. Cargo.lock additions are Burn with wgpu and ndarray (generated). * feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer Brings in craft-ai-burn-setup (feature `conversion`): checks the two published ONNX files by size and SHA-256, converts them to Burn weights with the pinned burn-onnx 0.22.0, and keeps one checked, locked, shared copy. Nothing is hosted or downloaded. Mutation group bp (10 cases). Cargo.lock additions are the optional burn-onnx tree (generated). * feat(engine-burn): GENERATED SAM 2.1 tiny architecture (30 files) Output of tools/burn/generate_sam21.py, revision sam21-tiny-burn-0.22.1-onnx-0.22.0-v1, from the published encoder.onnx and decoder.onnx with burn-onnx 0.22.0 and its five asserted fixes. Do not review line by line; rerun the script with --check instead. Longest file 699 lines. Marked linguist-generated. * feat(engine-burn): SAM 2.1 runner for image.segment on Burn Sam21Runner (engine burn, model sam21) over the generated architecture. The request handling, picture kept between requests, empty-mask answer and click/box mapping are the shared Loaded from craft-ai-engine-rten, so only the model run lives here. Weights load through BurnpackStore and come back as errors; every call into the generated code is guarded against panics. Graphics card when one answers, else the processor. An .onnx file is answered with 'prepare it first', not a guess. 16 unit tests on a fake backend: click and box mapping, empty mask, short mask, a failing model, shared conformance run with Cancel, damaged and truncated files. * test(engine-burn): live comparison with rten, and the shared revision check The ignored live test runs the real SAM 2.1 files through rten (published ONNX) and Burn (weights prepared on this computer) on the astronaut sample: one click and a box, best-mask IoU, timings, and a truncated prepared file refused. The revision test fails when the generator, the compiled architecture and the saved-weights cache key disagree. * test+docs(engine-burn): mutation group be, weight-loading tests and the Burn engine guide Group be: 15 cases, one target each, all caught (saved-weights marker, load completeness, panic guard, answer length, best proposal, file names, declared card makers, the revision shared by script, architecture and cache key, the catalogue route and the .bpk binding rule). fully_applied is split out so the load checks can be tested without the store's own refusals. Group nf's onnx case follows the rewritten extension check. docs/BURN-ENGINE.md: how to regenerate, the five fixes, the revision bump rule, limits. * feat(engine-burn): CRAFT_AI_BURN_DEVICE=cpu forces the processor, and the processor path is measured * feat(engine-burn): prepare the saved copy when loading from the downloaded ONNX files The host step: given the downloaded encoder.onnx with decoder.onnx beside it, the runner calls craft-ai-burn-setup (exact source bytes checked, reused when already saved) and loads from the burn-prepared folder beside the model folder. Behind the default 'prepare' feature; mutation group be gains two cases (17/17); docs say what is measured. * fix(burn-setup): sweep the scratch folders a killed run left, and keep craft-ai-features a dev dependency CodeRabbit on #89: tempdir_in(cache) folders hold the two source copies (about 130 MB) and were removed only by Drop, so a killed app leaked them for good. They now carry the cache key and a role in their names, and after the key's lock is taken the same key's leftovers are removed (other keys' folders, the lock file and links are left alone). Red first: leftovers_of_a_killed_run_are_swept_for_this_key_only. Mutation cases burn-killed-run-leftovers-kept and burn-sweep-takes-other-keys, both caught. craft-ai-features is only used by a unit test, so it moves to dev-dependencies. * fix(engine-burn): review findings on #90 CodeRabbit: the generator now refuses an unknown option (a mistyped --chek used to select the run that rewrites src/model; red first: tools/burn/test_generate_sam21.py failed to import parse_args); the preparation live test needs the prepare feature and is ignored by default; the refusal test no longer leaves burn-prepared/<key>.lock in the shared system temp folder (the model folder is nested one level inside the test's own folder; confirmed the old layout leaked it on this PC); docs, STATUS and the mutation README no longer describe the client feature and catalogue route, which arrive in the next PR, as available. * fix(burn-setup): sweep only the scratch folders, not a renamed copy of the key's folder CodeRabbit on #89 (second round): sweep_stale removed every folder starting with <key>., so a damaged copy a person renamed to <key>.backup would be deleted on the next preparation. It now matches only <key>.work., <key>.conv. and <key>.out., the names the scratch folders are made with (one constant for both). Red first: the sweep test gained a <key>.backup folder that must survive. Mutation group bp 13/13 caught, including the new case burn-sweep-takes-a-renamed-copy. * test(burn): the generator's usage errors must exit with code 1 CodeRabbit on #90 (second round): the parse_args tests asserted only SystemExit, which a SystemExit(0) would also satisfy. They now assert the code. Checked against a mutant that exits 0: 6 failures. * fix(engine-burn): a damaged saved copy says it is damaged and where it lives CodeRabbit on #90 (third round) pointed out that a saved copy with a bad manifest or weights fails the same way on every retry, behind the message 'could not be read or written. Try again.' It proposed deleting the copy. The rule that a derived copy is refused, never repaired or deleted for the person, stays (#89 and its tests pin it); the dead end was the wording. craft-ai-burn-setup now answers every unusable saved copy with DAMAGED_COPY (remove it, prepare again, no 'try again'), and the Burn engine adds where it lives: the burn-prepared folder beside the model folder. Tests written first (they did not compile without DAMAGED_COPY and explain): a damaged copy of three kinds gets that answer and is left untouched; the engine explains it and passes other errors on. Mutation: bp 2 new cases and be 1 new case, all caught. * fix(burn-setup): a missing or unreadable saved weight is a damaged copy too CodeRabbit on #90 (fourth round): hash_file(...)? on a saved encoder.bpk or decoder.bpk that is gone returned the generic 'try again' error before the damaged-copy branch could run. It now maps to DAMAGED_COPY. Red first: the damaged-copy test gained 'missing encoder' and 'missing decoder' cases and failed with the old message. New mutation case burn-missing-saved-weight-answered-with-try-again; the saved-hash case was re-aimed at the new line. bp 16/16 caught. * fix(burn-setup): a manifest that cannot be opened or read is a damaged copy too CodeRabbit on #91 (round 5): File::open and read_to_end on an existing manifest returned the generic 'try again' error, so the engine gave no deletion guidance. Both now map to DAMAGED_COPY. Red first: a_manifest_that_cannot_be_opened_is_a_damaged_copy (Windows: another handle holds it exclusively; Unix: mode 0, ending quietly where permissions are not enforced) failed with the old message. The Unix variant was not run here. New mutation case burn-unopenable-manifest-answered-with-try-again; bp 17/17 caught (Windows). * test(burn-setup): write the Unix permission as octal (clippy::non_octal_unix_permissions, CI only) |
||
|
|
97dc996251 |
feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer (#89)
* refactor(engine-rten): let another engine reuse the SAM 2.1 request handling Loaded, Backend, Prediction, read_prompt, prompt_points and best_proposal become public. Visibility only: the click and box mapping, the picture kept between requests, the empty-mask answer and the size checks then live in one place for every SAM 2.1 engine. * feat(burn-setup): prepare SAM 2.1 weights for Burn once, on this computer Brings in craft-ai-burn-setup (feature `conversion`): checks the two published ONNX files by size and SHA-256, converts them to Burn weights with the pinned burn-onnx 0.22.0, and keeps one checked, locked, shared copy. Nothing is hosted or downloaded. Mutation group bp (10 cases). Cargo.lock additions are the optional burn-onnx tree (generated). * fix(burn-setup): sweep the scratch folders a killed run left, and keep craft-ai-features a dev dependency CodeRabbit on #89: tempdir_in(cache) folders hold the two source copies (about 130 MB) and were removed only by Drop, so a killed app leaked them for good. They now carry the cache key and a role in their names, and after the key's lock is taken the same key's leftovers are removed (other keys' folders, the lock file and links are left alone). Red first: leftovers_of_a_killed_run_are_swept_for_this_key_only. Mutation cases burn-killed-run-leftovers-kept and burn-sweep-takes-other-keys, both caught. craft-ai-features is only used by a unit test, so it moves to dev-dependencies. * fix(burn-setup): sweep only the scratch folders, not a renamed copy of the key's folder CodeRabbit on #89 (second round): sweep_stale removed every folder starting with <key>., so a damaged copy a person renamed to <key>.backup would be deleted on the next preparation. It now matches only <key>.work., <key>.conv. and <key>.out., the names the scratch folders are made with (one constant for both). Red first: the sweep test gained a <key>.backup folder that must survive. Mutation group bp 13/13 caught, including the new case burn-sweep-takes-a-renamed-copy. |
||
|
|
870e96048c |
docs: list the rten engine and the selection workflow route, and say what was run (#86)
The README crates table, docs/LAYOUT.md and docs/STATUS.md named only Candle and the SAM 3 clients. They now list craft-ai-engine-rten (SAM 2.1 from the published ONNX files, on the processor), the imported image.segment route on ComfyUI with checked masks, and what was and was not run: Windows only, one picture, no Burn runner, no app through the shared binding yet. |
||
|
|
611195b50e |
feat(ai-comfyui): send a selection picture once and resend it only when it is gone (#82)
* feat(ai-comfyui): import a selection workflow and run it with the picture sent first Adds the `image.segment` capability to imported ComfyUI workflows. A selection workflow maps a text prompt and one source picture; the picture is uploaded, the graph is queued with the name ComfyUI gave it, and every queued graph gets a sink name of its own so a repeat is not answered from cache with no output. Clicks or a box are refused in plain words before anything is sent, and a stored workflow file may declare a source binding and no mask. The answer is the graph's image as it comes. Checking the mask is the next change. * feat(ai-comfyui): check a selection workflow's mask and answer in the shared shape A selection workflow's image is now a mask the shared contract can trust. It must be the size of the picture sent (a JPEG may come back turned a quarter, because ComfyUI's loader applies the EXIF turn), is reduced to one 8-bit channel, and is followed by the shared `Found` result. A mask with no pixel above half is an empty mask and `matched: false`, never a failed job. Picture sizes are read from the PNG or JPEG header and bounded. This is not calibrated absence detection: the example Florence graph finds a box for any phrase. * feat(ai-comfyui): send a selection picture once and resend it only when it is gone A repeat selection on the same picture reuses the file already in ComfyUI's scratch area, keyed by a hash of the bytes. Only the last four pictures are remembered. If ComfyUI has cleared its scratch area (a restart), the first refusal of a reused name drops the entry and sends the picture again once; a refusal of a fresh upload is never retried. A failed selection job clears the cache, since the file may be what went wrong. Adds the ignored live test against a real ComfyUI. * test(ai-comfyui): count refused prompts without the deprecated fetch_update Newer Rust renames AtomicUsize::fetch_update to try_update and warns, which the strict Clippy job turns into an error on CI. The scripted server handles one job at a time here, so a load and a fetch_sub do the same job and build on both toolchains. * fix(ai-comfyui): hand on a binary mask, white where selected and black elsewhere A review finding: the first channel was kept as the graph saved it, so pixels from 128 to 254 reached the app as partly selected, while the shared contract says selected pixels are white. Every pixel above half is now 255 and the rest 0. Written first and seen to fail (the answer kept [0, 100, 128, 200, 255]); mutation cases added for a grey kept as selected and a low grey kept. * docs(ai-comfyui): state the selection mask's byte limit, test it, and rename a mutation case Two review findings. The mask is read inline under the provider's output limit (never more than the 32 MiB inline cap) and never to the output folder, because the checks need its bytes in hand; that is now written in the module header and the provider, and a test shows a mask over a lowered limit fails the job and hands on nothing, with a mutation case for the limit being ignored. The case that only removed the media-type guard is renamed so it no longer implies JPEG answers are covered. The limit test passed on first run, as the behaviour already existed: it is a guard, not a red-first fix. * fix(ai-comfyui): forget the cached pictures when any selection job fails A review finding: only an error status from ComfyUI cleared the upload cache, so a job whose mask was fetched but refused (wrong size, not a PNG) left its picture cached and the next selection could reuse a stale scratch name. The cache is now cleared once, after the job's state is settled, whenever a selection job ends failed. Written first and seen to fail (a wrong-size mask left one upload for two selections); the existing mutation case is re-aimed at the single clear. |
||
|
|
4d4ef93a23 |
feat(ai-engine-rten): run SAM 2.1 through the shared selection contract (#79)
* feat(ai-core): share the image.segment request and result contract * fix(ai-core): take only an inline PNG as the selection mask * feat(ai-engine-rten): bounded picture decoding, mask encoding and resampling for selection models * feat(ai-engine-rten): run SAM 2.1 through the shared selection contract * fix(ai-engine-rten): bound a thin picture's memory, refuse extreme sides, and make the mask size fallible * fix(ai-engine-rten): judge a match on the mask handed on, not on the raw logits A review finding: matched was set from the model's raw logits before resampling and 8-bit quantization, so one positive logit that a small picture never samples reported a match with an all-black mask. The match is now whether any pixel of the emitted mask is above half, using the same quantization as the PNG. Written first and seen to fail (matched stayed true for a speck at logit 8 in a 10 by 6 picture). The runner's raw-logit test stays as a shortcut that skips the resampling; forcing it open gives the same answer, so its mutation case is retired with the reason in the group header. * docs(mutation): point the usage text at GROUPS instead of a list that was out of date A review finding: the usage line named only the early groups and left out rt, which is new here, and also seg, gs and others. A list in the usage text goes stale each time a group is added, so it now says to take the group from GROUPS and README.md. |
||
|
|
dae74cc8a7 |
feat(ai-comfyui): check a selection workflow's mask and answer in the shared shape (#81)
* feat(ai-comfyui): import a selection workflow and run it with the picture sent first Adds the `image.segment` capability to imported ComfyUI workflows. A selection workflow maps a text prompt and one source picture; the picture is uploaded, the graph is queued with the name ComfyUI gave it, and every queued graph gets a sink name of its own so a repeat is not answered from cache with no output. Clicks or a box are refused in plain words before anything is sent, and a stored workflow file may declare a source binding and no mask. The answer is the graph's image as it comes. Checking the mask is the next change. * feat(ai-comfyui): check a selection workflow's mask and answer in the shared shape A selection workflow's image is now a mask the shared contract can trust. It must be the size of the picture sent (a JPEG may come back turned a quarter, because ComfyUI's loader applies the EXIF turn), is reduced to one 8-bit channel, and is followed by the shared `Found` result. A mask with no pixel above half is an empty mask and `matched: false`, never a failed job. Picture sizes are read from the PNG or JPEG header and bounded. This is not calibrated absence detection: the example Florence graph finds a box for any phrase. * fix(ai-comfyui): hand on a binary mask, white where selected and black elsewhere A review finding: the first channel was kept as the graph saved it, so pixels from 128 to 254 reached the app as partly selected, while the shared contract says selected pixels are white. Every pixel above half is now 255 and the rest 0. Written first and seen to fail (the answer kept [0, 100, 128, 200, 255]); mutation cases added for a grey kept as selected and a low grey kept. * docs(ai-comfyui): state the selection mask's byte limit, test it, and rename a mutation case Two review findings. The mask is read inline under the provider's output limit (never more than the 32 MiB inline cap) and never to the output folder, because the checks need its bytes in hand; that is now written in the module header and the provider, and a test shows a mask over a lowered limit fails the job and hands on nothing, with a mutation case for the limit being ignored. The case that only removed the media-type guard is renamed so it no longer implies JPEG answers are covered. The limit test passed on first run, as the behaviour already existed: it is a guard, not a red-first fix. |
||
|
|
4effe6a190 |
feat(ai-comfyui): import a selection workflow and run it with the picture sent first (#80)
Adds the `image.segment` capability to imported ComfyUI workflows. A selection workflow maps a text prompt and one source picture; the picture is uploaded, the graph is queued with the name ComfyUI gave it, and every queued graph gets a sink name of its own so a repeat is not answered from cache with no output. Clicks or a box are refused in plain words before anything is sent, and a stored workflow file may declare a source binding and no mask. The answer is the graph's image as it comes. Checking the mask is the next change. |
||
|
|
8be4066b1f |
feat(ai-engine-candle): SAM 3 on the Candle engine, and the catalogue names the files it reads (#41)
* feat(ai-engine): a runner contract for models that run on this computer
Candle and Burn were named in the catalogue but no app could share them: each would have needed
its own job handling, cancel, progress and weights loading. This adds the seam so an engine author
writes only the model.
- craft-ai-engine: ModelRunner (engine, model spec, load) and LoadedModel (run), a RunContext for
progress, cancel and notices, an EngineRegistry, and EngineProvider, the one Provider that runs
any registered model (weights loaded once, jobs for one model take turns, a panicking runner
becomes a failed job).
- testing::{FakeRunner, check_runner}: puts a runner behind the real provider and runs the shared
conformance suite.
- craft-ai-client: ProviderFactory::register_engines is the whole of enabling an engine in an app;
register now forgets what was declared about the adapter it replaces, and unregister removes one.
- docs/ADD-AN-ENGINE.md is the crate documentation, so its code is compiled by the doctests.
* feat(ai-engine-candle): SAM 3 on the Candle engine, and the catalogue names the files it reads
The built-in SAM 3 route was documented as reading the same file as ComfyUI. It does not: the
ComfyUI file is Meta's layout (detector.backbone..., 1465 tensors); the Candle port reads the
Hugging Face layout (detector_model..., 1797 tensors) plus vocab.json and merges.txt. A route
pointed at the ComfyUI file could never load.
- ai-features: NativeRoute gains its own `models`, so a runtime can name the files it reads. The
SAM 3 routes name facebook/sam3 at a pinned revision, with sizes and SHA-256 checked against a
real download. NativeRoute::weights and total_bytes read them.
- craft-ai-engine-candle: the model code from LightCraft's lightcraft-segment crate (see NOTICE),
behind the runner contract. image.segment takes a PNG source and either a text prompt or click
points, and answers with a grayscale PNG mask the size of the source. Apache-2.0 only, because
the port is a derivative of Hugging Face Transformers.
- craft-ai-client: the `candle` cargo feature makes ProviderFactory::standard() know the engine, so
an app adopts it by turning the feature on.
* fix(ai-engine,ai-client): keep one provider per connection, and let a cancelled job leave the queue without loading or running
The client asks the factory for a provider on every job, so each job built a fresh EngineProvider and
loaded the weights again; two jobs at once loaded two copies. The factory now keeps one provider per
connection and builds another only when the connection's models or weight files change.
A job waiting behind another for the same model reported Running, and if it was cancelled it still
loaded the weights and ran. It now reports Queued until it holds the model, and a cancel before then
or during a slow load stops it before any work. At most 16 jobs may wait or run at once; a burst is
refused in plain words rather than piling up threads that each hold a copy of the picture.
* fix(ai-client): write the kept-provider key with escapes, not a literal newline and tab
* fix(ai-features,deny): say what the Candle route really runs on, offer no download for Burn, and record the candle advisories
The Candle route said it ran on Nvidia or Apple graphics, but this build declares the Apple card only and
runs on the processor elsewhere; the label now says so. The Burn route named the 3.4 GB Hugging Face files
although no Burn code exists, so it now names none and offers no download.
cargo-deny failed on candle-core's zip (RUSTSEC-2026-0367, 0368, 0369) and paste (RUSTSEC-2024-0436).
Each is ignored with the reason it cannot be reached here: only safetensors are read and no archive is
extracted.
* feat(ai-engine-candle): read JPEG pictures, and turn them upright by their EXIF orientation
A source can now be a PNG or a JPEG, told apart by its first bytes. JPEGs are decoded with zune-jpeg through
the image crate (baseline, progressive, greyscale), refused from the header when over 100 megapixels, and
given an allocation cap. The EXIF orientation is applied, as browsers, photo editors and OpenCV do, so a
phone photo taken sideways is segmented upright and a click normalised to the picture lands where the person
clicked. The mask comes back the size of the upright picture. A PNG is read as stored.
Verified on Meta's checkpoint in release mode: a 128x192 JPEG marked 'turn 90 degrees clockwise' gives a
192x128 mask centred on the disc. Unit tests cover colour and greyscale, every damaged and cut-off case,
a header patched to 30000x30000, and the turn itself (the test fails without it).
jpeg-encoder makes the test JPEGs; it carries the IJG licence, allowed for that one crate in deny.toml.
* test(ai-engine-candle): write the EXIF header with escapes, not raw NUL bytes, so git shows the file as text
* fix(ai-engine-candle): lift the PNG decoder's buffer limit, and bound tokenizer work for long prompts
A one-row picture inside the 100 megapixel limit but with a row over 64 MiB was refused by the png crate's default allowance; the decoder now gets the same 900 MiB cap as the JPEG route. Tokenizer::encode now clips the text to CONTEXT * 32 characters and each word to CONTEXT * 8 before the merge loop, and stops once the ids fill the context. Both found by CodeRabbit on #41.
* docs(ai-engine-candle): doc comments on the functions touched by the review fixes
* fix(ai-engine-candle): collapse whitespace before the tokenizer's character limit
Spaces at the start of a prompt used up the 1,024 character allowance, so a prompt of 1,024 spaces then a word reached the model as nothing. Whitespace is now collapsed first, and the text is copied only as far as the allowance reaches. Found by CodeRabbit on #41.
---------
Co-authored-by: scratch <s@s>
Co-authored-by: t <t@t>
|
||
|
|
037a011df6 |
feat(ai-features,ai-client): a tool can offer several local models (#63)
* feat(ai-features,ai-client): a tool can offer several local models Feature.local becomes Feature.locals (breaking). plans() gives one plan per recipe, named in Plan.recipe. Setup options are per recipe (local:<feature>:<recipe>, breaking). ToolDesk::enable_local_recipe registers one named recipe as its own connection; the first keeps local-<feature>. * fix(ai-client): keep recipe connections apart from built-in runtimes, and follow the runnable recipe A second recipe's connection is now local-<feature>-recipe-<workflow>, so a recipe named like a runtime (candle, burn) can never replace that runtime's connection. engine_advice, enable_native and enable_native_with use the first recipe that can run, the same one enable_local registers. * docs: say which recipe a built-in runtime belongs to * fix(deps): update rustls-webpki and webpki roots (RUSTSEC-2026-0381, 0382, 0383) rustls-webpki 0.103.15 -> 0.103.16, webpki-roots and webpki-root-certs 1.0.9 -> 1.0.10. The new versions reject certificate paths through the distrusted emSign intermediates, whose private keys are now public. Lockfile only. |
||
|
|
7428cb8c75 |
fix(ai-core,ai-egui): required inputs and test-result addresses, matching the upstream contract fixes (#59)
* refactor(ai-core): move the connection presets into their own file draft.rs was 519 lines. The built-in presets and their static model lists are data that changes on a different schedule from the save rules, so they move to draft/presets.rs unchanged. Three mutation cases follow the code. * fix(ai-core,ai-egui): match the upstream contract fixes for required inputs and test-result addresses A model now has to accept every input a tool sends and require no input the tool cannot supply; the picker, binding, app status and planning agree, and a refusal happens before a key is read or anyone is asked to consent. A connection test result is recorded with the address the test started with (ConnectionDraft::set_models(address, models)), so a late answer for an old address is refused and loaded, preset and tested models keep their address through repeated edits. The shared connection panel passes the captured address. docs/CORE-SYNC.md says what this local copy still adds beyond craft-libs, and the mutation group 'ca' covers the ten safety rules. Two mutation anchors that matched twice are fixed. * docs: document the functions this change adds CodeRabbit's docstring check was below its 80% bar. Test functions get a one-line sentence from their name; helpers and session methods get a real description. |
||
|
|
ea85917afe |
fix(ai-openai): cap a streamed reply and the events a job holds unpollled (#53)
* fix(ai-vertex): send the express key in a header, not the URL query C4 from the 2026-10-17 security audit. url() percent-encoded the API key and appended "?key=" to every generation request, making the Vertex express adapter the only provider whose credential traveled in the request URL. Request lines are what TLS-intercepting proxies and access logs commonly record - and craft-ai-http deliberately trusts the platform's certificate store, so such middleboxes can be reading - while header sets are rarely logged in full. Every other adapter already kept its key in a header. The key now travels only in the x-goog-api-key header, the same header the Gemini API documents for key auth, and url() no longer touches it. Header injection cannot occur: the key was already validated at construction to contain no control characters or whitespace. The test server now asserts the path carries no key and the header carries the key, and two mutation cases (vx group) pin the rule: putting the key back in the URL, or dropping the header, are both caught. Verified against the scripted server only; per the audit's note, one live express-mode run is still wanted before claiming the official endpoint accepts the header, and nothing here was run against a real provider. Co-Authored-By: Claude Code <noreply@anthropic.com> * test(ai-vertex): pin that submit refuses other models and options before any call A CodeRabbit review round on PR #52 flagged that only the Mask-input refusal was covered. The provider refuses a wrong model, a streamed request, a second output and any param before any network call; each case now asserts ErrorKind::Unsupported and that the scripted server was never contacted (count stays 0). Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(ai-openai): cap a streamed reply and the events a job holds unpollled C5 from the 2026-10-17 security audit, found independently by two auditors. The streaming path capped every hostile input except the total: SseState.text grew by push_str for as long as the stream stayed open, tool-call arguments likewise, and every delta was also pushed as a TextDelta event into the job cell, which grew without end if nobody polled. A hostile OpenAI-shaped server could accumulate text twice for the full 600-second request timeout, into the multi-gigabyte range. The reply is now bounded three ways: - Per line: unchanged (MAX_SSE_LINE, 1 MiB). - Total bytes kept: new MAX_STREAM_TOTAL, the same size as the whole-reply cap http::MAX_BODY (128 MiB), so a stream can never hold more than a whole reply would. Text and tool-call name/argument bytes count against one shared budget; a line that passes it fails the stream with "the streamed reply was too large". - Events held for one poll: new MAX_EVENTS (65,536) in JobCell. A stream that produces more without a poll fails the job with "too many events are waiting; poll the job while it runs" and the backlog is dropped, rather than growing for as long as the request timeout allows. The worker's line loop now stops when the cell is terminal, not only when cancelled: a job failed by the backlog cap must also stop reading, drop the connection and free its worker for the rest of the 600-second window it would otherwise burn. Mid-stream a terminal cell is exactly cancel or backlog failure, since the worker sets the terminal states only after the loop returns. chat.rs was at the 500-line soft limit and this grows the streaming half, so the SSE reader moved to stream.rs (SseState, MAX_SSE_LINE, MAX_STREAM_TOTAL) and chat.rs keeps request planning and whole-reply parsing; both are well under the limit. The total cap is a field defaulted to MAX_STREAM_TOTAL with a test-only with_cap, so a stream can be driven past the limit cheaply, the same trick read_capped's parameter takes. Six u1 mutation cases pin the rules, all caught: removing either cap check, unlimited defaults, a loosened event cap, a backlog kept after failure, and a worker still reading a dead cell's stream. The last is caught by a new provider test that streams 70,000 deltas nobody polls: the job fails at the cap and the server sees the connection drop. Verified against the scripted server only; no real provider contacted. Co-Authored-By: Claude Code <noreply@anthropic.com> * test(ai-openai): leave the firehose far more unread than kernel socket buffers CI failed on all three OSes: the worker failed the job at the event cap and dropped the connection, but the server never reported the drop. The scripted server only notices when a write fails, and with 70_000 chunks about 210 KB remained when the worker stopped - little enough that CI's autotuned kernel buffers swallowed it, the server finished writing, and client_dropped never became true. One million chunks leave about 44 MB unread, which no kernel buffers; the drop is observed within the deadline on every platform. CodeRabbit flagged the same line on PR #53 and asked for 400_000; the larger count widens the margin past even generous Linux autotuning. Each line still holds one byte of text and only 65_537 lines are ever read, so the byte total stays far under the stream cap. The dead-cell-still-read mutation case still catches its mutant. Co-Authored-By: Claude Code <noreply@anthropic.com> * docs(ai-openai,ai-vertex): document every function the PR's diff touches CodeRabbit's docstring coverage pre-merge check on PR #53 reads 72% against an 80% threshold, scoped to functions touched by the diff (25 functions across 8 files). The comment names no functions, so every diff-touched function in the stacked diff that lacked a /// now has one: jobs.rs (push, succeed, run_chat and two unit tests), stream.rs (Default, tool_delta and three unit tests), the three touched provider tests in each crate, and vertex lib.rs's lock and generate. Production docs state the bound or contract; test docs are one line naming the behaviour the test pins. No code changes; all tests pass and every mutation target still resolves uniquely. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: Claude Code <noreply@anthropic.com> |
||
|
|
72bf336f96 |
feat(ai-core,ai-comfy-env,ai-client): the person's model folders, kept as a map and never reorganised (#40)
* feat(ai-core,ai-comfy-env,ai-client): the person's model folders, kept as a map and never reorganised People already keep models in folders of their own. This lets the suite point at them instead of asking for a layout. - ai-core::model_folders: a folder, what is known to be in it (kind to sub-folders, with ComfyUI's names), the checks every list passes before it is stored (full paths, no sub-folder that leaves its folder, one default, limits), and download_target, which never picks a folder read from another program. StoreFile gains `model_folders`; older files load unchanged. - ai-comfy-env: scan_model_folder reads a folder and records where each kind lives, from a known file name and size, a folder name, or a safetensors header. Read only, bounded by depth, files, entries and header size, and a link is followed once. render_extra_paths writes the map as a ComfyUI extra-model-paths file, leaving out any folder that would not pass the store's checks. - ai-client: FolderDesk to add, rescan, choose the default, remove and write the extra-paths file. - ai-native: the folder the launcher proposes when a person has none. * fix(ai-client,ai-native): removing the last model folder sticks, case counts only where the file system says so, and the macOS test skips The store carries unknown top-level keys through a rewrite, and model_folders was not on its list of known keys. With the last folder removed the typed list is empty and is left out of the output, so the old list was put back from the file: the folder could not be removed. It is a known key now. A duplicate folder was found by lower-casing the whole path, which made /Models and /models the same folder on Linux. Case is ignored only on Windows and macOS now, and the Windows verbatim prefix is dropped so a folder that exists and one that does not still meet. The non-text path test cannot create its folder on macOS, which refuses such names; it skips there. --------- Co-authored-by: scratch <s@s> |
||
|
|
69ebbc0491 |
feat(ai-engine): a runner contract for models that run on this computer (#39)
* feat(ai-engine): a runner contract for models that run on this computer
Candle and Burn were named in the catalogue but no app could share them: each would have needed
its own job handling, cancel, progress and weights loading. This adds the seam so an engine author
writes only the model.
- craft-ai-engine: ModelRunner (engine, model spec, load) and LoadedModel (run), a RunContext for
progress, cancel and notices, an EngineRegistry, and EngineProvider, the one Provider that runs
any registered model (weights loaded once, jobs for one model take turns, a panicking runner
becomes a failed job).
- testing::{FakeRunner, check_runner}: puts a runner behind the real provider and runs the shared
conformance suite.
- craft-ai-client: ProviderFactory::register_engines is the whole of enabling an engine in an app;
register now forgets what was declared about the adapter it replaces, and unregister removes one.
- docs/ADD-AN-ENGINE.md is the crate documentation, so its code is compiled by the doctests.
* fix(ai-engine,ai-client): keep one provider per connection, and let a cancelled job leave the queue without loading or running
The client asks the factory for a provider on every job, so each job built a fresh EngineProvider and
loaded the weights again; two jobs at once loaded two copies. The factory now keeps one provider per
connection and builds another only when the connection's models or weight files change.
A job waiting behind another for the same model reported Running, and if it was cancelled it still
loaded the weights and ran. It now reports Queued until it holds the model, and a cancel before then
or during a slow load stops it before any work. At most 16 jobs may wait or run at once; a burst is
refused in plain words rather than piling up threads that each hold a copy of the picture.
* fix(ai-client): write the kept-provider key with escapes, not a literal newline and tab
---------
Co-authored-by: scratch <s@s>
|
||
|
|
301ee23f7c |
fix(ai-client): refuse a choice the app cannot run at plan, and test the third-party path (#38)
plan() did not check that the app has an adapter for the chosen service, so an app without one showed the consent prompt and only failed after the person agreed. start() also read the key from the keychain before finding out there was no adapter to give it to. Both now refuse first, with the one sentence status already uses. Adds the executable adoption example PLATFORM-CONTRACT.md asked for (a vendor's tool and service used by two independent apps, consent per app, cancel, an app without the adapter, an older store file) and docs/ADOPT-A-TOOL.md, which walks through it. |
||
|
|
4d8e733924 |
docs: remove internal task codes and add community files (#29)
The comments and docs carried labels from our own planning (task u2, v3, l5, Phase 2e, t8) that mean nothing to a reader of a public repository, and one design note pointed at a folder that is no longer in the tree. CONTRIBUTING said main is protected, which is not set up yet. - Strip the task labels from module comments and test headers (comment text only; no code changes). Reword the ai-core crate comment to say the contract is provisional pending craft-libs review. - Rename docs/design/u2-declarative-adapter.md to declarative-adapter.md, point it at tools/mutation, and update the three references. - CONTRIBUTING: say changes arrive by pull request instead of claiming a protection that is not configured; make the build advice about local convenience, not a rule. - Add SECURITY.md (private reporting through GitHub), issue forms, a pull request template and .gitattributes (LF in the repository). Checked: cargo fmt --all --check, cargo check -p craft-ai-core -p craft-ai-egui, and mutation_check.py --dry on all 14 groups (every case still has exactly one target). CI runs the rest. |
||
|
|
aea912bb55 |
chore: prepare the repository for transfer to storytold/craft-ai-integrations
- Rename the contract crate ai-model to ai-core (package craft-ai-core), matching the crate proposed for craft-libs. - Port the two fixes already made in the craft-libs copy: consent expiry is per kind of data, and models found by a test at a new address survive a save (ConnectionDraft::set_models). - Take docs/research, the SAM 3 handoff notes and their scripts out of the tree (local paths and evidence files). Move the deliberate-bug harness to tools/mutation and repair ten cases that no longer matched the source. - Rewrite the README, add docs/STATUS.md (tested, run for real, not verified), fix LAYOUT, PLATFORM-CONTRACT and CONTRIBUTING, add the missing ai-comfyui manifest fields, point the repository URL at storytold/craft-ai-integrations, and add a wasm check for craft-ai-features. - Allow clippy::large_enum_variant on TestTarget, which the larger draft now trips. Checked on Windows: fmt, clippy --all-targets -D warnings on all 16 crates, 967 tests passed (15 ignored), wasm check for craft-ai-core and craft-ai-features. Not run: cargo-deny, Linux, macOS, live services, the real keychain test. The contract stays provisional until craft-libs review. |
||
|
|
f5a9f9db6d |
chore: remove local mutation-check logs that were committed by mistake
|
||
|
|
1ba49dc08b |
fix(ai-comfy-env): refuse a node pack archive with folders that differ only in case (#3)
The archive reader refused two file names that differ only in case but not two folder names, so an archive holding Dir/a.py and dir/b.py made two folders on a case-sensitive disk and one on Windows and default macOS. Names are now tracked as a path tree: a folder spelt two ways, a file and a folder that differ only in case (either order) and a directory entry spelt differently from an earlier folder are all refused with the same reason as the file rule. Using one spelling of a folder again is still fine. Five new cases in hostile_archives_are_refused_for_the_right_reason, each asserting the exact reason; the U4 mutant for the old check is updated and two more are added (folders accepted, folders compared by lower-case path), all caught. Closes #3 |
||
|
|
ed8447e5cc |
feat(ai-http): check hosted certificates with the platform verifier
Every adapter and downloader built its own ureq agent with the bundled public roots, so a machine whose antivirus or company proxy re-signs HTTPS with an installed root could not reach any hosted service. The launcher hit this. New crate craft-ai-http holds the one setting (tls_config(), the platform verifier) and all ten crates that build an agent call it. A test reads the source of every crate and fails if an agent is built without it. Trade-off, written at the top of the crate: roots the operating system has installed are now trusted, so software the person chose to install can read the traffic, API keys included. Unverified: a real intercepting proxy or antivirus, and the platform verifier on macOS and Linux. The scripted tests use plain http. |