Files
craft-ai-integrations/tools/mutation/mutation_app_tools.py
T
Jeremy 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.
2026-11-13 18:54:45 +01:00

44 lines
4.5 KiB
Python

"""Deliberate-bug cases for group `at`: AppTools lists, plans and runs tools the same way for every app.
Loaded by mutation_check.py. Each case breaks one rule and names the test that should notice.
Format: (name, file, old, new, package, test target, test filter). Target 'lib' runs unit tests.
Not mutation-covered, with the reason: "reading writes nothing" and "a tool with no choice is
greyed, not an error" are delegated to AiClient::status and SharedStore::load, whose own groups
(`ca`, `ct`) cover them; app_tools.rs adds no code of its own to break there. The consent ledger is
passed straight to AiClient::start, which refuses a missing agreement (group `ct`,
`consent-not-enforced`); ignoring a granted ledger would refuse a job, not send one.
"""
A = 'crates/ai-client/src/app_tools.rs'
CL = 'craft-ai-client'
T = 'app_tools'
AT = [
('unknown-tool-falls-back-to-the-first-tool', A, '.find(|role| role.id.as_str() == tool))', '.find(|role| role.id.as_str() == tool)\n .or_else(|| self.roles.first().map(|(_, role)| role.clone())))', CL, T, 'an_unknown_tool'),
('custom-tools-left-out-of-the-report', A, 'custom.iter().map(|role| (role.label.as_str(), role))', 'custom.iter().take(0).map(|role| (role.label.as_str(), role))', CL, T, 'a_custom_tool_is_listed'),
('custom-tool-has-no-role', A, 'Ok(self\n .custom_tools()?\n .into_iter()\n .find(|role| role.id.as_str() == tool))', 'Ok(None)', CL, T, 'a_custom_tool_is_listed'),
('request-for-the-wrong-capability', A, 'Request::new(role.capability)', 'Request::new(craft_ai_core::CapabilityId::parse("text.complete").unwrap())', CL, T, 'a_request_carries'),
('run-drops-the-outputs', A, 'Event::Output(output) => outputs.push(output),', 'Event::Output(_) => {}', CL, T, 'plan_then_run'),
('cancelled-job-reported-as-success', A, 'JobState::Cancelled => Err("Cancelled.".to_owned()),', 'JobState::Cancelled => Ok(Vec::new()),', CL, T, 'cancel_reaches_the_running_job'),
('failed-job-reported-as-success', A, 'JobState::Failed { error } => Err(error.message),', 'JobState::Failed { error } => {\n let _ = error;\n Ok(Vec::new())\n }', CL, T, 'a_failed_job'),
('running-job-not-recorded', A, 'lock(&self.running).push((number, job.clone()));', 'let _ = number;', CL, T, 'cancel_reaches_the_running_job'),
('cancel-reaches-only-the-first-job', A, 'for job in jobs {', 'for job in jobs.into_iter().take(1) {', CL, T, 'one_cancel_reaches'),
('finished-job-forgets-every-job', A, 'lock(self.running).retain(|(n, _)| *n != self.number);', 'lock(self.running).clear();', CL, T, 'a_finished_job_removes'),
('own-limit-ignored', A, 'job.wait(step, limit)', 'job.wait(step, LIMIT)', CL, T, 'outlasts_the_wait'),
('text-reply-dropped', A, 'Event::TextDelta { text: part } => text.push_str(&part),', 'Event::TextDelta { .. } => {}', CL, 'app_tools_stop', 'a_text_reply'),
('refused-stop-reported-as-stopped', A, 'Err(_) => job.poll().is_ok_and(|snap| snap.state.is_terminal()),', 'Err(_) => true,', CL, 'app_tools_stop', 'will_not_stop'),
('refused-cancel-hidden', A, ' if job.cancel().is_err() {\n refused = refused.saturating_add(1);\n }', ' let _ = job.cancel();', CL, 'app_tools_stop', 'a_refused_cancel'),
('unreadable-answer-left-running', A, ' if stop(&job) {\n e.message', ' if true {\n e.message', CL, 'app_tools_stop', 'unreadable_answer'),
('cancel-reads-the-result-away', A, ' if job.cancel().is_err() {', ' if !stop(&job) {', CL, 'app_tools_stop', 'as_the_job_finishes'),
('zero-wait-starts-a-job', A, ' if limit.is_zero() {', ' if limit.is_zero() && false {', CL, 'app_tools_stop', 'zero_wait'),
('online-job-asked-every-step', A, 'Locality::Remote => REMOTE_STEP,', 'Locality::Remote => STEP,', CL, 'app_tools_stop', 'online_job'),
('no-limit-overflows', 'crates/ai-client/src/client_wait.rs', 'now.checked_add(timeout.min(LONGEST_WAIT)).unwrap_or(now)', 'now + timeout', CL, 'app_tools_stop', 'no_limit'),
('unreadable-store-is-an-unknown-tool', A, '.map_err(|e| e.to_string())\n }', '.or_else(|_| Ok(Vec::new()))\n }', CL, 'app_tools_stop', 'unreadable_store'),
]
AT_EQUIVALENT = {}
# Reviewed and dropped: removing a cancel from run_for after a timeout. Job::wait already cancels the
# job when its limit passes, so that mutant is equivalent; own-limit-ignored and the outlasts test
# cover the limit instead.