diff --git a/AGENTS.md b/AGENTS.md index 6726ea84..0299dca6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,6 +94,12 @@ These go beyond the global defaults because this repo's release pipeline `root.go`. - `internal/{scaffold,validate,pkgzip,manifest,api,config,auth}` — the building blocks behind those commands. +- `internal/genapi` — the orchestrator **generation** client behind + `civitai generate` and `civitai workflows …`: tRPC transport, the two envelope + shapes, the graph payload, model-version resolution. Deliberately not in + `pkg/civitai` (that is the public read/download SDK) because generation is a + money-spending surface whose wire shape is not a public contract. Read + items 12–17 before touching it. - **Module root** (`package cli`, `main.go` + `schema.go`) exists *only* to `go:embed` the vendored `schema/` and `examples/`. It is not the executable. @@ -154,9 +160,16 @@ func newWhoAmICmd() *cobra.Command { Items 1–3, 10 and 11 are deliberate mirrors of the platform (items 4 and 8 are deliberate *non*-mirrors); items 5–9 cover `civitai app metrics`, the CLI's only -analytics read path. The durable fix for the mirroring is a server-side -`civitai app validate` endpoint that calls the real `BlockManifestValidator` — -until that exists, vendoring is on purpose. +analytics read path; items 12–17 cover `civitai generate`, the CLI's only path +that **spends the user's money irreversibly**. The durable fix for the mirroring +is a server-side `civitai app validate` endpoint that calls the real +`BlockManifestValidator` — until that exists, vendoring is on purpose. + +The generate items pull in the opposite direction from the mirror items, and +that is deliberate: `validate` mirrors the platform because a local answer is +*cheaper* than a round-trip, while `generate` mirrors nothing because a local +answer that is *wrong* costs real Buzz. Read item 13 before adding any check to +that path. **Maintaining this list:** items are append-only and numbered by arrival — a PR adding items takes the next free numbers, and when two PRs collide the one @@ -502,10 +515,179 @@ neither one's. no correctness gain. If you reconsider, note the init-fragment fast path ships gated off and refuses `surface === 'dev-tunnel'` by construction. -**When you change a validation rule, keep both vendored mirrors (`schema/` + the -ported Go checks in `internal/validate/`, including the slot registry) in sync -with the server, and update `examples_test.go` (asserts shipped examples -validate clean) + the README.** +12. **`civitai generate` calls tRPC, not REST — because there is no REST + generation route to call.** Exactly the situation item 5 documents for + `app metrics`, and it will attract the same "fix". Generation exists only as + the tRPC procedures `orchestrator.whatIfFromGraph` (the cost estimate, a + GET) and `orchestrator.generateFromGraph` (the submit, a POST) in + `civitai/civitai → src/server/routers/orchestrator.router.ts`; there is no + `/api/v1` equivalent, and the same is true of the reads behind + `civitai workflows list|get|cancel`. So `internal/genapi` speaks tRPC — path + constants in `generate.go`, the query's input riding in + `?input={"json":{…}}`, success unwrapping `result.data.json` — reusing the + `authedDo` + envelope-unwrap pattern `internal/appapi` already established. + Don't "simplify" any of it into a REST call that does not exist. + Two things in there are load-bearing and look like oversights. `unwrapTRPC` + rejects a literal `null` payload as malformed rather than unmarshalling it: + `null` decodes CLEANLY into a zero `WhatIfResult`, which renders as + **total 0** — a fabricated free quote, on the one screen a user reads before + approving a charge. And `CancelWorkflow` deliberately does NOT go through + that unwrap, because the server's successful cancel reply has no + `result.data.json` at all (`workflows.ts`) — routing it through the standard + path would turn **every successful cancel** into "unexpected response". HTTP + 200 is the success signal there. + +13. **The CLI deliberately validates NOTHING about the generation graph, and + that is the feature.** `internal/genapi/graph.go` models a handful of fields + and `--input` passes a caller's graph through byte-for-byte. It does not + vendor, and must never vendor: the ecosystem keys, the ~51 per-engine + graphs, the sampler enum, the resolution/aspect-ratio buckets, the + per-ecosystem defaults, the tier limits, or any cost table. The server + re-derives every one of them at submit time from state the CLI cannot see — + a caller's usable (non-disabled, non-memberOnly) ecosystem set, for one, so + even the *default* model differs between a free and a member account — so a + vendored copy buys no correctness, goes stale, and starts **refusing valid + new inputs**, which is worse than the gap it closes. This is the same + anti-mirror judgement as item 8, with money on it. + Two consequences that look like missing features: + (a) `KnownGraphKeys()` (`graph.go`) is derived by REFLECTION over the struct + tags, never hand-listed, and it answers *"does the CLI model this key?"* — + **not** *"does the server accept it?"*. `unknownKeyWarning` + (`internal/cmd/generate_input.go`) is worded to say exactly that and must + stay worded that way; a warning phrased as "invalid key" would be a + validation claim this CLI has no authority to make. + (b) The one bounded exception is `serverQuantityClamp` in + `internal/cmd/generate.go` — a **warn-only** constant, currently 10, that + **fails soft**: it warns and sends anyway. It exists because the server + silently CLAMPS an out-of-range quantity (measured: 10000 → 10, −5 → 1) with + no error, so a `--quantity 40` typo charges for 10 and gives the user no + signal at all. Because it only warns, a stale number produces a needless + note, never a blocked valid request. Do not promote it to validation, and do + not add siblings for the other clamped fields without the same fail-soft + shape. + **Live lookups are not mirrors**, which is why one is allowed: + `ResolveModelVersion` (`internal/genapi/versions.go`) resolves + `--checkpoint` / `--lora` ids against the existing public + `GET /api/v1/model-versions/{id}` before submitting. It is a round-trip, so + it carries no drift cost, and it buys two things nothing else can. A + **nonexistent** checkpoint id is otherwise accepted with HTTP 200, the + ecosystem default silently substituted, and **billed** (measured on one + ecosystem: the correct id priced 160, while a nonexistent id, a + foreign-ecosystem id, and no model at all ALL priced 60 — the server's own + comment says this correction is visible on-site and invisible through a + non-browser path). And `Graph.Resources` entries **require** `model:{type}`, + which is not derivable from a version id — a bare id and `{id}` alone are + both 400s, while a *wrong* type is silently accepted. The type must come + from the lookup, never a guess. + +14. **Unset flags must be ABSENT from the payload, never Go zero values.** Every + optional field on `genapi.Graph` is a pointer or carries `omitempty`. This + reads as a missing-`omitempty` nit or gratuitous pointer-itis; it is a + correctness requirement, and the server is what makes it one. Measured: + `steps: 0` is **accepted**, and prices a degenerate, cheaper, WRONG job (the + steps cost factor drops to 0.333 from 1) — HTTP 200, billed. `cfgScale: 0` + goes the same way, and `quantity: 0` is clamped rather than rejected. So a + value-typed field silently converts *"the user did not pass `--steps`"* into + *"the user asked for a broken job"*, at half price, with no error anywhere. + The pointers also keep "unset" distinguishable from "explicitly zero", which + a `--print-input` → edit → `--input` round-trip depends on. The parsed + invocation carries `quantitySet` / `checkpointSet` / `maxCostSet` off + `cmd.Flags().Changed(...)` for the same reason. + 🔴 **The guard asserts KEY ABSENCE on a decoded `map[string]any`** — see + `TestGraph_UnsetFieldsAreAbsent` in `internal/genapi/generate_test.go`, which + marshals the real outgoing bytes and checks `_, ok := m["steps"]`. It is + explicitly **not** a `strings.Contains` search, and rewriting it as one would + make it vacuous in a way that reads fine: `"cfg"` substring-matches + `"cfgScale"`, so a text search cannot tell the two keys apart. The same test + also pins that a zero-valued `Graph` marshals to zero keys, so a newly added + value-typed field fails immediately rather than at the first user's expense. + +15. **`whatIf` and `generate` take DIFFERENT tRPC envelopes for the SAME graph, + and both shapes are pinned by tests.** The query takes the graph **flat** + (`{"json": }`); the mutation takes it **NESTED** under `.input` + (`{"json":{"input": , "externalId": …}}`), because the server + destructures the graph out of a wrapper on the mutation and not on the query. + The web mirrors the asymmetry deliberately. This looks like an obvious + duplication to collapse into one builder. Do not. + 🔴 **The mismatch is SILENT and returns HTTP 200 with a plausible wrong + cost.** Measured: a nested payload sent to whatIf is never parsed at all — + every nested body prices the server's default job (total 8) byte-identically + to `{}`, while the same graph sent flat priced 60. The discriminating control + was an ecosystem that 500s "Unknown ecosystem" when sent flat and returns a + clean `200 ready:true` when sent nested. So a builder wired to the wrong + nesting quotes a **constant** while every "did it 200?" assertion stays + green — and `--max-cost 50` would wave through an arbitrarily expensive job + while the confirmation prints "cost 8". That is the spend-safety feature + failing open, inside itself. A test that only checks the request succeeded + cannot see this; the tests assert the envelope SHAPE on the decoded body, on + both procedures. + Related, and easy to undo by accident: `whatIfGraph` strips + `prompt`/`negativePrompt` from the estimate (they do not affect cost, and the + server substitutes its own defaults), and it strips them from a RAW `--input` + graph by deleting the two keys from the decoded object — never by + re-marshalling through the typed struct, which would silently DELETE every + key the struct does not model. + +16. **`externalId` is minted unconditionally on every submit, and must never be + sent on a whatIf.** `generateInput.ExternalID` deliberately has **no** + `omitempty`, and `GenerateFromGraph` mints a UUIDv4 when the caller passes + none. This looks like a field that should be optional. It is the idempotency + key, and without it a single user action can be charged up to **three + times**: the platform's submit wrapper retries 3× on a 5xx *and* on a network + error / no response, reusing the same body, adds no idempotency key of its + own, and has no server-side minting fallback. The orchestrator dedupes on + `(userId, externalId)`. The web client is safe only because it always mints + one. + It is also what makes the CLI's own 401-refresh replay in + `genapi/client.go` safe to point at a mutation — the key is minted *before* + the body is marshalled, so a replay re-sends byte-identical bytes and gets + the pre-existing workflow back. **Do not add a mutation to that package that + omits it.** + 🔴 **Never send it on `whatIfFromGraph`.** A matching key returns the + pre-existing workflow, so a quote would BURN the key the subsequent submit + needs — which is why the server's own whatIf body omits it. And because a + duplicate key returns **HTTP 200 with the pre-existing workflow** rather than + a 409, re-attachment has to be inferred locally: that is why the key is + written to a local record *before* the POST goes out + (`internal/cmd/generate_state.go`) and why `--external-id` exists at all. It + overrides; it does not enable. + A `--input` file supplying its own `externalId` is REFUSED, not honoured — + see the envelope whitelist below. + +17. **`DownloadPresigned` exists so a blob fetch carries NO credential, and it is + the thing in this feature most likely to be "simplified" away.** It is a + near-duplicate of `DownloadFile` in `pkg/civitai/download.go` differing only + in that it passes an empty token, and every instinct says to fold it back in + behind a bool. 🔴 Doing that leaks a full-scope personal API key. + `isTrustedDownloadHost` attaches the bearer token to `civitai.com` and to + **any** `*.civitai.com` subdomain — correct for the model-download route it + was written for — and orchestrator output blobs are served from + `orchestration.civitai.com`, which **matches**. So `DownloadFile` would send + a 25-scope key (including `ModelsDelete` and `VaultWrite`) to the + orchestrator, on a request that is already authorized by its own signature + and needs no token whatsoever. + Weakening `isTrustedDownloadHost` is not the alternative: `civitai download` + depends on it attaching the token. The fix is a **seam that never has a + credential to attach** — `DownloadPresigned` passes `""` to `doDownload`, + whose guard is `token != "" && isTrustedDownloadHost(...)`, so the empty + token short-circuits before the host predicate is even consulted. That + ordering is deliberate: it cannot be defeated by a change to the predicate. + Everything genuinely shared is still shared — the SSRF dial guard, the + https-per-redirect-hop policy and 10-hop cap, the `ResponseHeaderTimeout` — + so there is no duplicated security logic to drift. It also skips the + 401-refresh replay on purpose: there is no credential to refresh, and a 401 + from a presigned URL means the signature is wrong or **expired**, which a + token would not fix. `internal/cmd/generate.go` wires + `deps.downloadBlob = reader.DownloadPresigned`; if you ever see that wired to + `DownloadFile`, it is a credential leak, not a cleanup. + +**When you change a validation rule, keep all four vendored mirrors in sync with +the server — `schema/`, the ported Go checks in `internal/validate/` (including +the slot registry), the Vite dotenv resolution behind the dev-tunnel parent-origin +check (item 10), and the block→host ready-ack in `internal/blockproto/` (item 11) +— and update `examples_test.go` (asserts shipped examples validate clean) + the +README. `internal/genapi` is deliberately NOT on that list: item 13 explains why +the generation path mirrors nothing.** ## Permission boundaries diff --git a/README.md b/README.md index b467e577..e12ae27c 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,10 @@ README. For the end-to-end walkthrough, see | `civitai app status [blockId] [--id ] [--json]` | Check the review/deploy status of **your own** submissions. No arg lists them all; a `blockId` (app slug) or `--id` shows one in detail (rejection reason if rejected, live URL once deployed). See [Submission status](#submission-status). | | `civitai app metrics [--from ] [--to ] [--json]` | **Owner-only analytics for one of your Apps** — installs, runs + Buzz spent, Buzz purchased, and API engagement. Always prints the window the **server** served (it defaults to 30 days and clamps to 366), so a zero is never ambiguous. Needs a **personal API key** (an OAuth login is refused). See [App metrics](#app-metrics). | | `civitai app withdraw [pubreq-id] [--id ]` | **Withdraw your own pending submission** (the `pubreq_…` id from `civitai app status`). Frees the slug so a fresh `civitai app submit` can replace it. Idempotent; only a `pending` request can be withdrawn. See [Submission status](#submission-status). | +| `civitai generate "" [--negative-prompt

] [--quantity ] [--aspect-ratio ] [--checkpoint ] [--lora [:strength]] [--input ] [--print-input] [--dry-run] [--json] [--max-cost ] [--yes] [--no-wait] [--timeout ] [--out-dir

] [--no-download] [--force] [--external-id ]` | **Generate images from a text prompt — this SPENDS REAL BUZZ.** Prices the job with the server's estimator, shows the cost + your balance, asks before spending, submits, then **waits and downloads** the results into `--out-dir` as `-.`. `--no-wait` prints the workflow id and exits; `--timeout` bounds the **wait** (never the job and never the charge); `--no-download` waits but prints URLs instead of writing files. `--dry-run` estimates and exits without submitting (`--dry-run --json` emits the raw estimate). `--print-input` prints the assembled graph and exits **without reaching any money seam** (no submit, no estimate, no balance read); `--input ` (or `-` for stdin) sends a raw graph as-is — txt2img only, and mutually exclusive with the content flags. Needs a **personal API key** with the AI Services scopes; an OAuth login is refused. `--max-cost` is an **estimate check, not a spending cap**. See [Generate](#generate). | +| `civitai workflows list [--limit ] [--cursor ] [--tag ] [--json]` | **List the generation workflows you have submitted**, newest first — status, when, cost, and `deliverable/total` outputs. Cursor-paged: the next cursor is printed on stdout when more results exist. Reading spends nothing. See [Generate](#listing-and-cancelling-workflows). | +| `civitai workflows get [--json]` | **Look up one generation workflow** — status, steps and outputs. This is how you re-attach after `--no-wait`, a `--timeout` expiry or a Ctrl-C. Outputs that are blocked, unavailable or hidden are listed **with the reason** rather than omitted. Output URLs are presigned and expire; re-run for fresh links. Reading spends nothing. See [Generate](#waiting-downloading-and-re-attaching). | +| `civitai workflows cancel [--json]` | **Stop a running generation.** 🔴 **This does not refund anything** — a mid-run cancel bills the accrued cost, non-refundably. Cancel because you no longer want the output, never to save money. See [Generate](#listing-and-cancelling-workflows). | | `civitai version` | Print version / commit / build date. | | `civitai completion [shell]` | Generate a shell-completion script. | @@ -335,13 +339,20 @@ blocked by CORS preflight and rejected by civitai's tRPC origin gate. The same-origin proxy + Origin rewrite fixes both. `VITE_LIVE_HOST_ORIGIN` overrides the proxy target (default `https://civitai.com`). -**Which credential can spend?** Only a full-scope **personal API key** can run a -real `dev:live` generation — the default OAuth login can't: +**Which credential can spend?** Only a full-scope **personal API key** can spend +Buzz — whether that is a real `dev:live` generation in your app or a +[`civitai generate`](#generate) run from the terminal. The default OAuth login +can't do either: -| Credential | Real `dev:live` generation? | How to get it | +| Credential | Can spend Buzz? (`dev:live`, `civitai generate`) | How to get it | |---|---|---| | **Personal API key** (full scope) | ✅ **Yes** — estimate → submit → generation → real Buzz | create it **in the web UI** at `civitai.com/user/account`, then `civitai login --token ` (a personal key carries AI Services) | -| **`civitai login`** (OAuth, default) | ❌ No — viewer + catalog + app storage only | the `civitai-cli` client has no AI Services scope, so the server strips the spend scope — fine for read/identity `dev:live`, not generation | +| **`civitai login`** (OAuth, default) | ❌ No — viewer + catalog + app storage only | the `civitai-cli` client has no AI Services scope, so the server strips the spend scope — fine for read/identity `dev:live`, not for generation | + +This is the single most common blocker for `civitai generate`: an OAuth login +looks perfectly valid, and the refusal is a scope problem, not a login problem — +re-running `civitai login` will not fix it. `civitai whoami` shows the capability +as **Spend Buzz (AI Services)**. You can't mint a personal key over OAuth or the CLI (`apiKey.add` returns 403 without a full-scope session) — create it in the web UI. The dev token always grants @@ -532,6 +543,11 @@ Two properties make the output safe to pipe: exits `4` with `Error: not found (404): Model not found` on stderr and an empty stdout. +Both properties hold for `civitai generate` and `civitai workflows …` too, but +their payloads are **not** Site API REST shapes — generation has no REST route, +so those commands pass through the raw *orchestrator* reply. Read +[Generation `--json`](#generation---json) before scripting against them. + ### Cursor pagination loop For deep paging use `--cursor` (**not** `--page` — the API caps `page*limit` at @@ -557,6 +573,35 @@ The CLI runs a background check for a newer release and prints a nag to `--no-update-check` (flag). Either way stdout stays pure JSON — the nag never touches stdout — but suppressing it keeps stderr clean for logs. +### Generation `--json` + +`civitai generate --dry-run --json`, `civitai workflows list --json` and +`civitai workflows get --json` emit the raw orchestrator payload. Two +caveats have bitten people, and neither shows up as an error: + +- **Output URLs are presigned and EXPIRE.** The links in a workflow payload are + short-lived signatures, not durable addresses. A pipeline that stores them and + fetches later gets a 401/403 from the storage host that no credential can fix + — re-run `civitai workflows get ` for fresh links instead of caching the + old ones. (Fetch them with **no** `Authorization` header; they are already + authorized, and the CLI deliberately attaches nothing to them.) +- **`--json` still exits `0` when the job is not generatable.** + `--dry-run --json` prints the estimate and exits `0` even when the payload + says `"ready": false`, which means the server has already decided it cannot + serve this job (an unavailable or unsupported resource). A human `--dry-run` + prints a warning and a real submit refuses outright, but a script reading only + the exit code sees success. **Branch on the field**, exactly as `app metrics` + requires branching on `notOwned`: + + ```bash + q=$(civitai generate "a cat" --checkpoint 128713 --dry-run --json) || exit $? + [ "$(echo "$q" | jq -r .ready)" = "true" ] || { echo "not generatable" >&2; exit 1; } + echo "$q" | jq -r .cost.total + ``` + + Cost keys (`cost.factors`, `cost.fixed`) are server-owned and passed through + **verbatim**, so treat them as an open map rather than a fixed set. + ### Gotchas - **SHA256 is UPPER-case** in the API/`--json` (e.g. @@ -854,6 +899,266 @@ outage from a real zero. A server old enough to predate this section omits the (naming the different cause), and a script should treat a missing `.views` the same way. +## Generate + +`civitai generate ""` runs a text-to-image generation on Civitai's +generator. + +> 🔴 **This spends real Buzz and cannot be undone.** A submitted generation is +> charged. There is no cancel-for-refund. Price it with `--dry-run` first — that +> calls the cost estimator and spends nothing. + +```bash +# Price it. Spends nothing. +civitai generate "a cat wearing sunglasses" --dry-run + +# The same estimate as raw JSON, for scripts +civitai generate "a cat wearing sunglasses" --dry-run --json + +# Generate, refusing if the estimate exceeds 50 Buzz +civitai generate "a cat wearing sunglasses" --quantity 4 --max-cost 50 + +# A specific checkpoint plus a LoRA at 0.8 strength +civitai generate "a cat" --checkpoint 128713 --lora 250712:0.8 + +# Wait for the result and write the images into ./out +civitai generate "a cat" --yes --out-dir ./out + +# Fire and forget; collect the results later +civitai generate "a cat" --yes --no-wait +civitai workflows list +civitai workflows get + +# Non-interactive (CI) — --yes is required, or the run is refused +civitai generate "a cat" --yes --max-cost 20 + +# Graduate from flags to a raw graph: print, edit, send back +civitai generate "a cat" --quantity 2 --print-input > graph.json +civitai generate --input graph.json --dry-run +``` + +**Credential.** Generation needs a full-scope **personal API key** carrying the +AI Services scopes ([create one](https://civitai.com/user/account), then +`civitai login --token `). An OAuth browser login (`civitai login`) does +**not** carry them and is refused. `civitai whoami` shows the capability as +**Spend Buzz (AI Services)**. + +### 🔴 `--max-cost` is an estimate check, not a spending cap + +The cost this command shows is an **estimate, not a quote**: the server's +estimator returns no quote id, no signed price and no expiry, so there is +nothing to hand back at submit time — and **no server-side spending ceiling is +reachable from an API key at all**. The realized charge can exceed the estimate +and is **not refunded**. + +`--max-cost` compares that estimate against your number and refuses **locally** +before submitting. It catches a `--quantity` typo. That is all it can do. Do not +run an unattended loop believing it caps spend. (The per-API-key `buzzLimit` on +your account does not bind this path either — the generator meters a separate +server-minted subject, not your key.) + +### Confirmation + +An interactive run prints the estimate, your balance and the resolved model +names, then asks. A **non-interactive shell (pipe/CI) without `--yes` is +refused** rather than charged silently. Everything the confirmation prints goes +to **stderr**, so `--json` keeps stdout machine-clean. + +### The five content flags, and why there aren't twelve + +`--negative-prompt`, `--quantity`, `--aspect-ratio`, `--checkpoint +`, `--lora [:strength]` (repeatable). + +The generator is **permissive, not a validator** — it returns HTTP 200 for +things it silently changes: + +- An out-of-range `--quantity` is **clamped** with no error (asking for 40 + charges you for the server's limit). The CLI warns when you cross it. +- `--steps 0` / `--cfg-scale 0` are *accepted* and price a degenerate, cheaper, + wrong job — which is exactly why those flags are **not** exposed yet. +- A checkpoint id that does not exist is accepted, the ecosystem default is + **silently substituted**, and you are billed for it. + +So `--checkpoint` and every `--lora` is resolved against the public +model-version API **before** anything is submitted: a bad id becomes a hard +local *not found* (exit 4) instead of a wrong charge, and the confirmation +echoes the resolved **model name** so you approve a name rather than an integer. +`--model` is deliberately absent: `civitai download --model` takes a *model* id, +while this takes a *version* id. + +### Raw graphs: `--print-input` and `--input` + +The five flags cover the common job. Everything else the generator understands +lives in the **generation graph** — the JSON document the flags assemble. You can +write that document yourself: + +```bash +# 1. Assemble it from flags, print it, and exit. No submit, no cost estimate, +# no balance read — with no --checkpoint/--lora, no request at all. +civitai generate "a cat" --quantity 2 --aspect-ratio 1:1 --print-input > graph.json + +# 2. Edit graph.json however you like. + +# 3. Send it as-is. Price it first; --dry-run still spends nothing. +civitai generate --input graph.json --dry-run +civitai generate --input graph.json --yes + +# …or pipe it, with `-` +jq '.prompt = "a dog"' graph.json | civitai generate --input - --dry-run +``` + +`--print-input` reaches **no money seam**: not the submit, not the cost +estimator, not the balance read. With `--checkpoint`/`--lora` it does still make +the public model-version *read* those flags always make — that lookup supplies +`model.type`, which graph `resources[]` require, so skipping it would print a +document `--input` could not submit. + +`--print-input`'s output is a valid `--input` document by construction — that +round-trip is the point of the pair, and it is what replaces a `--set +some.path=value` expression language the CLI deliberately does not have (a wrong +type in such an expression is accepted by the server silently, and billed; an +edited file is inspectable before it is sent). + +Four things to know, all of them consequences of it being a **passthrough**: + +- **txt2img only.** A graph declaring any other workflow is refused. The + server's content audit reads the top-level `prompt` node, and it rebuilds what + it inspects from *declared* graph nodes — so a graph carrying its prompt + somewhere else (a comfy node, a nested step input) is exactly the shape that + could reach the generator unaudited. That question is open upstream, and this + CLI will not be the path that answers it the wrong way. +- **Envelope keys are refused, not ignored.** `civitaiTip`, `creatorTip`, + `buzzType`, `tags`, `externalId`, `sourceMetadata`, `sourceMetadataMap`, + `remixOfId` and a top-level `input` belong to the request *envelope* around the + graph, not to the graph. A file setting `civitaiTip` would charge a tip that + **`--dry-run` structurally cannot show you** — the estimator prices a strictly + smaller request and is never sent tips at all — so the file is rejected with an + error rather than quietly cleaned up. +- **Keys the CLI does not model are passed through, with a warning.** The warning + says the CLI cannot *verify* the key; it is not a claim that the key is + invalid, because the CLI does not carry a copy of the server's node registry. + It matters because the server's failure mode for a key it does not declare is + to **drop it silently at HTTP 200** — a typo costs Buzz and produces a job that + ran without your parameter, with no error anywhere. +- **No model-id safety net.** `--checkpoint` / `--lora` are resolved against the + public API before submitting; a raw graph is not interpreted, so a nonexistent + id in it is accepted, the ecosystem default is substituted, and you are billed. + +`--input` cannot be combined with a prompt argument or with +`--negative-prompt` / `--quantity` / `--aspect-ratio` / `--checkpoint` / +`--lora` — there is no predictable answer to "does `--lora` append to or replace +the file's `resources`?", so the combination is a usage error. Every *execution* +flag (`--dry-run`, `--yes`, `--max-cost`, `--json`, `--no-wait`, `--timeout`, +`--out-dir`, `--no-download`, `--force`, `--external-id`) still applies. + +### Waiting, downloading, and re-attaching + +By default `generate` **waits** for the job to finish and writes every +deliverable output into `--out-dir` (default `.`) as +`-.`. `--force` overwrites existing files; without it a +collision is refused *before any bytes move*. + +- `--no-wait` submits, prints the workflow id and exits `0`. +- `--no-download` waits and prints the output URLs instead of writing files. +- `civitai workflows get ` shows a workflow at any time. It is the + re-attach path for every case where the CLI stopped early, and it spends + nothing. + +> 🔴 **`--timeout` stops *waiting*. It does not stop *paying*.** When the +> deadline passes (or you press Ctrl-C) the generation keeps running +> server-side and the charge stands — there is no cancel-for-refund, and a +> mid-run cancel bills the accrued cost anyway. Both cases exit **non-zero**, +> print the workflow id, the idempotency key and the exact `civitai workflows +> get …` command, and never report success. + +**Output URLs are presigned and expire.** Download promptly; re-read the +workflow for fresh links. The blob fetch deliberately carries **no credential** +— the URL is already authorized, and attaching your full-scope API key to it +would hand 25 unrelated permissions to a request that needs none. + +**A finished workflow can contain fewer usable results than you paid for.** An +output can be blocked by moderation, never land, or be one you hid on the +website. Those are filtered out of the download — and **reported, with the +reason**, plus an explicit note when the count differs from `--quantity`. +Silently writing three files for a four-image job is the failure this exists to +prevent. If *every* output is filtered out the command exits non-zero. + +**Crash safety.** The orchestrator's idempotency key is written to +`~/.config/civitai/pending/.json` **before** the request is sent, because +the money moves server-side even if the process dies mid-POST. If a submit's +reply never arrives, re-run with `--external-id `: the orchestrator dedupes +on it and returns the **pre-existing** workflow instead of charging again (it +answers a duplicate with HTTP 200, not a 409, so re-attachment is inferred +locally). + +**Polling cadence.** The status poll starts at 5s, backs off exponentially to a +cap, and backs off harder on a `429`. That floor is not tunable downward: the +workflow read proxies straight through to the orchestrator with no cache and no +server-side rate limit, so the CLI's own restraint is the only thing between it +and a 429 storm. + +### Listing and cancelling workflows + +```bash +civitai workflows list # newest first +civitai workflows list --limit 5 +civitai workflows list --limit 50 --cursor +civitai workflows list --json # raw server payload, incl. nextCursor +civitai workflows cancel +``` + +`list` is **cursor-paged**, not page-numbered: when more results exist it prints +`Next cursor: ` on **stdout**, which you pass back as `--cursor`. `--tag` +filters on orchestrator workflow tags (repeatable). + +The `OUTPUTS` column reads `deliverable/total`. The two differ when an output was +blocked by moderation, never landed, or you hid it on the website — so +`0/4` means four images were produced and paid for and none of them are usable, +which is a very different fact from `0/0`. `civitai workflows get ` shows +the per-output reason. + +> 🔴 **`cancel` does not refund anything.** A mid-run cancel **bills the accrued +> cost**, orchestrator-side and non-refundably. There is no cancel-for-refund on +> this platform: by the time a workflow is running the money has moved. Cancel a +> job because you no longer want its *output* — never as a way to save Buzz, and +> never to undo a submit. (This is also why `--timeout` and Ctrl-C deliberately +> do **not** cancel: stopping the wait costs nothing, while stopping the job +> would cost the same as letting it finish and throw the result away.) + +### Exit codes specific to `generate` + +`generate` follows the [global exit-code table](#exit-codes), with one +deliberate refinement. The API answers several very different failures with the +same HTTP status, and the generic mapping would send a script down the wrong +path — in particular a caller who is out of Buzz, muted, or hitting a +server-side outage must **never** be told to re-run `civitai login`. Those cases +therefore exit `1` (generic), not `3` (auth) or `2` (usage): + +🔴 **An exit code does not tell you whether you were charged.** Every failure +above the divider happens *before* anything is submitted, so nothing was spent. +Every failure below it happens *after* the submit, and **the Buzz is gone** — +including a `--timeout`, a Ctrl-C, and a workflow that ends `failed`. Do not +write a retry loop that branches on the exit code alone; re-attach with +`civitai workflows get ` instead of re-submitting. + +| Failure | Exit | +| --- | --- | +| *— nothing submitted, nothing spent —* | | +| Missing AI Services scope / no token / not authenticated | `3` | +| Not enough Buzz (caught locally against your balance, or reported by the server) | `1` | +| Account muted, or onboarding incomplete | `1` | +| Generation disabled server-side | `1` | +| Prompt refused by content moderation — 🔴 **never retry**, repeated blocked prompts get the account muted | `1` | +| The server priced the job but reports `ready: false` (a selected resource is not currently generatable) | `2` | +| Estimate above `--max-cost`, an unknown ecosystem, or a resource that resolved fine but is "not enabled for generation" (the ids exist; the *combination* is not runnable — distinct from exit `4`, which means "no such id") | `2` | +| `--input` that is malformed, declares a non-txt2img workflow, carries an envelope key (`civitaiTip`, …), or is combined with a content flag | `2` | +| No such `--checkpoint` / `--lora` version id | `4` | +| `civitai workflows get` / `workflows cancel` on an unknown workflow id (a read; spends nothing) | `4` | +| *— 🔴 submitted: the Buzz is already spent —* | | +| `--timeout` expired, or Ctrl-C while waiting — the job **keeps running** server-side and was **not** cancelled | `1` | +| The workflow finished `failed` / `expired` / `canceled` | `1` | +| The workflow succeeded but every output was filtered out (blocked / unavailable / hidden) | `1` | + ## Configuration | Setting | Config key | Env var | Default | @@ -877,7 +1182,7 @@ by this — only `echo $?` differs. | `0` | Success. | | `1` | Generic / unclassified error. | | `2` | Usage error — a bad flag, a bad flag value (e.g. `--limit` out of range, a non-integer id), or a request the API rejected as malformed (HTTP 400, e.g. a bad `--period`/`--sort` enum). | -| `3` | Authentication/authorization — login required, token invalid/expired, or the credential lacks the needed scope (HTTP 401/403, or no token configured). | +| `3` | Authentication/authorization — login required, token invalid/expired, or the credential lacks the needed scope (HTTP 401/403, or no token configured). **`civitai generate` refines this**: several of its failures are *not* credential problems but would otherwise land here or on `2`, so they exit `1` instead and a script never loops on `civitai login`. A **muted account or incomplete onboarding** arrives as a bare `403` that is byte-identical to a missing scope; **out of Buzz** and **generation disabled** arrive as `400` (the upstream 403 is re-thrown server-side as a tRPC `BAD_REQUEST`), which would otherwise read as "bad flags". See [Generate](#exit-codes-specific-to-generate). | | `4` | Not found — the requested resource does not exist (HTTP 404). | | `5` | Network/transport failure or service unavailable — dial/timeout, or HTTP 502/503/504 after retries. | | `6` | Rate limited — throttled by the API (HTTP 429). | diff --git a/claudedocs/civitai-generate-design.md b/claudedocs/civitai-generate-design.md new file mode 100644 index 00000000..011cbb5a --- /dev/null +++ b/claudedocs/civitai-generate-design.md @@ -0,0 +1,619 @@ +# `civitai generate` — feasibility + surface design (v2, post-review) + +Status: **feasible, but the v1 effort estimate in v1 of this doc was wrong.** Core +transport and auth are **verified live**; the *envelope*, the *idempotency*, and the +*spend-safety* story all failed adversarial review and are rewritten below. + +- 🧪 = measured against `https://civitai.com` (read-only `whatIfFromGraph` only; no + mutation was ever called). Probe harness validated with a positive control + (`buzz.getBuzzAccount` → 200 + real balance) and a negative control (bad token → 401). + Buzz balance was byte-identical before and after every probe — `whatIf` spends nothing. +- Everything else is code-path analysis against `/home/zach/workspace/civit/civitai` + @ working tree, 2026-08-05. + +**Reviewed by three independent adversarial passes** (correctness, CLI surface, spend +risk). Two independently discovered the envelope asymmetry (§2.1). Where they conflicted +(§6.2) the conflict was resolved by direct code reading, not by preferring a reviewer. + +--- + +## 1. Verdict + +**Yes — buildable. Transport verified. But it is not the "~none new plumbing" job v1 +claimed.** + +| | | +|---|---| +| **Transport** | `POST /api/trpc/orchestrator.generateFromGraph` | +| **Auth** | Personal API key with `AIServicesWrite` (bit 15) / `AIServicesRead` (bit 14) | +| **🧪 Verified** | A personal API key **does** authenticate tRPC orchestrator calls | +| **Blocker** | `civitai login` OAuth client lacks the AI bits — personal-key-only v1 | +| **Blockers found in review** | Envelope asymmetry (§2.1), missing idempotency (§2.2), broken `--lora` (§2.3) | +| **Honest spend framing** | **No server-side spend ceiling is reachable from a personal API key.** Every control the CLI can offer is client-side pre-flight (§4) | + +### 🧪 Verified live + +| Payload to `whatIfFromGraph` | Result | +|---|---| +| `{workflow:"txt2img", prompt:"a cat"}` | 200, cost 8 — `ecosystem` omittable (but see §5.3) | +| `+ ecosystem:"SDXL"` | 200, cost 4 | +| Full param set incl. `quantity:4` | 200, cost 12, adds `bulk discount: 0.93` | +| `model` + `resources[{id,model:{type},strength}]` | Parses + graph-validates; fails only at the resource-availability gate | + +--- + +## 2. The three blockers found in review + +### 2.1 🔴 CRITICAL — `whatIf` and `generate` take DIFFERENT envelopes, and the mismatch returns 200 with a bogus cost + +v1 of this doc claimed "Layer 2 is a convenience shell over the same builder, **not a +parallel path**." That is false at the tRPC envelope. + +- `generateFromGraph` destructures the graph **out of a wrapper**: + `const { input: formInput, civitaiTip, creatorTip, tags, …, externalId } = input` + (`orchestrator.router.ts:335-345`). +- `whatIfFromGraph` takes the graph **flat** (`:428`, `:473-474`). +- The web mirrors this deliberately: nested for submit (`FormFooter.tsx:1211-1224`), + flat for whatIf (`useWhatIfFromGraph.ts:137`). + +🧪 Measured, sending the **generate** envelope to whatIf: + +| payload | total | +|---|---| +| flat `{workflow, ecosystem:NanoBanana, prompt}` | **60** | +| nested `{input:{…same…}}` | **8** | +| nested `{input:{workflow:txt2vid, ecosystem:WanVideo22Ti2V5B}}` | **8** | +| flat `{workflow:txt2vid, ecosystem:WanVideo22Ti2V5B}` | **500 "Unknown ecosystem"** | +| `{}` (empty) | **8** | + +The discriminating control is rows 3–4: an ecosystem that **500s** flat returns a clean +`200 ready:true` nested. **The nested content is never parsed at all** — every nested +payload prices the default job, byte-identical to `{}`. + +**Consequence:** a CLI with one builder that dry-runs against whatIf gets `total=8` for +every job. `--max-cost 50` would wave through a 160-Buzz job while the confirmation prints +"cost 8". This is the exact silent-degradation class §5 exists to warn about, sitting +inside the spend-safety feature itself. + +**Required:** one builder emitting **two pinned envelope shapes**, plus a **positive-control +test** asserting the whatIf total *moves* when `quantity`/`priority` change. A builder +wired to the wrong nesting returns a plausible number, so every "did it 200?" assertion +stays green — a zero/constant result must be proven observable. + +### 2.2 🔴 CRITICAL — the server retries submits 3× with NO idempotency key + +`submitWorkflow` → `submitWorkflowWithRetry`, `maxAttempts = 3`, retrying on 5xx **and on +network error / no response** (`workflows.ts:308`, `:471`, `:494-500`). The wrapper's own +doc comment (`workflows.ts:463-466`): + +> *"It does NOT add an idempotency key. If the same workflow must not be duplicated when a +> 500 actually created it server-side, **the CALLER must set `body.externalId`** (the +> orchestrator dedupes on `(userId, externalId)`); the same body — and thus the same key — +> is reused across every retry here."* + +`:313-314` explicitly keeps the 3 retries on the generate path. There is **no server-side +minting fallback** (`externalId` appears 3× in `orchestration-new.service.ts`: type `:143`, +destructure `:1448`, body `:1567`). The web is safe only because its client always mints +one (`FormFooter.tsx:1130-1132`). This was already audited and fixed **for App Blocks +only** (`block-gen-idempotency.ts:184-193`, which states "up to 3 charges for one user +action" verbatim). + +**Required:** mint a UUIDv4 `externalId` on **every** submit, unconditionally. +`--external-id` only *overrides*. 🔴 **Never send it on a whatIf call** — a matching key +returns the pre-existing workflow, so a quote would burn the key (`:1616-1622` omits it for +exactly this reason). + +v1 of this doc treated `externalId` as a nice-to-have, and the surface review argued for +cutting it from v1. **Both were wrong.** + +**CLI-side retry, for completeness:** `authedDo` (`appblocks.go:322-340`) *would* re-send a +POST body on 401, but the branch is gated on a successful refresh, and a personal key +returns `ErrNoRefresh` (`auth/source.go:72-74`) — so it cannot fire in a personal-key-only +v1. + +✅ **CORRECTED in phase 0 — this hazard is closed NOW, not deferred to the OAuth +migration.** The unconditional `externalId` already neutralises it: `externalID` is minted +once *before* the body is marshalled and the retry closure captures the finished bytes +(`genapi/generate.go:202-217`), so a 401 replay re-sends a byte-identical body and the +orchestrator dedupes on `(userId, externalId)`. Pinned by an assertion that the replayed +submit's `externalId` equals the first attempt's. Do not "re-close" it later by disabling +the replay. `pkg/civitai/retry.go` is GET-only by +*convention, not enforcement* (`:18-24`); its predicates are method-agnostic and +`isTransientNetErr` returns true for a timeout *after* the server received the POST. Add a +guard test pinning that no mutation path reaches `getWithRetry`. + +### 2.3 🔴 HIGH — `--lora [:strength]` cannot work as specified + +v1 claimed "AIRs are computed server-side… a bare number even coerces to `{id}`". 🧪 That +is **true for the checkpoint node and false for `resources[]`**: + +``` +resources: [250712] 400 "expected object, received undefined" +resources: [{id:250712}] 400 same +resources: [{id:250712, model:{type:"LORA"}, strength:0.8}] 200 +model: 128713 / model: {id:128713} 200 (both) +``` + +v1 cited `common.ts:590-604` — that is `resourceSchema`, the node's **output** schema, which +*requires* `model:{type}`. The loose coercion is `resourceInputSchema` (`:616-619`), and the +loose input still has to satisfy the strict output (`:1200`). v1 generalised from the one +node where it holds to the one where it doesn't. + +**Consequence:** the CLI must know each resource's **model type**, which is not derivable +from a version id. That means a per-resource lookup against `/api/v1/model-versions/` — +real plumbing and per-resource latency, against a doc that budgeted "~none". + +Aggravating: 🧪 a **wrong** type is silently accepted (a LoRA id sent as +`{type:"Checkpoint"}` → 200, cost unchanged), while a **nonexistent** id 400s with +`AIR not found for resource ID …`. + +**Decision:** do the lookup (it doubles as §3's substitution mitigation) rather than +inventing a `--lora ::` spelling that pushes platform trivia onto users. + +--- + +## 3. The silent-degradation family + +The server is **permissive**. It is not a validator. Every item below returns HTTP 200. + +| Input | 🧪 Behaviour | +|---|---| +| `steps:0, cfgScale:0` | Accepted; `steps` factor 0.333 vs 1 — a **degenerate, cheaper, wrong** job | +| `sampler:"NotARealSampler"` | Silently ignored | +| **Unknown key** (`foobar:123`) | **Silently dropped** — `_validate` copies only declared node keys (`data-graph.ts:737-765`) | +| `quantity:10000` / `quantity:-5` | **Clamped** to 10 / 1 — no error | +| `steps:10000` | Clamped | +| `model.id` nonexistent | **200, billed, ecosystem default substituted** (§3.1) | +| `ecosystem:"SDXLL"` | **HTTP 500**, not 4xx (`ecosystems/index.ts:536` throws a bare `Error`) | + +Two corrections to v1: + +- v1 called the zero-value trap "the single most important implementation rule" but never + addressed the **unknown-key** trap, which is strictly worse because `--input` — the + design's headline strength — is the surface most exposed to it. v1's own flagship example + **`--set wan.shift=3` is a no-op that reports success**: `shift` is a real node + (`wan-graph.ts:300,362`) but it is **flat**, not namespaced. +- v1's §7 said "tier limit exceeded → validation error → pass through". **There is no error + to pass through.** A script asking for 10,000 images gets 10 and no signal. + +**Required:** echo the server's *effective* values back from the whatIf `factors`, and diff +what was sent against what was used. `--print-input` alone is insufficient. + +### 3.1 Silent model substitution — measured, and independently reproduced + +`common.ts:978-1000`, whose own comment says the correction is visible on-site and +**invisible** through non-browser paths. + +🧪 On `NanoBanana`: correct id `2436219` → **160**; an SDXL checkpoint id → **60**; a +**nonexistent** id → **60**; **no `model` at all** → **60**. The reviewer reproduced this +exactly, confirming substitution lands on the ecosystem default. `grep -c +modelSubstitutions orchestrator.router.ts` → **0**; it is surfaced only on the App-Blocks +path. + +**Mitigation (better than v1's three, and available today):** resolve `--checkpoint ` +and every `--lora ` against `/api/v1/model-versions/` — a route the CLI already +speaks — **before** submitting. Converts "nonexistent id → 200 + wrong bill" into a hard +local 404. It is a live lookup, not a vendored table, so it carries **no drift cost** and +does not violate the anti-mirror rule (§5). It doesn't catch same-ecosystem substitution, +but it closes the demonstrated case. Echo the **resolved model name** in the confirmation so +the user approves a name, not an integer. §2.3 requires this lookup anyway. + +**Raise upstream, additionally:** `orchestrator.router.ts:344-358` hardcodes the +substitution-context label `'onsite'`, whose comment says `'onsite'` specifically means the +*visible*, benign degradation and is deliberately excluded from the incidence number +gating a policy decision. CLI traffic recorded as `'onsite'` would inflate the benign +bucket with structurally invisible cases — corrupting the metric used to decide whether to +fix this class. Ask for a distinct label before v1. + +--- + +## 4. 🔴 The honest spend framing + +**There is no server-side spend ceiling reachable from a personal API key. The quote is not +binding and can be exceeded without refund. Every control the CLI can offer is client-side +pre-flight.** This must appear in `--help` and the README *in those words*, because the +failure mode is a user who believes otherwise running an unattended loop. + +Evidence: + +1. **The quote is not binding.** The whatIf response is `{allowMatureContent, transactions, + cost, ready}` — no quote id, nonce, signed price, or expiry. Nothing to hand back to + submit. `grep maxCost|costCeiling|maxBuzz|priceLimit|maxSpend` over the orchestrator wire + types → **zero hits**. +2. **Realized cost provably exceeds quotes, and nobody refunds it.** `blocks.router.ts:7293-7315` + computes `overage = ceil(realizedCost) - reserveBuzz` where `reserveBuzz = max(declaredPrice, + live whatIf quote)`. The correction is accounting only — `:7295-7297`: *"an accounting + correction for money already spent, **NOT a gate**: every `charge*` helper deliberately + has no deny path."* The bare `generateFromGraph` path has **no counter or reconciliation + at all**. +3. **whatIf prices a strictly smaller body.** Submit sends `{tags, steps, tips, experimental, + metadata, callbacks, nsfwLevel, allowMatureContent, currencies, externalId}` + (`orchestration-new.service.ts:1553-1570`); whatIf sends `{steps, experimental, currencies}` + (`:1615-1626`). `WorkflowCost.total` is documented as *"including tips"*, and the web adds + the tip arithmetic **client-side** (`FormFooter.tsx:155`). A CLI trusting the whatIf total + while passing any tip is wrong **by arithmetic**. +4. **The user's own per-API-key `buzzLimit` does not bind this path.** It exists + (`api-key.schema.ts:32-65`, surfaced at `/api/v1/me`), but `orchestratorMiddleware` calls + `getOrchestratorToken(user.id, ctx)` (`orchestrator.router.ts:102`), which mints a + **separate `type:'System'` ApiKey** (`get-orchestrator-token.ts:88-97`). The orchestrator + meters that subject, not the caller's key. **A user who sets `buzzLimit` believing they + capped exposure has not.** A safety feature that reads as engaged and is inert is worse + than one that visibly doesn't exist. Never present `--max-cost` and `buzzLimit` as + belt-and-braces; neither binds. +5. **Mid-run cancel still bills.** `blocks.router.ts:3305-3307`: *"a mid-run cancel BILLS the + accrued cost (orchestrator-side, non-refundable)."* `--timeout` must be documented as + "stop waiting", **never** "stop paying". Whether any graph *video* engine is time-metered + is **SUSPECTED**, not determinable from this repo. + +Bounded blast radius, the one piece of good news: 🧪 **quantity clamps server-side at 10.** + +**So `--max-cost` is an estimate check, not a cap.** Keep it — it catches the `-n 40` +typo — but label it honestly. + +**Also:** whitelist the generate envelope. `--input` keys populate the **graph**; only +CLI-owned keys populate envelope siblings. Never splat an input file into the top level, or +a committed `graph.json` carrying `civitaiTip: 5000` charges a tip that `--dry-run` +structurally cannot see. + +### 4.1 `--dry-run` green does NOT imply submit will succeed + +`generateFromGraph` (service) awaits `auditPromptServer` (`orchestration-new.service.ts:1460-1470`); +`whatIfFromGraph` **does not** — it injects `prompt:'cost-estimation'` as a default. So v1's +"whatIf is the *same* submitWorkflow call" is true of the orchestrator hop and **false of the +Civitai-side pipeline**. + +This matters more than it sounds: a blocked prompt increments a 30-day Redis counter, and at +**>8** creates a `UserRestriction`, sets `user.muted = true`, and every subsequent generate is +rejected by `isMuted` inside `guardedProcedure` (`promptAuditing.ts:334-479`; +`constants.ts:243-245`; `trpc.ts:479`). **A scripted retry loop on a flagged prompt can get the +user auto-muted.** That error must never be retried, and needs its own §7 row. + +Related: the web deliberately **strips** `prompt`/`negativePrompt` from whatIf — +*"they don't affect cost and shouldn't be sent to the server until actual submission"* +(`useWhatIfFromGraph.ts:118-124`). Match that; it's cheap and it stops shipping user prompts +on every estimate. + +--- + +## 5. Why the CLI still stays thin — and where that thesis broke + +The graph applies defaults server-side (`data-graph.ts:1932`) with a second fallback layer in +the handlers (`stable-diffusion.handler.ts:194-196`: `sampler ?? 'Euler'`, `steps ?? 25`, +`cfgScale ?? 7`). Width/height derive from `aspectRatio`. Adding `images` auto-promotes +txt2img → img2img:edit (`orchestration-new.service.ts:490`). + +**The thin thesis survives for the *fields*, and fails at the *envelope*** (§2.1) — which v1 +never examined. + +### Anti-mirror discipline (unchanged, and endorsed by review) + +AGENTS.md tracks three vendored mirrors and item 8 deliberately declined a fourth. Do **not** +vendor: ecosystem keys, the 51 per-engine graphs, sampler enums, resolution buckets, +per-ecosystem defaults, tier limits, or any cost table. Validate nothing locally the server +validates; echo what the server *used*. + +**One bounded exception:** a **warn-only** sampler check (§3) catches a money-spending typo +and *fails soft* — warn, then send anyway — so a stale list can never block a valid new +sampler. Label it a mirror; never promote it to validation. + +**Live lookups are not mirrors.** The `/api/v1/model-versions/` resolution in §2.3/§3.1 +is a server round-trip, so it carries no drift cost. This distinction is what makes it the +right fix. + +### 5.3 ⚠️ Reopened: `ecosystem` is omittable, but its default is NOT a stable fact + +v1 closed this on one measurement. `ecosystem-graph.ts:231-244`: `ZImageTurbo` is only the +`outputDefault`; the real default is +`usableEcosystems.includes(outputDefault) ? outputDefault : usableEcosystems[0] ?? … ?? 'SDXL'`, +where `usableEcosystems` **excludes disabled and memberOnly** entries. So Layer 1 can resolve +to a different model, at a different price, for a free-tier user vs. this author's account, +or after a server-side gating change. **Measured on one account only.** The CLI must print +which ecosystem/model the server actually used. + +--- + +## 6. Proposed surface (revised) + +### Command shape — decided in v1, not deferred + +`civitai generate ""`, bare and top-level. **Do not** make it a runnable parent that +later grows subcommands: `root.go:364` installs the unknown-subcommand guard only for +`HasSubCommands() && !Runnable()`, and `Args` is non-nil everywhere (`:351-358`), disabling +cobra's `legacyArgs` fallback. So `civitai generate lst` would resolve to `generate` with +`"lst"` as the **prompt** — and charge for it. Deferred verbs go to **`civitai workflows +list|get|cancel`**, which is honest naming (they are orchestrator workflows). + +**Pull `workflows get ` into v1.** It's a small tRPC GET, and without it `--no-wait` and +the Ctrl-C recovery path (§6.3) print a workflowId the CLI cannot query — a dead end. + +### Layer 1 — simple + +```bash +civitai generate "a cat wearing sunglasses" +``` + +### Layer 2 — five flags, not twelve + +`--negative-prompt`, `--quantity`, `--aspect-ratio`, `--checkpoint `, +`--lora [:strength]` (repeatable). + +Rationale for the cut: every layer-2 flag is a validation-free money-spending surface that +`--input` already covers, and §3 proves the server rejects nothing. **Defer** +`--steps`/`--cfg-scale`/`--sampler` to v2 (they are exactly the silently-degrading ones); if +they must ship, reject `0` locally as a usage error. **Cut** `--clip-skip`, `--priority` +(a 🧪 3.5× price lever: 8 → 28), `--output-format`. + +Naming corrections, all forced by existing collisions in the same binary: + +| v1 | v2 | Why | +|---|---|---| +| `--model` | `--checkpoint` | 🔴 `download.go:127` `--model` = a **MODEL** id; this is a **VERSION** id. `download.go` has ~90 lines of machinery to disambiguate exactly this | +| `--out ./dir/` | `--out-dir` | `--out` is a single **file path** in both existing uses (`download.go:132`, `app_submit.go:145`) | +| `--cfg`, `--aspect`, `--negative`, `--format` | `--cfg-scale`, `--aspect-ratio`, `--negative-prompt`, `--output-format` | House rule is kebab-case of the API key (`--model-version-id`, `--base-model`) | +| `-n` | `--quantity`, no shorthand | `-n` conventionally means *dry run/no*; adjacent to a `[y/N]` money prompt | + +🔴 **Unset flags must be ABSENT from the JSON**, never Go zero values — 🧪 measured (§3). +Pin with a test asserting **key absence** in the marshalled payload (`map[string]any`, +`_, ok := m["steps"]`), not `strings.Contains` — `"cfg"` substring-matches `"cfgScale"`. +Show the guard red against a naive non-pointer struct before counting it. + +**Add:** `--prompt-file ` (shell-quoting long prompts is miserable), and a +wait-but-don't-download mode (`--no-download`, or state that `--json` implies it). + +### Layer 3 — `--input` + +```bash +civitai generate --input graph.json # or --input - +civitai generate "a cat" --print-input # dump assembled JSON, exit +``` + +Still the core move: all 51 ecosystem graphs, zero CLI code per engine. + +**Cut `--set` from v1.** It needs path parsing, array indexing, and type inference — and §3 +proves a wrong type is accepted silently and billed. `--print-input > g.json` → edit → +`--input g.json` covers it with no new parsing surface. + +**Make `--input` mutually exclusive with layer-2 flags in v1** and return a usage error. +`validateDownloadFlags` (`download.go:253-277`) rejects six flag combinations rather than +defining subtle merges; that's the house answer and it's testable in one function. It also +sidesteps the unanswered "does `--lora` append to or replace `--input`'s `resources`?". + +🔴 **Do not ship `--input` beyond txt2img until the audit question is closed** (§7). + +### 6.2 Blob download — reuse the machinery, decide the token deliberately + +**Do not write a new downloader.** `internal/genapi/blobs.go` would discard: the SSRF dial +guard (`download.go:106-130,144-151`), https-per-redirect-hop with a 10-hop cap (`:77-104`), +cross-host `Authorization` stripping (`:226,242-269`), `filepath.Base` + degenerate-name +rejection (`internal/cmd/download.go:674-690`), collision detection (`:657`), and +`.part` + atomic rename (`:706+`). + +The SSRF guard would **not** block presigned blob URLs — `isBlockedDownloadIP` blocks only +non-public IPs; public signed-storage hosts pass. + +🔴 **But `isTrustedDownloadHost` (`download.go:254-269`) attaches the bearer token to +`civitai.com` and *any* `.civitai.com` subdomain.** Orchestrator blobs appear to be served +from `orchestration.civitai.com`, which matches — so naively reusing `DownloadFile` sends a +**full-scope personal API key** (25 scopes incl. `ModelsDelete`, `VaultWrite`) to the +orchestrator on every blob fetch, for a URL that is already presigned and needs no token. +*(The two reviewers disagreed here; resolved by reading the code. The predicate is verified; +the actual blob host is inferred — no real blob URL was observed, since that requires a paid +generation. Verify before shipping.)* + +**Decision:** reuse the downloader, pass the blob fetch through a path that does **not** +attach the token. + +**Also handle output state.** A `succeeded` workflow can contain moderation-blocked or +not-yet-available outputs. Without filtering, `generate` reports success and silently +writes fewer files than `--quantity` asked for. Name files `-.`; add +`--force` for collisions. + +⚠️ **CORRECTED in phase 2 — the shape above is the WRONG one for the endpoint §6.3 +mandates.** `{available, blockedReason, hidden}` as *blob* fields +(`orchestration-new.service.ts:2142-2149`, `workflow-data.ts:222`) belong to the +**normalized** path (`statusUpdate` / `queryGeneratedImages`). But `orchestrator.getWorkflow` +returns the **RAW orchestrator workflow** — the router hands `getWorkflow`'s result straight +back with no `formatGenerationResponse2` step (`orchestrator.router.ts:203-207`). On the raw +shape: + +- `hidden` is **not** a blob field — it is `step.metadata.output[].hidden`, with a + **legacy `step.metadata.images[]` fallback**. A reader built to the normalized + shape misses it entirely and reports every deleted output as visible. +- `seed` is `step.metadata.params.seed + index`, not a blob field. `width`/`height` *are* on + the blob. +- Outputs live in **three different containers** keyed by step `$type`: `output.images` + (textToImage/imageGen), `output.blobs` (comfy), `output.blob` (upscaler/preprocess). + Reading only one silently yields zero outputs for the others. +- There is **no `pending` status**. The enum is + `unassigned|preparing|scheduled|processing|succeeded|failed|expired|canceled`; treat an + unrecognised value as "keep waiting". + +⚠️ **And `queryGeneratedImages` (used by `workflows list`) returns the NORMALIZED shape** — +i.e. a *different* shape again from `getWorkflow`. This doc previously treated "a workflow" +as one type. Reusing one struct for both reads fabricated zeros. They need separate types. + +⚠️ **`cancelWorkflow` returns `undefined`** — its success reply has no `result.data.json` at +all (`workflows.ts:532-539`), so routing it through the standard tRPC unwrap turns *every +successful cancel* into "unexpected response". HTTP 200 is the success signal. + +### 6.3 Polling — v1's justification was wrong + +v1 argued 3–5 s from a "3 s server-side feed cache". That cache is +`QUERIED_WORKFLOWS_CACHE_TTL`, which belongs to `queryGeneratedImages`, and the comment above +it says the opposite: *"Live generation progress does NOT flow through this route… +`orchestrator.statusUpdate` (a separate per-workflow endpoint)"* (`:2668-2670`). +`getWorkflowStatusUpdate` is `getWorkflow(...)` plus a projection (`:2854-2861`) — **no cache, +no cursor, no delta.** + +So the cited protection does not exist on the endpoint being polled, and v1 argued 12–20× the +web's 60 s fallback against a straight passthrough to the orchestrator. + +**Required:** exponential backoff, a floor no faster than ~5 s, and explicit **429 handling** +(an orchestrator 429 → `throwRateLimitError`, `workflows.ts:390`, whose comment mentions "a +429 storm"). No tRPC-level rate limit is attached to any orchestrator procedure, so nothing +stops the CLI from *being* the storm. + +Two more: `statusUpdate` returns no workflow `metadata` (where substitution data would live), +and it is `orchestratorGuardedProcedure` while `getWorkflow` is `orchestratorProcedure` +(`:593` vs `:203`) — **a muted user cannot poll a workflow they already paid for** via +`statusUpdate`. Prefer `getWorkflow` for the poll. + +### 6.4 Interrupt safety + +No global signal handling exists (`signal.NotifyContext` appears only in `download.go:163` +and `app_dev_tunnel.go`). This repo already learned this on a non-money path: +`SubmitVersion` (`appblocks.go:389-432`) has bespoke timeout recovery because "the upload can +complete server-side while its HTTP response is slow or never arrives." + +**Required:** `signal.NotifyContext`; write `{externalId, submittedAt, payloadHash}` to a +local state file **before** the POST; on interrupt/timeout print the externalId and the exact +re-attach command. A duplicate `externalId` returns **200 with the pre-existing workflow** +(there is no 409), so re-attach must be inferred locally. + +--- + +## 7. Error paths — with kinds, not just messages + +v1 specified §7 entirely in message text — the exact failure AGENTS.md item 7 documents. +🔴 **`errkind.go:72-74` maps both 401 AND 403 to `ErrUnauthorized` → exit 3**, documented as +"login required / credential lacks scope". + +⚠️ **CORRECTED during phase 1 — the v2 table below was wrong on two rows.** Insufficient +Buzz does **not** reach the CLI as a 403: the orchestrator's 403 is caught and re-thrown by +`throwInsufficientFundsError` as tRPC `BAD_REQUEST` (`workflows.ts:385` → +`errorHandling.ts:218`), so it arrives as a **400**. "Generation disabled" is likewise +`BAD_REQUEST` → **400** (`orchestrator.router.ts:379-390`). tRPC derives the HTTP status +from the TRPCError *code*, so no upstream 403 survives to the wire on those paths. The +genuine 403 misclassification victims are a **muted account** (`trpc.ts:392-396`) and +**incomplete onboarding** (`trpc.ts:423-435`) — both bare `FORBIDDEN`, byte-identical to a +missing scope. **Verified by reading the server source, not inferred.** + +🔴 **Constraint discovered in phase 1: do NOT "fix" this by changing `statusKind`** — it is +shared by every command, so a new 403 mapping would silently alter exit codes CLI-wide. +Discriminate at the genapi/cmd layer instead, on the server's `message`, and **fail soft** +(an unrecognised message keeps its status-derived kind, so a server-side rewording degrades +to today's behaviour rather than to a wrong one). + +| Cause | Server | Kind / exit | Note | +|---|---|---|---| +| OAuth token / missing scope | `FORBIDDEN` (`enforce-token-scope.ts:84`) | `ErrUnauthorized` (3) ✅ | name the **AI Services** preset | +| Insufficient Buzz | ⚠️ **400**, not 403 | `ErrInsufficientBuzz` (1) — matched **status-agnostically** | show cost vs balance | +| Generation globally disabled | ⚠️ **400**, not 403 | `ErrGenerationDisabled` (1) | not the user's fault; a custom server message falls through to the 400 default | +| **Muted / onboarding incomplete** | **403** — the real victims | `ErrAccountRestricted` (1) | `civitai login` will NOT help | +| Onboarding incomplete / **muted** | bare `FORBIDDEN` (`trpc.ts:423-435`, `:479`) | distinct | reads identical to a scope error | +| Prompt blocked | audit throw | distinct, **never retry** | retry loops can auto-mute (§4.1) | +| Unknown ecosystem | **500** (`ecosystems/index.ts:536`) | 🔴 map to usage (2) | a bare `Error`; a user typo would otherwise log at **error** severity to the platform's Axiom with the full payload (`orchestrator.router.ts:485-510`) | +| Resource not generatable | 400 with names | `ErrNotFound` (4)? | route names through `safeTerm` | +| Tier limit | **none — silently clamps** | n/a | echo effective values (§3) | + +Every row needs an `errors.Is` test. `README.md:809-817` changes in the same PR. + +--- + +## 8. Implementation notes the design must not omit + +- **`safeTerm` everywhere.** Server strings carry user-generated model names and prompts. + `serverError` (`appblocks.go:1220-1233`) interpolates server text *without* it today. +- **Stream discipline.** `--json` → stdout; **all** confirmation, progress, warnings → stderr + (`download.go:214`, `images.go:66,114`). CONVENTION.md: "Machine-readable output stays raw." +- **`internal/ui`** for warnings; split TTY/non-TTY rendering as CONVENTION.md mandates + (`waitTunnelQuiet` / `waitTunnelTTY`). +- **A `generateDeps` struct** of func fields — `whatIf`, `submit`, `pollStatus`, + `downloadBlob`, `buzzBalance`, `resolveVersion` — injected like `app_metrics.go:35-38,87-90`. + Without it the confirm/poll/download branches are untestable. +- **A poll-interval seam** (`app_dev_tunnel.go:760-765` is the precedent) so tests don't sleep. +- **TTY confirm needs no new seam** — `stdinIsTTY` is already an injectable package var + (`app_init.go:245-248`), forced off in `TestMain`, with `withStdinTTY` helpers. +- **Confirmation shape**: copy `confirmSubmit` (`app_submit.go:161-184`) — `--yes`/`-y`, + non-TTY without `--yes` refuses. Generate has a *stronger* case than the precedent: + `app submit` gates a reversible action and still prompts. +- **Cost display**: one line at the prompt (`Cost: 12 Buzz (balance 4,188,809) — 4 images? + [y/N]`); full `base/factors/fixed/tips/total` under `--dry-run`, plus **`--dry-run --json`** + (v1 omitted it; it's the most script-relevant output the command has). Print factor keys + **verbatim** — inventing labels is AGENTS.md item 8 again. +- **Balance check before submit** — the CLI has cost and balance in hand. +- **`whoami` already has the row.** `whoami.go:81` prints `Spend Buzz (AI Services)` off + `ScopeAIServicesWrite` — the very bit generate needs. Don't add a second row; **reword** its + `dev:live`-specific help text (`:91-93`), which becomes wrong once `generate` exists. + +### Package layout + +`internal/genapi/{generate,status}.go` + `internal/cmd/generate.go`. **Not** `pkg/civitai` +(that's the public read/download SDK — rationale at `pkg/civitai/api.go:15`). Blob download +reuses `pkg/civitai`'s downloader (§6.2) rather than a new `blobs.go`. + +### Docs burden + +`README.md` command table (`:203-218`) + a new `## Generate` section; exit codes +(`:809-817`); the credential table (`:291-294`); `## Scripting with --json` (`:465`) for the +URL-expiry and `ready:false` caveats. `root.go:182` says "It does **two** things from one +static binary" — generation makes it three. AGENTS.md needs **three** new +"intentional decisions" items (tRPC-not-REST; the CLI validates nothing on purpose; the +unset-key rule + substitution hazard), plus `genapi` in the Layout list — and its closing +paragraph already says "both vendored mirrors" while items 2 and 10 track three. + +--- + +## 9. Phasing + +1. **v1** — txt2img. Two pinned envelopes, mandatory `externalId`, version-id resolution, + 5 flags, `--input` (txt2img only), `--dry-run` + confirmation, poll with backoff + 429, + download with output-state filtering, `workflows get`. Personal-key only. +2. **v2** — img2img (`--image` → presigned upload → `images[]`); `--steps`/`--cfg-scale`/ + `--sampler` + warn-only sampler list. +3. **v3** — `workflows list|cancel`; OAuth scope migration (🔴 which **arms** the `authedDo` + POST-retry hazard in §2.2 — close it first). + +--- + +## 10. Open questions + +1. ✅ **CLOSED** — a personal API key authenticates tRPC `orchestrator.*`. Verified live. +2. ⚠️ **REOPENED** — `ecosystem` is omittable, but its default is tier- and + server-state-dependent (§5.3). Measured on one account. +3. 🔴 **OPEN** — will the server surface `modelSubstitutions` on the tRPC reply, and give CLI + traffic a label distinct from `'onsite'` (§3.1)? +4. 🔴 **OPEN, blocks `--input` beyond txt2img** — the prompt audit is gated on + `'prompt' in data && typeof data.prompt === 'string'` (`orchestration-new.service.ts:1452`), + and `data` is rebuilt from **declared nodes only**. A graph carrying its prompt in a + non-`prompt` node (comfy, nested step input) is exactly the shape that would slip the audit. + **SUSPECTED**; neither review resolved it. +5. **SUSPECTED** — are any graph *video* engines time-metered? Determines whether `--timeout` + has a money meaning (§4). +6. Platform bug worth filing, no CLI impact: the POI throw at `:1007-1012` tests + `'disablePoi' in data`, but `disablePoi` is not a declared graph node anywhere — so the + branch is unreachable **for every caller including the browser**. Backstopped by the audit's + `inappropriate_poi` trigger and post-generation scanning. + +--- + +## Appendix — v1 claims this revision retracts + +| v1 claim | Status | +|---|---| +| "Layer 2 is a convenience shell over the same builder, not a parallel path" | ❌ **False** — two envelopes (§2.1) | +| "New plumbing needed: ~none" | ❌ **False** — two envelopes, idempotency, version resolution | +| "a bare number even coerces to `{id}`" | ❌ **False for `resources[]`** (§2.3) | +| "3 s server-side feed cache… 3–5 s is appropriate" | ❌ **Misattributed cache** (§6.3) | +| "`--set wan.shift=3`" | ❌ **A no-op that reports success** (§3) | +| "Tier limit exceeded → validation error → pass through" | ❌ **Silently clamps** (§3) | +| `--max-cost` presented as a guard | ❌ **Advisory only** (§4) | +| "`ecosystem` defaults to ZImageTurbo" (stated as fixed) | ⚠️ **Tier-dependent** (§5.3) | +| `externalId` as a nice-to-have `--external-id` flag | ❌ **Mandatory + unconditional** (§2.2) | +| Add a "Generate" row to `whoami` | ❌ **Already exists** (`whoami.go:81`) | +| `analytics.go:240-245`, `stable-diffusion.handler.ts:186-210`, `token-scope.ts` path | ⚠️ Citations off by a few lines / file moved to `packages/civitai-auth/` | +| §7: insufficient Buzz / generation-disabled arrive as **403** | ❌ **Both are 400** — the orchestrator 403 is re-thrown as tRPC `BAD_REQUEST`. The real 403 victims are muted + onboarding (§7) | +| §2.2: the `authedDo` POST-replay hazard is armed by the OAuth migration | ❌ **Closed now** by the unconditional `externalId` (§2.2) | +| §6.2: outputs carry `{available, blockedReason, hidden}` as blob fields | ❌ **That is the NORMALIZED shape**; `getWorkflow` returns the RAW one (§6.2) | +| Treating "a workflow" as one shape across endpoints | ❌ `getWorkflow` is raw, `queryGeneratedImages` is normalized — two types (§6.2) | +| §4: "whitelist the generate envelope" (siblings unenumerated) | ⚠️ There are **9** envelope siblings, not the 5 named: + `sourceMetadata`, `sourceMetadataMap`, `remixOfId`, and a top-level `input` | +| §9: `workflows list\|cancel` belong in v3 with the OAuth migration | ⚠️ No OAuth dependency; they shipped in phase 3 | +| §6.4: "print the exact re-attach command" | ⚠️ Unsatisfiable if the submit reply is lost — needs `--external-id` to be executable | + +### Verified live at the phase-2 gate (first real generation) + +One SDXL-default txt2img, quantity 1, workflow `8753561-20260805192923707`: +**estimated 8 Buzz, charged exactly 8 Buzz** (blue 1,339,760 → 1,339,752), 1024×1024 JPEG +downloaded with **no credential attached**, `workflows get` re-attach confirmed. The submit +response shape (previously `⚠️ UNVERIFIED`) is now verified. One data point — it does **not** +disprove §4's finding that realized cost *can* exceed the quote without refund. diff --git a/go.mod b/go.mod index 08fd2d7b..554639cf 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,7 @@ require ( github.com/muesli/termenv v0.16.0 github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 github.com/spf13/cobra v1.8.1 + github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.19.0 golang.org/x/crypto v0.54.0 golang.org/x/net v0.57.0 @@ -55,7 +56,6 @@ require ( github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect github.com/spf13/cast v1.6.0 // indirect - github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect go.uber.org/atomic v1.9.0 // indirect diff --git a/internal/cmd/generate.go b/internal/cmd/generate.go new file mode 100644 index 00000000..66c91d0a --- /dev/null +++ b/internal/cmd/generate.go @@ -0,0 +1,1226 @@ +package cmd + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/signal" + "sort" + "strconv" + "strings" + "text/tabwriter" + "time" + + "github.com/civitai/cli/internal/appapi" + "github.com/civitai/cli/internal/auth" + "github.com/civitai/cli/internal/config" + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" + "github.com/civitai/cli/pkg/civitai" + "github.com/spf13/cobra" +) + +// generateWorkflow is the only generation mode this release builds. img2img and +// arbitrary graphs come later; pinning it here keeps the graph honest about what +// the five flags can actually express. +const generateWorkflow = "txt2img" + +// serverQuantityClamp is the server's CURRENT upper bound on --quantity. It is +// used for a WARNING ONLY and must never gate the request: the server silently +// clamps out-of-range values (measured: 10000 -> 10, -5 -> 1) with no error, so +// a user who asks for 40 images pays for 10 and gets no signal at all. Warning +// fails soft — if the platform raises the bound, a stale number here produces a +// needless note, never a blocked valid request. Do not promote it to validation +// (this repo's anti-mirror rule). +const serverQuantityClamp = 10 + +// Classification sentinels for generation failures that the HTTP-status mapping +// alone gets wrong. They carry NO user-visible text: they are ATTACHED via +// civitai.Tag so errors.Is reports the KIND while the printed message is +// whatever classifyGenerateError composed. +// +// 🔴 Why they exist: civitai.TagStatus maps BOTH 401 and 403 to +// civitai.ErrUnauthorized -> exit 3, documented as "login required / credential +// lacks scope". A muted account and an incomplete onboarding both arrive as a +// bare 403, so without this a restricted user is told to re-run `civitai login` +// — forever. Changing statusKind was not an option: it would silently move the +// exit code of every other command. +// +// None of these is mapped in cmd/civitai's exitCode, so they all land on the +// GENERIC exit 1 — deliberately distinct from 3 (auth) and 2 (usage), neither of +// which describes them. They are still errors.Is-assertable, which is what pins +// the contract. +var ( + // ErrInsufficientBuzz marks a refusal for lack of spendable Buzz — whether + // caught locally against the balance or reported by the server. + ErrInsufficientBuzz = errors.New("insufficient Buzz") + // ErrGenerationDisabled marks generation being switched off server-side (or + // restricted to members). Not the caller's fault and not fixable by them. + ErrGenerationDisabled = errors.New("generation disabled") + // ErrAccountRestricted marks a muted account or an incomplete onboarding — + // the two failures that read byte-identical to a missing scope. + ErrAccountRestricted = errors.New("account restricted") + // ErrPromptBlocked marks a prompt the content audit refused. 🔴 A caller must + // NEVER retry this: repeated blocked prompts increment a 30-day counter that + // auto-mutes the account. + ErrPromptBlocked = errors.New("prompt blocked") +) + +// generateDeps are the network seams `generate` needs. Bundled as func fields so +// every branch — confirmation, cost ceiling, each error row — is exercisable +// without a live server, and so a test can PROVE the submit seam was not called. +type generateDeps struct { + // whatIf estimates the cost. It spends nothing. + whatIf func(ctx context.Context, g genapi.Graph) (*genapi.WhatIfResult, json.RawMessage, error) + // submit SPENDS BUZZ. 🔴 A test must never point this at a real server. + submit func(ctx context.Context, g genapi.Graph, opts genapi.SubmitOptions) (*genapi.SubmitResult, string, json.RawMessage, error) + // resolveVersion turns a model-version id into its model TYPE + display name. + resolveVersion func(ctx context.Context, id int) (*genapi.ResolvedVersion, error) + // buzzBalance reads the spendable balance for the cost-vs-balance check. + buzzBalance func(ctx context.Context) (int64, error) + // getWorkflow reads a workflow back. It is the POLL seam, and it spends + // nothing. + getWorkflow getWorkflowFn + // downloadBlob fetches one presigned output URL WITHOUT a credential (see + // blobFetcher). + downloadBlob blobFetcher + // pendingDir is where the pre-submit crash-recovery record is written. A + // test points it at a t.TempDir(); empty means the real config dir. + pendingDir string + // poll carries the poll cadence + the injected clock/sleep. Zero values fall + // back to the documented defaults (see pollConfig.resolved). + poll pollConfig +} + +// generateOpts is the parsed invocation. The *Set fields record whether a flag +// was given at all: an unset flag must be ABSENT from the outgoing JSON, never a +// Go zero value, because the server accepts `quantity: 0` and silently clamps it +// rather than rejecting it. +type generateOpts struct { + prompt string + negativePrompt string + quantity int + quantitySet bool + aspectRatio string + checkpoint int + checkpointSet bool + loras []string + dryRun bool + jsonOut bool + assumeYes bool + maxCost int + maxCostSet bool + baseURL string + + // noWait prints the workflow id and exits instead of waiting. + noWait bool + // timeout bounds the WAIT, never the job and never the charge. + timeout time.Duration + // outDir is the directory outputs are written into. + outDir string + // noDownload waits for the result but writes no files. + noDownload bool + // force overwrites existing output files. + force bool + // externalID overrides the minted idempotency key, which is how a lost + // submit is re-attached rather than re-charged. + externalID string + + // inputPath is the `--input` graph file ("-" reads stdin). When set, the + // graph is a raw passthrough and every content flag above is REFUSED. + inputPath string + // printInput dumps the assembled graph and exits without submitting. + printInput bool +} + +func newGenerateCmd() *cobra.Command { + var o generateOpts + + cmd := &cobra.Command{ + Use: "generate [prompt]", + Short: "Generate images from a text prompt (SPENDS BUZZ)", + Long: `Generate images from a text prompt on Civitai's generator. + +🔴 THIS SPENDS REAL BUZZ AND CANNOT BE UNDONE. A submitted generation is charged; +there is no cancel-for-refund and no "undo". Preview the price with --dry-run +first — it calls the server's cost estimator and spends nothing. + +CREDENTIAL: generation needs a full-scope PERSONAL API KEY with the AI Services +scopes (create one at https://civitai.com/user/account, then +` + "`civitai login --token `" + `). An OAuth browser login (` + "`civitai login`" + `) does +NOT carry those scopes and is refused. Check yours with ` + "`civitai whoami`" + `. + +--max-cost IS AN ESTIMATE CHECK, NOT A SPENDING CAP. The cost this command shows +is an estimate, not a quote: the server's estimator returns no quote id, no +signed price and no expiry — there is nothing to hand back at submit time, and +no server-side ceiling is reachable from an API key at all. The realized charge +can exceed the estimate, and it is not refunded. --max-cost compares the +ESTIMATE against your number and refuses locally before submitting; it catches a +--quantity typo, and that is all it can do. Do not run an unattended loop +believing it caps spend. + +CONFIRMATION: an interactive run prints the estimate and your balance and asks +before spending. A non-interactive shell (pipe/CI) without --yes is REFUSED +rather than charged silently. + +WHAT THE SERVER DOES NOT TELL YOU: the generator is permissive, not a validator. +An out-of-range --quantity is clamped with no error, and a checkpoint id that +does not exist is accepted with the ecosystem default silently substituted and +billed. This command therefore resolves every --checkpoint / --lora id against +the public model-version API BEFORE submitting, so a bad id is a hard local +error instead of a wrong charge, and it echoes the resolved model NAME in the +confirmation so you approve a name rather than an integer. + +WAITING AND DOWNLOADING: by default the command waits for the job to finish and +writes every deliverable output into --out-dir as -.. Pass +--no-wait to print the workflow id and exit immediately, and pick the results up +later with ` + "`civitai workflows get `" + `. Output URLs are PRESIGNED AND +EXPIRE, so download promptly; re-read the workflow for fresh links. + +🔴 --timeout STOPS WAITING. IT DOES NOT STOP PAYING. The generation keeps +running server-side after the CLI gives up, and the charge stands — there is no +cancel-for-refund, and a mid-run cancel bills the accrued cost anyway. The same +is true of Ctrl-C. Both print the workflow id and the exact command to re-attach. + +CRASH SAFETY: the idempotency key is written to a local file BEFORE the request +is sent, because the money moves server-side even if this process dies mid-POST. +If a submit's reply never arrives, re-run with --external-id : +the orchestrator dedupes on it and returns the PRE-EXISTING workflow instead of +charging a second time. + +RAW GRAPHS: --input (or --input -) sends a generation-graph JSON document +exactly as written, instead of building one from the flags above. It is how you +reach graph parameters this CLI has no flag for. Get a valid starting point with +--print-input, which assembles the graph, prints it, and exits without +submitting or even pricing anything. + +--input is txt2img only in this release. It cannot be combined with the content +flags (--negative-prompt, --quantity, --aspect-ratio, --checkpoint, --lora) or +with a prompt argument; the execution flags all still apply. Keys that belong to +the request ENVELOPE rather than the graph — civitaiTip, creatorTip, buzzType, +tags, externalId — are REFUSED in an input file: they are this CLI's to set, and +a tip in particular is real Buzz that --dry-run structurally cannot see. Keys +this CLI does not recognise are passed through with a warning, because the +server silently drops what it does not declare rather than reporting an error. + +🔴 --input DOES NOT get the model-id safety net. --checkpoint and --lora are +resolved against the public API before submitting, so a bad id fails locally +instead of being billed with a substituted model; a raw graph is not +interpreted, so nothing in it is checked before you pay for it.`, + Example: ` # Preview the price — spends nothing + civitai generate "a cat wearing sunglasses" --dry-run + + # The same estimate as JSON, for scripts + civitai generate "a cat wearing sunglasses" --dry-run --json + + # Generate 4 images, refusing if the estimate exceeds 50 Buzz + civitai generate "a cat wearing sunglasses" --quantity 4 --max-cost 50 + + # A specific checkpoint plus a LoRA at 0.8 strength + civitai generate "a cat" --checkpoint 128713 --lora 250712:0.8 + + # Wait, and write the images into ./out + civitai generate "a cat" --yes --out-dir ./out + + # Fire and forget; collect the results later + civitai generate "a cat" --yes --no-wait + civitai workflows get + + # Non-interactive (CI): --yes is required, or the run is refused + civitai generate "a cat" --yes --max-cost 20 + + # Graduate from flags to a raw graph: print, edit, send back + civitai generate "a cat" --quantity 2 --print-input > graph.json + civitai generate --input graph.json --dry-run + civitai generate --input graph.json --yes + + # …or pipe it straight through + jq '.prompt = "a dog"' graph.json | civitai generate --input - --dry-run`, + // MaximumNArgs(1), not ExactArgs(1): a later release adds a prompt-less + // mode (--input). Today a missing prompt is a usage error, raised in + // validateGenerateOpts. 🔴 This command deliberately has NO subcommands — + // root.go's unknown-subcommand guard only covers non-runnable parents, so + // a typo'd subcommand on a runnable one would be swallowed as the PROMPT + // and billed. + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if len(args) == 1 { + o.prompt = args[0] + } + o.quantitySet = cmd.Flags().Changed("quantity") + o.checkpointSet = cmd.Flags().Changed("checkpoint") + o.maxCostSet = cmd.Flags().Changed("max-cost") + + cfg, err := config.Load() + if err != nil { + return err + } + if cfg.Token() == "" { + return civitai.Tag(civitai.ErrUnauthorized, fmt.Errorf( + "no token configured — generation needs a personal API key: run `civitai login --token ` (or set CIVITAI_TOKEN)")) + } + o.baseURL = cfg.BaseURL() + + src := auth.New(cfg) + gen := genapi.NewWithSource(cfg.BaseURL(), src) + buzz := appapi.NewWithSource(cfg.BaseURL(), src, "") + // 🔴 The blob fetcher is DownloadPresigned, never DownloadFile: + // output URLs are presigned and are served from a *.civitai.com + // host, which the download layer's trusted-host predicate would + // match — so DownloadFile would hand a full-scope personal API key + // to a request that needs no credential at all. + reader := civitai.NewWithSource(cfg.BaseURL(), src) + deps := generateDeps{ + whatIf: gen.WhatIfFromGraph, + submit: gen.GenerateFromGraph, + resolveVersion: gen.ResolveModelVersion, + getWorkflow: gen.GetWorkflow, + downloadBlob: reader.DownloadPresigned, + buzzBalance: func(ctx context.Context) (int64, error) { + acct, err := buzz.GetBuzzAccount(ctx) + if err != nil { + return 0, err + } + return acct.Total(), nil + }, + } + // Bind SIGINT for the whole run: the poll loop, the sleep between + // polls and every blob transfer all take this context, so Ctrl-C + // unblocks promptly, writePart's defer removes any partial file, + // and runGenerate's recovery path prints the re-attach command for + // the job that was already paid for. + ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt) + defer stop() + cmd.SetContext(ctx) + return runGenerate(cmd, deps, o) + }, + } + + // EXACTLY five content flags. Everything else the graph accepts is either a + // silently-degrading money lever (--steps / --cfg-scale / --sampler: a zero is + // ACCEPTED and prices a cheaper, broken job; an unknown sampler is ignored) or + // a price multiplier best not exposed before there is a way to echo what the + // server actually used. --model is deliberately absent: `civitai download` + // already uses --model for a MODEL id, and this takes a VERSION id. + cmd.Flags().StringVar(&o.negativePrompt, "negative-prompt", "", "negative prompt") + cmd.Flags().IntVar(&o.quantity, "quantity", 0, "number of images to generate (server default when unset; no -n shorthand, it reads as \"no\")") + cmd.Flags().StringVar(&o.aspectRatio, "aspect-ratio", "", "aspect ratio bucket, e.g. 1:1 (width/height derive from it)") + cmd.Flags().IntVar(&o.checkpoint, "checkpoint", 0, "checkpoint model-VERSION id (not a model id) — resolved before submitting") + cmd.Flags().StringArrayVar(&o.loras, "lora", nil, "LoRA model-version id, optionally :strength (e.g. 250712:0.8). Repeatable") + + cmd.Flags().BoolVar(&o.dryRun, "dry-run", false, "print the cost estimate and exit without submitting (spends nothing)") + cmd.Flags().BoolVar(&o.jsonOut, "json", false, "emit the raw server payload on stdout (scriptable)") + cmd.Flags().BoolVarP(&o.assumeYes, "yes", "y", false, "skip the confirmation and submit (required in a non-interactive shell)") + // NOTE: no back-quotes in this usage string — pflag's UnquoteUsage treats the + // first back-quoted span as the flag's VALUE NAME. + cmd.Flags().IntVar(&o.maxCost, "max-cost", 0, + "refuse to submit if the ESTIMATE exceeds this many Buzz. This is an estimate check, NOT a spending cap: "+ + "the estimate is not binding, the server enforces no ceiling, and the realized charge can be higher with no refund") + + // NOTE: no back-quotes in ANY usage string here — pflag's UnquoteUsage + // treats the first back-quoted span as the flag's VALUE NAME. Quoting a + // command in this bool flag's usage rendered it in --help as a flag that + // takes a value called "civitai workflows get " (measured, then fixed). + // Use single quotes. Pinned by TestGenerateFlagUsageHasNoBackquotes. + cmd.Flags().BoolVar(&o.noWait, "no-wait", false, + "submit, print the workflow id and exit without waiting; collect the results later with 'civitai workflows get '") + // 🔴 The wording here is load-bearing. --timeout bounds the CLI's WAIT. The + // job keeps running and the charge stands, so any phrasing that hints at + // "stop the generation" or "cap the spend" is a lie the user pays for. + cmd.Flags().DurationVar(&o.timeout, "timeout", defaultWaitTimeout, + "how long to WAIT for the generation to finish (e.g. 5m, 0 waits indefinitely). This stops the CLI waiting; "+ + "it does NOT stop the generation and does NOT stop the charge — the job continues server-side and is not refunded") + cmd.Flags().StringVar(&o.outDir, "out-dir", ".", + "directory to write the generated files into (created if needed); named -.") + cmd.Flags().BoolVar(&o.noDownload, "no-download", false, + "wait for the result and print the output URLs, but write no files") + cmd.Flags().BoolVar(&o.force, "force", false, "overwrite existing output files instead of refusing") + cmd.Flags().StringVar(&o.externalID, "external-id", "", + "re-attach to an earlier submit by reusing its idempotency key (the orchestrator dedupes on it and returns the "+ + "PRE-EXISTING workflow rather than charging again). Use the key recorded before the lost submit") + + // NOTE: no back-quotes in these usage strings either — see the note above. + cmd.Flags().StringVar(&o.inputPath, "input", "", + "read the generation graph from a JSON file ('-' for stdin) and send it as-is, instead of building one from flags. "+ + "txt2img only. Cannot be combined with the content flags above") + cmd.Flags().BoolVar(&o.printInput, "print-input", false, + "print the exact generation graph that would be sent and exit without submitting. Redirect it to a file, edit it, "+ + "and feed it back with --input") + return cmd +} + +// graphInputFlags are the content flags --input replaces. They are listed here +// so the mutual-exclusion error can name exactly which one the user passed, +// following validateDownloadFlags: reject the combination rather than invent a +// merge rule. (What would --lora mean against a file that already declares +// `resources`? Append, or replace? There is no answer the user can predict, and +// guessing wrong costs them a generation.) +func graphInputFlags(o generateOpts) []string { + var used []string + if strings.TrimSpace(o.prompt) != "" { + used = append(used, "a prompt argument") + } + if o.negativePrompt != "" { + used = append(used, "--negative-prompt") + } + if o.quantitySet { + used = append(used, "--quantity") + } + if o.aspectRatio != "" { + used = append(used, "--aspect-ratio") + } + if o.checkpointSet { + used = append(used, "--checkpoint") + } + if len(o.loras) > 0 { + used = append(used, "--lora") + } + return used +} + +// validateGenerateOpts rejects impossible invocations BEFORE any network call, +// the way validateDownloadFlags does — every failure here is a local mistake, so +// it is a usage error (exit 2). +func validateGenerateOpts(o *generateOpts) error { + usingInput := strings.TrimSpace(o.inputPath) != "" + if usingInput { + // Mutual exclusion, not a merge. Execution flags (--dry-run, --yes, + // --max-cost, --out-dir, --timeout, --no-wait, --json, --force, + // --external-id) stay valid: they govern HOW the request is made and + // what happens to the result, and none of them writes to the graph. + if used := graphInputFlags(*o); len(used) > 0 { + return asUsageError(fmt.Errorf( + "--input cannot be combined with %s — --input sends the graph in the file exactly as written, so a flag that would also set graph content has no defined meaning against it. "+ + "Either drop %s, or edit the file (start from `civitai generate \"a cat\" --print-input`)", + strings.Join(used, ", "), plural(len(used), "it", "them"))) + } + } else if strings.TrimSpace(o.prompt) == "" { + return asUsageError(errors.New( + "a prompt is required — quote it as one argument: civitai generate \"a cat wearing sunglasses\" (or pass a graph with --input )")) + } + if o.quantitySet && o.quantity < 1 { + // The server would CLAMP this to 1 without saying so. Refuse instead: a + // user who typed 0 did not mean 1, and they would be charged for it. + return asUsageError(fmt.Errorf("--quantity must be at least 1, got %d", o.quantity)) + } + if o.checkpointSet && o.checkpoint < 1 { + return asUsageError(fmt.Errorf( + "--checkpoint must be a positive model-VERSION id, got %d — find it in a model's URL (…/models/?modelVersionId=)", o.checkpoint)) + } + if o.maxCostSet && o.maxCost < 0 { + return asUsageError(fmt.Errorf("--max-cost must not be negative, got %d", o.maxCost)) + } + if o.jsonOut && !o.dryRun && !o.assumeYes { + // --json is a scripting path; pairing it with an interactive money prompt + // invites a script that hangs or, worse, one whose operator clicks through. + // Say so up front rather than at the prompt. + return asUsageError(errors.New( + "--json without --dry-run submits and spends Buzz — pass --yes to confirm non-interactively, or --dry-run to only estimate")) + } + if o.timeout < 0 { + return asUsageError(fmt.Errorf("--timeout must not be negative, got %s (use 0 to wait indefinitely)", o.timeout)) + } + if o.noWait && o.noDownload { + // --no-wait already downloads nothing; accepting both would imply the + // two do different things. + return asUsageError(errors.New("--no-wait already exits before any result exists — drop --no-download")) + } + if strings.TrimSpace(o.outDir) == "" { + // The flag default is ".", so an empty value can only come from a + // programmatic construction (or `--out-dir ""`). Resolve it to the + // documented default rather than erroring: an empty path would silently + // become a relative write anyway. + o.outDir = "." + } + for _, raw := range o.loras { + if _, err := parseLoraFlag(raw); err != nil { + return err + } + } + return nil +} + +// loraSpec is one parsed --lora value. +type loraSpec struct { + versionID int + // strength is nil when the user gave none, so the field is ABSENT from the + // payload and the server applies its own default. + strength *float64 +} + +// parseLoraFlag parses `` or `:`. Anything else +// is a usage error — a silently-mis-parsed strength is a money mistake, since the +// server accepts whatever it is handed. +func parseLoraFlag(raw string) (loraSpec, error) { + v := strings.TrimSpace(raw) + bad := func(why string) error { + return asUsageError(fmt.Errorf("invalid --lora %q — %s; expected or :, e.g. 250712 or 250712:0.8", raw, why)) + } + if v == "" { + return loraSpec{}, bad("it is empty") + } + idPart, strengthPart, hasStrength := strings.Cut(v, ":") + id, err := strconv.Atoi(strings.TrimSpace(idPart)) + if err != nil { + return loraSpec{}, bad("the id is not an integer") + } + if id < 1 { + return loraSpec{}, bad("the id must be positive") + } + if !hasStrength { + return loraSpec{versionID: id}, nil + } + s := strings.TrimSpace(strengthPart) + if s == "" { + return loraSpec{}, bad("the strength is missing after ':'") + } + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return loraSpec{}, bad("the strength is not a number") + } + return loraSpec{versionID: id, strength: &f}, nil +} + +// resolvedGraph is the built payload plus the human labels the confirmation +// needs, so the user approves NAMES rather than integers. +type resolvedGraph struct { + graph genapi.Graph + checkpoint string + loras []string + // inputPath is set when the graph came from --input, so the confirmation can + // name the FILE the user is about to be charged for rather than a prompt it + // deliberately did not parse out of it. + inputPath string +} + +// buildInputGraph loads, validates and wraps a `--input` graph. +// +// It performs NO network calls: the graph is passed through verbatim, so there +// are no model-version ids for the CLI to resolve — and resolving them would +// require parsing a structure the CLI has deliberately declined to interpret. +// +// 🔴 The cost of that: the --checkpoint/--lora path's protection against a +// nonexistent id (accepted with HTTP 200, ecosystem default silently +// substituted, billed) does NOT extend to --input. That is inherent to a +// passthrough, not an oversight, and the warning below says so out loud rather +// than letting the flag look as safe as the flags it replaces. +func buildInputGraph(cmd *cobra.Command, o generateOpts) (*resolvedGraph, error) { + data, err := readGraphInput(cmd.InOrStdin(), o.inputPath) + if err != nil { + return nil, err + } + parsed, err := parseGraphInput(data) + if err != nil { + return nil, err + } + errw := cmd.ErrOrStderr() + if w := unknownKeyWarning(parsed.unknownKeys); w != "" { + fmt.Fprintln(errw, ui.For(errw).Warn(w)) + } + return &resolvedGraph{ + graph: genapi.Graph{Raw: parsed.raw}, + inputPath: o.inputPath, + }, nil +} + +// buildGenerateGraph resolves every model-version id and assembles the graph. +// +// 🔴 The resolution is not a nicety. Graph resources REQUIRE the model type, +// which is not derivable from a version id, and a nonexistent checkpoint id is +// accepted by the generator with HTTP 200 and the ecosystem default substituted +// and BILLED. Resolving first turns that into a hard local 404 — before any +// spend, and before the cost estimate the user is shown. +func buildGenerateGraph(ctx context.Context, deps generateDeps, o generateOpts) (*resolvedGraph, error) { + out := &resolvedGraph{graph: genapi.Graph{ + Workflow: generateWorkflow, + Prompt: o.prompt, + NegativePrompt: o.negativePrompt, + AspectRatio: o.aspectRatio, + }} + if o.quantitySet { + out.graph.Quantity = genapi.Ptr(o.quantity) + } + + if o.checkpointSet { + rv, err := deps.resolveVersion(ctx, o.checkpoint) + if err != nil { + return nil, fmt.Errorf("--checkpoint %d: %w", o.checkpoint, err) + } + out.graph.Model = genapi.Ptr(rv.Resource(nil)) + out.checkpoint = describeVersion(rv, nil) + } + for _, raw := range o.loras { + spec, err := parseLoraFlag(raw) + if err != nil { + return nil, err + } + rv, err := deps.resolveVersion(ctx, spec.versionID) + if err != nil { + return nil, fmt.Errorf("--lora %s: %w", raw, err) + } + out.graph.Resources = append(out.graph.Resources, rv.Resource(spec.strength)) + out.loras = append(out.loras, describeVersion(rv, spec.strength)) + } + return out, nil +} + +// buildGraphForRun picks the graph source: a `--input` passthrough, or the five +// content flags. validateGenerateOpts has already proved the two were not +// combined. +func buildGraphForRun(ctx context.Context, cmd *cobra.Command, deps generateDeps, o generateOpts) (*resolvedGraph, error) { + if strings.TrimSpace(o.inputPath) != "" { + return buildInputGraph(cmd, o) + } + return buildGenerateGraph(ctx, deps, o) +} + +// printAssembledGraph writes the graph that WOULD be sent, indented, to stdout. +// +// It prints the graph and nothing else — not the tRPC envelope. The envelope's +// siblings (externalId, tips, tags) are CLI-owned and are refused on the way +// back in (see envelopeOnlyKeys), so printing them would emit a document that +// `--input` then rejects. What comes out of --print-input must be a valid +// --input; that round-trip is the feature. +func printAssembledGraph(out io.Writer, g genapi.Graph) error { + raw, err := json.Marshal(g) + if err != nil { + return err + } + var buf bytes.Buffer + if err := json.Indent(&buf, raw, "", " "); err != nil { + return err + } + buf.WriteByte('\n') + _, err = out.Write(buf.Bytes()) + return err +} + +// describeVersion renders a resolved version for human output. The name is +// server-origin text, so it goes through safeTerm. +func describeVersion(rv *genapi.ResolvedVersion, strength *float64) string { + s := fmt.Sprintf("%s (%s, id %d)", safeTerm(rv.DisplayName()), safeTerm(rv.ModelType), rv.VersionID) + if strength != nil { + s += fmt.Sprintf(", strength %s", strconv.FormatFloat(*strength, 'g', -1, 64)) + } + return s +} + +// runGenerate is the testable core: validate, resolve, estimate, gate, submit. +// +// The order matters and is a spend-safety property: nothing that could charge +// the user runs until the ids resolve, the estimate is in hand, --max-cost has +// been honoured, the balance has been compared, and the user (or --yes) has +// agreed. +func runGenerate(cmd *cobra.Command, deps generateDeps, o generateOpts) error { + if err := validateGenerateOpts(&o); err != nil { + return err + } + ctx := cmd.Context() + if ctx == nil { + ctx = context.Background() + } + out, errw := cmd.OutOrStdout(), cmd.ErrOrStderr() + + if o.quantitySet && o.quantity > serverQuantityClamp { + // Warn, never block: the clamp is a server fact that can change, and the + // silent version of this is a user paying for 10 images after asking for 40. + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf( + "--quantity %d is above the server's current limit (%d). The server CLAMPS silently — you will get %d, and the estimate below already prices that.", + o.quantity, serverQuantityClamp, serverQuantityClamp))) + } + + built, err := buildGraphForRun(ctx, cmd, deps, o) + if err != nil { + return err + } + + if o.printInput { + // 🔴 Exit here, BEFORE the estimator and long before the submit. This is + // the documented way to graduate from flags to a file + // (`--print-input > g.json` → edit → `--input g.json`), and it replaces + // the `--set` path-expression surface that was cut: a wrong type in a + // hand-written --set expression is accepted silently by the server and + // billed, whereas editing a printed file is inspectable before it is + // sent. + // + // One honest caveat on "no network call": it reaches NO money seam — + // not the submit, not the estimator, not the balance read. But the graph + // is printed AFTER buildGraphForRun, so `--checkpoint`/`--lora` still + // perform their public model-version READ (free, unauthenticated-capable, + // spends nothing). That is deliberate: the resolution supplies + // `model.type`, which graph `resources[]` REQUIRE — a bare `{id}` is + // rejected 400 "expected object, received undefined". Skipping it would + // make --print-input emit a document that --input then cannot submit, + // destroying the round-trip that is the whole feature. With no + // --checkpoint/--lora there is no request of any kind. + return printAssembledGraph(out, built.graph) + } + + quote, rawQuote, err := deps.whatIf(ctx, built.graph) + if err != nil { + return classifyGenerateError(err) + } + if quote == nil || quote.Cost == nil { + // A cost-less estimate must never render as "free". Refuse rather than + // invent a number the user would approve. + return fmt.Errorf("the server returned no cost estimate — refusing to submit a generation whose price is unknown") + } + + if o.dryRun { + if o.jsonOut { + // Raw passthrough: a script sees every field, including ones this CLI + // does not model. + return writeRawJSON(out, rawQuote) + } + printGenerateQuote(out, errw, built, o, quote) + return nil + } + + if !quote.Ready { + // `ready:false` means some job in the workflow has no available support — + // the resources are not currently generatable. Submitting anyway spends on + // a job the server has already said it cannot serve. + return civitai.Tag(civitai.ErrBadRequest, fmt.Errorf( + "the server reports this job is not currently generatable (ready: false) — the selected resources may be unavailable or unsupported by this workflow; inspect the estimate with --dry-run --json")) + } + + cost := quote.Cost.Total + if o.maxCostSet && cost > float64(o.maxCost) { + return asUsageError(fmt.Errorf( + "estimated cost %s Buzz exceeds --max-cost %d — nothing was submitted. Raise --max-cost or lower --quantity (remember --max-cost only checks this ESTIMATE; it is not a cap the server enforces)", + buzzAmount(cost), o.maxCost)) + } + + balance, balanceKnown := int64(0), false + if b, berr := deps.buzzBalance(ctx); berr != nil { + // Advisory: a balance we cannot read must not block a user who can + // generate — but it must never be shown as a number either, or an + // unreadable balance reads as "you have 0". + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf( + "could not read your Buzz balance (%v) — continuing without the balance check; verify with `civitai buzz`", berr))) + } else { + balance, balanceKnown = b, true + } + if balanceKnown && cost > float64(balance) { + return civitai.Tag(ErrInsufficientBuzz, fmt.Errorf( + "estimated cost %s Buzz exceeds your balance of %d — nothing was submitted; buy Buzz at %s/purchase/buzz", + buzzAmount(cost), balance, strings.TrimRight(o.baseURL, "/"))) + } + + if err := confirmGenerate(cmd, o, built, cost, balance, balanceKnown); err != nil { + return err + } + + // 🔴 The idempotency key is minted HERE, not inside the submit, so it can be + // RECORDED BEFORE the request leaves. The charge happens server-side the + // moment the orchestrator accepts the workflow; a process that dies during + // the POST has already spent the money and, without this record, has no + // handle to what it bought. + externalID := strings.TrimSpace(o.externalID) + if externalID == "" { + var mintErr error + if externalID, mintErr = genapi.NewExternalID(); mintErr != nil { + return mintErr + } + } + statePath, stateErr := writeSubmitRecord(deps, o, built.graph, externalID) + if stateErr != nil { + // Never fatal — a user who can generate must not be blocked by a config + // directory problem. But say it BEFORE the spend, because the crash- + // recovery net is what is missing, not a cosmetic feature. + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf( + "could not write the crash-recovery record (%v) — if this run is interrupted mid-submit you will have to find the job at %s/generate. Your idempotency key is %s", + stateErr, strings.TrimRight(o.baseURL, "/"), externalID))) + } + + result, externalID, rawSubmit, err := deps.submit(ctx, built.graph, genapi.SubmitOptions{ExternalID: externalID}) + if err != nil { + if genapi.StatusOf(err) == 0 { + // No HTTP status means no interpretable reply: the request may well + // have reached the orchestrator and been charged. Never let this + // read as "nothing happened". + // + // 🔴 THIS WARNING MUST NEVER BE SUPPRESSED, and a cancelled context is + // NOT grounds to suppress it. An earlier revision returned early on + // ctx.Err() != nil, reasoning that a cancel means the request never + // left the process. That is true only for the microseconds before the + // POST; Ctrl-C during the round trip cancels the SAME context, and + // that window is up to submitTimeout (see genapi.Client.submitClient) + // — a slow orchestrator hop being exactly why a user reaches for + // Ctrl-C. So the guard traded a harmless false warning in a + // microsecond window for SILENCE in a two-minute window where the + // charge is real, and silence here strands the user: this is the only + // surface that hands back the externalId, and nothing reads the + // crash-recovery record. Compare the wait loop's cancel path, which + // routes to printReattach (this file, called from waitAndCollect) and + // says the job "has already been charged" — the precedent points the + // other way. + // + // We cannot observe whether the bytes were written, so the message + // carries the uncertainty instead of the control flow resolving it. + lead := "the submit got no answer from the server" + if ctxErr := ctx.Err(); ctxErr != nil { + lead = "the submit was interrupted before any answer arrived" + } + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf( + "%s — it MAY still have been accepted and charged. Do NOT simply re-run it; re-attach with:\n civitai generate %s --external-id %s", + lead, reattachInvocation(o), externalID))) + } + return classifyGenerateError(err) + } + + workflowID := "" + if result != nil { + workflowID = result.ID + } + if statePath != "" && workflowID != "" { + // Best-effort: the id is about to be printed anyway. + _ = recordPendingWorkflowID(statePath, workflowID) + } + + if o.noWait || workflowID == "" { + // Nothing more can be done without a handle to poll, so the record has + // served its purpose the moment the id reaches the user. + if workflowID != "" { + clearSubmitRecord(statePath) + } + if o.jsonOut { + return writeRawJSON(out, rawSubmit) + } + printSubmitResult(out, errw, result, externalID, o.baseURL, o.noWait) + return nil + } + + var submitCost *genapi.WorkflowCost + if result != nil { + submitCost = result.Cost + } + printSubmitted(errw, workflowID, externalID, o.baseURL, submitCost) + return waitAndCollect(ctx, cmd, deps, o, workflowID, externalID, statePath) +} + +// writeSubmitRecord writes the pre-submit crash-recovery record and returns its +// path. It resolves the directory from deps (a test points it at a t.TempDir()). +func writeSubmitRecord(deps generateDeps, o generateOpts, g genapi.Graph, externalID string) (string, error) { + dir := deps.pendingDir + if dir == "" { + var err error + if dir, err = pendingDir(); err != nil { + return "", err + } + } + return writePendingGeneration(dir, pendingGeneration{ + ExternalID: externalID, + SubmittedAt: nowRFC3339(), + PayloadHash: graphPayloadHash(g), + BaseURL: o.baseURL, + }) +} + +// clearSubmitRecord removes a record whose workflow id has been reported to the +// user — from that point the workflow id IS the handle, and keeping the file +// would just accumulate clutter that looks like unfinished work. +func clearSubmitRecord(path string) { + if path != "" { + _ = os.Remove(path) + } +} + +// waitAndCollect polls the submitted workflow to a terminal status, then reports +// and (unless --no-download) downloads its deliverable outputs. +// +// Every early exit here — timeout, Ctrl-C, a failed workflow — is an ERROR +// return, never a success: the user paid, and a zero exit code would tell a +// script the images are on disk. +func waitAndCollect(ctx context.Context, cmd *cobra.Command, deps generateDeps, o generateOpts, workflowID, externalID, statePath string) error { + out, errw := cmd.OutOrStdout(), cmd.ErrOrStderr() + + cfg := deps.poll + cfg.timeout = o.timeout + rep := newPollReporter(errw, cfg.now, cfg.heartbeat) + + wf, rawWF, err := pollWorkflow(ctx, deps.getWorkflow, workflowID, cfg, rep) + if err != nil { + switch { + case errors.Is(err, errWaitTimeout): + printReattach(errw, o, workflowID, externalID, statusOrUnknown(wf), + fmt.Sprintf("Stopped waiting after %s.", o.timeout)) + return fmt.Errorf("%w after %s — the generation is still running and has already been charged; it was not cancelled", errWaitTimeout, o.timeout) + case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + printReattach(errw, o, workflowID, externalID, statusOrUnknown(wf), + "Interrupted.") + return fmt.Errorf("interrupted while waiting — the generation is still running and has already been charged; it was not cancelled") + } + return classifyGenerateError(err) + } + + // The workflow id is now the durable handle and has been printed; the + // pre-submit record is no longer load-bearing. + clearSubmitRecord(statePath) + + if !strings.EqualFold(wf.Status, genapi.StatusSucceeded) { + // failed / expired / canceled. Say plainly that it was still charged — + // the orchestrator does not refund a job that ran and failed. + return fmt.Errorf("the generation finished with status %q — it was charged and produced no usable result; inspect it with `civitai workflows get %s`", + safeTerm(wf.Status), safeTerm(workflowID)) + } + + kept, excluded := genapi.PartitionOutputs(wf) + reportExcludedOutputs(errw, excluded) + requested := 0 + if o.quantitySet { + requested = o.quantity + if requested > serverQuantityClamp { + // The server clamps silently, so the honest expectation is the + // clamped number, not what was typed. + requested = serverQuantityClamp + } + } + reportOutputCountMismatch(errw, requested, len(kept)) + + if len(kept) == 0 { + return fmt.Errorf("the generation succeeded but produced no deliverable outputs — it was charged; inspect it with `civitai workflows get %s`", safeTerm(workflowID)) + } + + if o.noDownload { + printOutputURLs(out, errw, kept) + } else { + // With --json the machine-readable payload owns stdout, so the "Saved …" + // lines move to stderr rather than corrupting it. + saveW := out + if o.jsonOut { + saveW = errw + } + paths, derr := downloadOutputs(ctx, deps.downloadBlob, saveW, errw, workflowID, kept, o.outDir, o.force) + if derr != nil { + if len(paths) > 0 { + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf("%d of %d output(s) were saved before this failed", len(paths), len(kept)))) + } + fmt.Fprintln(errw, ui.For(errw).Dim(fmt.Sprintf( + "Output URLs expire — re-read the workflow for fresh links: civitai workflows get %s", workflowID))) + return derr + } + } + + if o.jsonOut { + return writeRawJSON(out, rawWF) + } + return nil +} + +// printOutputURLs renders the --no-download listing. +func printOutputURLs(out, errw io.Writer, kept []genapi.Output) { + for i, o := range kept { + if o.URL != nil { + fmt.Fprintf(out, "%d\t%s\n", i+1, safeTerm(*o.URL)) + } + } + fmt.Fprintln(errw, ui.For(errw).Dim( + "These URLs are presigned and expire — fetch them promptly, or re-read the workflow for fresh links.")) +} + +// printSubmitted announces a submitted job on the DEFAULT (waiting) path. It +// writes to stderr so a --json stdout stays machine-clean. +// +// 🔴 It must print the REALIZED charge whenever the server reported one. The +// user approved an ESTIMATE, and this command's whole spend story is that the +// realized cost can exceed it with no refund (AGENTS.md items 11-16) — so the +// one number that settles what actually happened cannot be visible only on the +// --no-wait branch. `cost` is nil when the server sent none; say nothing then +// rather than printing a fabricated 0. +func printSubmitted(errw io.Writer, workflowID, externalID, baseURL string, cost *genapi.WorkflowCost) { + st := ui.For(errw) + fmt.Fprintln(errw, st.Success(fmt.Sprintf("Generation submitted — workflow %s", safeTerm(workflowID)))) + if cost != nil { + fmt.Fprintln(errw, st.Info(fmt.Sprintf("Charged %s Buzz", buzzAmount(cost.Total)))) + } + fmt.Fprintln(errw, st.Dim(fmt.Sprintf( + "External ID %s · watch it at %s/generate · re-attach any time with `civitai workflows get %s`", + externalID, strings.TrimRight(baseURL, "/"), safeTerm(workflowID)))) +} + +// printReattach is the recovery block for a wait that ended without a result. +// +// 🔴 It must never suggest the job stopped. The CLI gave up WAITING; the +// orchestrator kept generating and the Buzz is gone either way. Everything here +// exists so the user can get to what they already paid for. +func printReattach(errw io.Writer, o generateOpts, workflowID, externalID, status, lead string) { + st := ui.For(errw) + fmt.Fprintln(errw, st.Warn(fmt.Sprintf( + "%s The generation was NOT cancelled — it is still running server-side and has already been charged.", lead))) + fmt.Fprintf(errw, " Workflow ID: %s\n", safeTerm(workflowID)) + fmt.Fprintf(errw, " External ID: %s\n", externalID) + fmt.Fprintf(errw, " Last status: %s\n", safeTerm(status)) + fmt.Fprintf(errw, " Re-attach: civitai workflows get %s\n", safeTerm(workflowID)) + fmt.Fprintln(errw, st.Dim(fmt.Sprintf("Or watch it at %s/generate", strings.TrimRight(o.baseURL, "/")))) +} + +// confirmGenerate gates the spend. It mirrors confirmSubmit, with a stronger +// case: `app submit` gates a REVERSIBLE action and still prompts, while this +// charges Buzz that cannot be refunded. +// +// - --yes/-y → proceed without prompting. +// - non-TTY without --yes → REFUSE (never hang, never charge silently). +// - interactive TTY → show cost + balance, prompt, proceed only on "y". +// +// Everything it prints goes to STDERR so a `--json` stdout stays machine-clean. +func confirmGenerate(cmd *cobra.Command, o generateOpts, built *resolvedGraph, cost float64, balance int64, balanceKnown bool) error { + if o.assumeYes { + return nil + } + if !stdinIsTTY() { + return fmt.Errorf("refusing to spend Buzz without --yes in a non-interactive shell — this would charge %s Buzz with nobody to confirm it. "+ + "Pass --yes to confirm, --max-cost to refuse above an estimate, or --dry-run to price it without submitting", + buzzAmount(cost)) + } + + errw := cmd.ErrOrStderr() + st := ui.For(errw) + fmt.Fprintf(errw, "About to generate with %s at %s.\n", generateWorkflow, strings.TrimRight(o.baseURL, "/")) + if built.inputPath != "" { + // With --input the CLI has deliberately not interpreted the graph, so it + // names the file rather than echoing fields it did not parse. Printing a + // partial summary would imply the CLI had checked the rest. + fmt.Fprintf(errw, " Graph: %s (sent as-is; this CLI did not interpret it)\n", safeTerm(built.inputPath)) + } else { + fmt.Fprintf(errw, " Prompt: %s\n", safeTerm(o.prompt)) + } + if o.negativePrompt != "" { + fmt.Fprintf(errw, " Negative: %s\n", safeTerm(o.negativePrompt)) + } + if o.quantitySet { + fmt.Fprintf(errw, " Quantity: %d\n", o.quantity) + } + if built.checkpoint != "" { + fmt.Fprintf(errw, " Checkpoint: %s\n", built.checkpoint) + } + for _, l := range built.loras { + fmt.Fprintf(errw, " LoRA: %s\n", l) + } + if balanceKnown { + fmt.Fprintf(errw, "Cost: %s Buzz (balance %d).\n", buzzAmount(cost), balance) + } else { + fmt.Fprintf(errw, "Cost: %s Buzz (balance unknown).\n", buzzAmount(cost)) + } + fmt.Fprintln(errw, st.Warn("This SPENDS REAL BUZZ. It cannot be undone and is not refunded.")) + fmt.Fprintln(errw, st.Dim("The cost is an estimate, not a quote — the server enforces no ceiling and the realized charge can be higher.")) + fmt.Fprint(errw, "Generate? [y/N]: ") + + r := bufio.NewReader(cmd.InOrStdin()) + line, _ := r.ReadString('\n') + switch strings.ToLower(strings.TrimSpace(line)) { + case "y", "yes": + return nil + default: + return errors.New("generation cancelled") + } +} + +// printGenerateQuote renders the --dry-run breakdown. Factor and fixed keys are +// printed VERBATIM — they are server-owned, and inventing friendlier labels is +// how a vendored mapping starts. +func printGenerateQuote(out, errw io.Writer, built *resolvedGraph, o generateOpts, q *genapi.WhatIfResult) { + tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Workflow:\t%s\n", generateWorkflow) + if built.inputPath != "" { + fmt.Fprintf(tw, "Graph:\t%s (sent as-is)\n", safeTerm(built.inputPath)) + } else { + fmt.Fprintf(tw, "Prompt:\t%s\n", safeTerm(o.prompt)) + } + if o.negativePrompt != "" { + fmt.Fprintf(tw, "Negative prompt:\t%s\n", safeTerm(o.negativePrompt)) + } + if o.quantitySet { + fmt.Fprintf(tw, "Quantity:\t%d\n", o.quantity) + } + if o.aspectRatio != "" { + fmt.Fprintf(tw, "Aspect ratio:\t%s\n", safeTerm(o.aspectRatio)) + } + if built.checkpoint != "" { + fmt.Fprintf(tw, "Checkpoint:\t%s\n", built.checkpoint) + } + for _, l := range built.loras { + fmt.Fprintf(tw, "LoRA:\t%s\n", l) + } + fmt.Fprintf(tw, "Generatable:\t%t\n", q.Ready) + _ = tw.Flush() + + fmt.Fprintf(out, "\n%s\n", ui.For(out).Bold("Estimated cost")) + tw = tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, " base\t%s\n", buzzAmount(q.Cost.Base)) + printCostMap(tw, "factors", q.Cost.Factors) + printCostMap(tw, "fixed", q.Cost.Fixed) + printCostMap(tw, "tips", q.Cost.Tips) + fmt.Fprintf(tw, " total\t%s\n", buzzAmount(q.Cost.Total)) + _ = tw.Flush() + + if !q.Ready { + fmt.Fprintln(errw, ui.For(errw).Warn( + "The server reports this job is NOT currently generatable (ready: false) — a real submit would be refused.")) + } + // The caveat belongs on stderr next to the number, every time. A user who + // reads only the total will otherwise treat it as a quote. + fmt.Fprintln(errw, ui.For(errw).Dim( + "Estimate only — nothing was submitted and nothing was charged. The server returns no binding quote, enforces no spending ceiling, and the realized charge can exceed this figure with no refund.")) +} + +// printCostMap renders one server-owned cost map with its keys sorted for a +// stable rendering (Go map order is randomised). +func printCostMap(w io.Writer, label string, m map[string]float64) { + if len(m) == 0 { + return + } + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + fmt.Fprintf(w, " %s\t\n", label) + for _, k := range keys { + fmt.Fprintf(w, " %s\t%s\n", safeTerm(k), buzzAmount(m[k])) + } +} + +// printSubmitResult reports a completed submit. The workflow id is the ONLY +// handle to a job that has already been paid for, so if the server's reply does +// not carry one, say so loudly and print the idempotency key instead of leaving +// the user with nothing. +func printSubmitResult(out, errw io.Writer, r *genapi.SubmitResult, externalID, baseURL string, noWait bool) { + if r == nil || r.ID == "" { + fmt.Fprintln(errw, ui.For(errw).Warn( + "The generation was submitted but the server's reply carried no workflow id. It has been CHARGED — do not resubmit.")) + fmt.Fprintf(out, "External ID: %s\n", externalID) + fmt.Fprintln(errw, ui.For(errw).Dim(fmt.Sprintf( + "Find the job at %s/generate. To re-attach without paying again, re-run with --external-id %s — the orchestrator dedupes on it and returns the SAME workflow.", + strings.TrimRight(baseURL, "/"), externalID))) + return + } + fmt.Fprintln(out, ui.For(out).Success("Generation submitted")) + tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, " Workflow ID:\t%s\n", safeTerm(r.ID)) + if r.Status != "" { + fmt.Fprintf(tw, " Status:\t%s\n", safeTerm(r.Status)) + } + if r.Cost != nil { + fmt.Fprintf(tw, " Charged:\t%s Buzz\n", buzzAmount(r.Cost.Total)) + } + fmt.Fprintf(tw, " External ID:\t%s\n", externalID) + _ = tw.Flush() + if noWait { + fmt.Fprintln(errw, ui.For(errw).Dim(fmt.Sprintf( + "Not waiting (--no-wait). Collect the results with `civitai workflows get %s`, or watch it at %s/generate", + safeTerm(r.ID), strings.TrimRight(baseURL, "/")))) + } +} + +// reattachInvocation renders the argument the user must repeat to re-attach to a +// submit whose reply was lost. It has to reflect how the graph was BUILT: a +// --input run has no prompt to quote, and printing an empty one would hand the +// user a command that re-submits a different (and rejected) job. +func reattachInvocation(o generateOpts) string { + if p := strings.TrimSpace(o.inputPath); p != "" { + return fmt.Sprintf("--input %s", p) + } + return fmt.Sprintf("%q", o.prompt) +} + +// buzzAmount renders a Buzz figure: whole numbers without a decimal tail, and a +// fractional one with enough digits to stay honest. +func buzzAmount(f float64) string { + if f == float64(int64(f)) { + return strconv.FormatInt(int64(f), 10) + } + return strconv.FormatFloat(f, 'f', -1, 64) +} + +// classifyGenerateError re-classifies a generation failure whose HTTP status +// alone maps to the wrong exit code. +// +// 🔴 It reads genapi.APIError.ServerMessage — the SERVER's own text — never +// err.Error(). The formatted 403 message this CLI builds itself enumerates every +// cause a 403 can have, so matching against it would classify every 403 as +// whichever pattern is checked first. +// +// It REPLACES the error rather than wrapping it, because civitai.TagStatus has +// already attached ErrUnauthorized to a 403 and errors.Is would keep matching it +// through any wrapper — the user-visible text is rebuilt here (server message +// included, sanitised) so nothing is lost. +// +// Message matching is the only discriminator available: tRPC answers all of +// these with the same code, and the only difference is the text. It fails SOFT — +// an unrecognised message keeps today's status-derived classification, so a +// server-side rewording degrades to the current behaviour, never to a wrong one. +func classifyGenerateError(err error) error { + var apiErr *genapi.APIError + if !errors.As(err, &apiErr) { + return err + } + msg := strings.ToLower(apiErr.ServerMessage) + shown := safeTerm(strings.TrimSpace(apiErr.ServerMessage)) + has := func(needles ...string) bool { + for _, n := range needles { + if strings.Contains(msg, n) { + return true + } + } + return false + } + + switch { + // Insufficient Buzz. Server-side this is an orchestrator 403 re-thrown as + // tRPC BAD_REQUEST, so it reaches us as a 400 and would otherwise exit 2 + // ("bad flags") — which is wrong, and the design doc's claim that it exits 3 + // is wrong too. Matched status-agnostically on purpose: the promise is that + // running out of Buzz NEVER reads as "log in again", whichever status it + // arrives on. The default server text is "…don't have enough funds…"; a + // pass-through orchestrator detail is matched by the other needles. + case has("enough funds", "insufficient funds", "insufficient buzz", "not enough buzz"): + return civitai.Tag(ErrInsufficientBuzz, fmt.Errorf( + "not enough Buzz to run this generation: %s — check your balance with `civitai buzz`", shown)) + + // Prompt refused by the content audit. 🔴 Never retry: repeated blocked + // prompts increment a 30-day counter that auto-mutes the account, so a retry + // loop turns one refusal into a permanent generation ban. + case has("your prompt was flagged", "prompt was flagged"): + return civitai.Tag(ErrPromptBlocked, fmt.Errorf( + "the prompt was refused by content moderation: %s — 🔴 do NOT retry this prompt: repeated blocked attempts get the account muted. Edit the prompt instead", shown)) + + // Generation switched off (or member-only) server-side. Arrives as a 400, + // which would read as a usage error; it is not the caller's invocation. + // A custom server-configured status message falls through to the 400 default + // — fail-soft, never a false classification. + case has("generation is currently disabled", "generation is disabled"): + return civitai.Tag(ErrGenerationDisabled, fmt.Errorf( + "generation is currently unavailable server-side: %s — this is not a problem with your credential or your invocation; try again later", shown)) + + // Muted account / incomplete onboarding. THESE are the real 403 victims: a + // bare FORBIDDEN that is byte-identical to a missing scope, which would send + // a restricted user round the `civitai login` loop forever. + case has("account has been restricted", "complete the onboarding"): + return civitai.Tag(ErrAccountRestricted, fmt.Errorf( + "your account cannot generate right now: %s — re-running `civitai login` will NOT help; resolve it on the website", shown)) + + // Unknown ecosystem is thrown server-side as a bare Error, so it arrives as a + // 500 and would exit 1 as an unclassified server fault. It is a client-side + // mistake in everything but the status code, so map it to usage (exit 2). + case apiErr.Status >= 500 && has("unknown ecosystem"): + return asUsageError(fmt.Errorf("unknown ecosystem: %s", shown)) + } + + // Everything else keeps its status-derived kind. Notably a 400 " is + // not enabled for generation" stays civitai.ErrBadRequest -> exit 2 rather + // than becoming ErrNotFound -> exit 4 (which the design doc floated with a + // question mark). Reason: exit 4 on this command already means "no such + // model-version id", produced locally and deterministically by the + // --checkpoint/--lora resolution before anything is submitted. A resource + // that resolved fine but is not currently generatable is a different + // condition — the ids exist, the COMBINATION is not runnable — and folding + // the two together would make exit 4 unactionable: a script could no longer + // tell "fix the id" from "pick a different resource". + return err +} diff --git a/internal/cmd/generate_charge_seam_test.go b/internal/cmd/generate_charge_seam_test.go new file mode 100644 index 00000000..14532347 --- /dev/null +++ b/internal/cmd/generate_charge_seam_test.go @@ -0,0 +1,148 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" +) + +// 🔴 The DEFAULT (waiting) path must print the realized charge. +// +// Delta-audit finding NEW-2 on PR #210: the renderer tests in +// generate_charge_test.go call printSubmitted DIRECTLY, so a mutant that makes +// the CALL SITE always pass a nil cost survived the entire package — the claim +// "the default path shows the charge" was asserted about the renderer, never +// about the path. This drives runGenerate down the real waiting path. +func TestGenerate_WaitingPathPrintsTheRealizedCharge(t *testing.T) { + withStdinTTY(t, false) + clock := newFakeClock() + var s genSeams + s.poll = clock.cfg() + s.submitReply = &genapi.SubmitResult{ + ID: "wf_123", Status: "queued", + Cost: &genapi.WorkflowCost{Total: 137}, + } + c, _, errOut := genCmd("") + + // 🔴 ORDERING, not just presence. Sampling stderr at the moment the FIRST + // poll runs is what makes "before the wait begins" an assertion rather than + // a comment — moving printSubmitted after waitAndCollect otherwise passes + // the whole suite, and a charge deferred until after a long wait is exactly + // the failure the user feels. + var stderrAtFirstPoll string + polls := 0 + s.getWorkflow = func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + if polls == 0 { + stderrAtFirstPoll = errOut.String() + } + polls++ + var wf genapi.Workflow + _ = json.Unmarshal([]byte(wfJSON(genapi.StatusFailed)), &wf) + return &wf, json.RawMessage(wfJSON(genapi.StatusFailed)), nil + } + + // A failed terminal status returns an error; the charge notice precedes it. + _ = runGenerate(c, s.deps(t), waitOpts(t.TempDir())) + + if polls == 0 { + t.Fatal("POSITIVE CONTROL FAILED: the poll seam was never reached, so the ordering assertion below is vacuous") + } + if !strings.Contains(errOut.String(), "137") { + t.Errorf("waiting path must print the realized charge 137 via runGenerate.\nstderr:\n%s", errOut.String()) + } + if !strings.Contains(errOut.String(), "Charged") { + t.Errorf("waiting path must label the charge.\nstderr:\n%s", errOut.String()) + } + if !strings.Contains(stderrAtFirstPoll, "Charged") { + t.Errorf("the charge must be printed BEFORE the wait begins; stderr at the first poll was:\n%s", stderrAtFirstPoll) + } +} + +// CONTRAST CONTROL for the test above: a submit reply with NO cost must print no +// charge line on the same path. Without this, an implementation that hardcoded a +// charge line would pass the test above. +func TestGenerate_WaitingPathNilCostPrintsNoCharge(t *testing.T) { + withStdinTTY(t, false) + clock := newFakeClock() + var s genSeams + s.poll = clock.cfg() + s.submitReply = &genapi.SubmitResult{ID: "wf_123", Status: "queued"} // no Cost + s.getWorkflow = func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + var wf genapi.Workflow + _ = json.Unmarshal([]byte(wfJSON(genapi.StatusFailed)), &wf) + return &wf, json.RawMessage(wfJSON(genapi.StatusFailed)), nil + } + + c, _, errOut := genCmd("") + _ = runGenerate(c, s.deps(t), waitOpts(t.TempDir())) + + if strings.Contains(errOut.String(), "Charged") { + t.Errorf("nil cost must not print a charge line on the waiting path.\nstderr:\n%s", errOut.String()) + } + if !strings.Contains(errOut.String(), "wf_123") { + t.Errorf("submission announcement lost.\nstderr:\n%s", errOut.String()) + } +} + +// 🔴 Ctrl-C DURING the submit round trip must STILL warn about a possible charge. +// +// Delta-audit finding NEW-1 on PR #210. An earlier revision returned early on +// ctx.Err() != nil, which suppressed this warning for every cancellation — but +// ctx.Err() cannot distinguish "cancelled before the POST" (microseconds, no +// charge possible) from "cancelled mid-flight" (up to the submit timeout, charge +// entirely possible). This is the case that regression made silent, and it is +// the dominant one: a slow orchestrator hop is exactly why a user hits Ctrl-C. +// +// The cancel fires inside the submit seam, so the spend gate has provably been +// passed and the seam entered (submitCalls == 1). +// +// ⚠️ Honest limit, measured: this fixture does NOT discriminate mid-flight +// cancellation from pre-entry cancellation. runGenerate performs no context +// check between entry and the submit seam, so both produce byte-identical +// output — cancelling before runGenerate leaves this test passing. It is kept +// because the SCENARIO is the one that matters, not because the fixture proves +// the bytes were written; distinguishing the two would need an httptrace +// WroteRequest seam the client does not expose. +func TestGenerate_CancelDuringSubmitStillWarnsAboutAPossibleCharge(t *testing.T) { + withStdinTTY(t, false) + + ctx, cancel := context.WithCancel(context.Background()) + s := genSeams{ + submitErr: errors.New("context canceled"), + submitObserver: cancel, // cancels once the seam has been entered + } + o := baseOpts() + o.assumeYes = true + + c, _, errOut := genCmd("") + c.SetContext(ctx) + if err := runGenerate(c, s.deps(t), o); err == nil { + t.Fatal("cancel during submit: want an error, got nil") + } + if s.submitCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: submit seam reached %d times, want 1", s.submitCalls) + } + if !strings.Contains(errOut.String(), "MAY still have been accepted") { + t.Errorf("cancel during the submit must still warn about a possible charge.\nstderr:\n%s", errOut.String()) + } + // 🔴 STRUCTURAL, not spelled: assert the externalId VALUE, not the flag name. + // `Contains(errOut, "--external-id")` matches even when the value behind it + // is empty, so blanking the interpolated id passed the whole suite — in the + // one case this warning exists to protect. + if s.lastExternalID == "" { + t.Fatal("POSITIVE CONTROL FAILED: no externalId was minted, so the assertion below cannot mean anything") + } + if !strings.Contains(errOut.String(), s.lastExternalID) { + t.Errorf("the externalId VALUE %q must appear — this is the only surface that hands it back, and nothing reads the crash-recovery record.\nstderr:\n%s", + s.lastExternalID, errOut.String()) + } + // The wording must acknowledge the interruption rather than claiming the + // server was silent, since we cannot observe whether the bytes were written. + if !strings.Contains(errOut.String(), "interrupted") { + t.Errorf("a cancelled submit should say it was interrupted.\nstderr:\n%s", errOut.String()) + } +} diff --git a/internal/cmd/generate_charge_test.go b/internal/cmd/generate_charge_test.go new file mode 100644 index 00000000..6a434191 --- /dev/null +++ b/internal/cmd/generate_charge_test.go @@ -0,0 +1,152 @@ +package cmd + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" +) + +// The realized charge must be visible on the DEFAULT (waiting) path, not only on +// --no-wait. The user approves an ESTIMATE and this command's whole spend story +// is that the realized cost can exceed it with no refund, so the number that +// settles what actually happened cannot be reachable only via a flag. +// +// Audit finding 🟡#1 on PR #210: `Charged:` had exactly one call site, inside +// printSubmitResult, which the waiting path never reaches. +func TestPrintSubmitted_ShowsTheRealizedCharge(t *testing.T) { + var buf bytes.Buffer + printSubmitted(&buf, "wf_123", "ext-1", "https://civitai.com", + &genapi.WorkflowCost{Total: 137}) + + got := buf.String() + if !strings.Contains(got, "137") { + t.Errorf("waiting path must print the realized charge 137; got:\n%s", got) + } + if !strings.Contains(got, "Charged") { + t.Errorf("waiting path must label the charge; got:\n%s", got) + } +} + +// POSITIVE CONTROL for the test above: the same assertion must be able to see a +// DIFFERENT number, so a hardcoded "137" in the renderer could not pass. +func TestPrintSubmitted_ChargeIsTheServersNumber(t *testing.T) { + var buf bytes.Buffer + printSubmitted(&buf, "wf_123", "ext-1", "https://civitai.com", + &genapi.WorkflowCost{Total: 9}) + if !strings.Contains(buf.String(), "9") { + t.Errorf("charge line must echo the server's number; got:\n%s", buf.String()) + } + if strings.Contains(buf.String(), "137") { + t.Errorf("charge line is not reading the cost it was given; got:\n%s", buf.String()) + } +} + +// A nil cost means the server reported none. Print NOTHING rather than a +// fabricated "Charged 0 Buzz" — a false zero on a money line is worse than +// silence, and is the same failure `unwrapTRPC`'s null-rejection exists to stop. +func TestPrintSubmitted_NilCostPrintsNoChargeLine(t *testing.T) { + var buf bytes.Buffer + printSubmitted(&buf, "wf_123", "ext-1", "https://civitai.com", nil) + got := buf.String() + if strings.Contains(got, "Charged") { + t.Errorf("nil cost must not print a charge line; got:\n%s", got) + } + if strings.Contains(got, " 0 Buzz") { + t.Errorf("nil cost must never render as 0 Buzz; got:\n%s", got) + } + // It still has to announce the submission and the re-attach handle. + if !strings.Contains(got, "wf_123") || !strings.Contains(got, "ext-1") { + t.Errorf("submission announcement lost; got:\n%s", got) + } +} + +// A cancelled context still warns — it just says "interrupted". +// +// 🔴 This test previously asserted the OPPOSITE (that a cancelled context must +// stay silent), and that revision was a money-safety regression: ctx.Err() +// cannot tell "cancelled before the POST" from "cancelled mid-flight", so +// suppressing on cancellation went silent in the window where the charge is +// real. See TestGenerate_CancelDuringSubmitStillWarnsAboutAPossibleCharge. +// +// The uncertainty belongs in the MESSAGE, not in the control flow: we cannot +// observe whether the request bytes were written, so we always warn, and the +// wording acknowledges the interruption instead of claiming the server was +// silent. +func TestGenerate_CancelledContextWarnsAsInterrupted(t *testing.T) { + withStdinTTY(t, false) + s := genSeams{submitErr: errors.New("context canceled")} + o := baseOpts() + o.assumeYes = true + + ctx, cancel := context.WithCancel(context.Background()) + cancel() // cancelled before the submit + + c, _, errOut := genCmd("") + c.SetContext(ctx) + err := runGenerate(c, s.deps(t), o) + if err == nil { + t.Fatal("cancelled context: want an error, got nil") + } + if !strings.Contains(errOut.String(), "MAY still have been accepted") { + t.Errorf("a cancelled submit must still warn about a possible charge — silence strands the user.\nstderr:\n%s", errOut.String()) + } + if !strings.Contains(errOut.String(), "interrupted") { + t.Errorf("a cancelled submit should be worded as interrupted, not as server silence.\nstderr:\n%s", errOut.String()) + } + if !strings.Contains(errOut.String(), "--external-id") { + t.Errorf("the externalId must be handed back — this is the only surface that does.\nstderr:\n%s", errOut.String()) + } +} + +// CONTRAST: a lost reply on a LIVE context uses the "no answer" wording, not the +// interrupted wording. Pins that the two cases are distinguishable in the text. +func TestGenerate_LostReplyOnLiveContextSaysNoAnswer(t *testing.T) { + withStdinTTY(t, false) + s := genSeams{submitErr: errors.New("EOF")} + o := baseOpts() + o.assumeYes = true + + c, _, errOut := genCmd("") + if err := runGenerate(c, s.deps(t), o); err == nil { + t.Fatal("lost reply: want an error, got nil") + } + if !strings.Contains(errOut.String(), "got no answer from the server") { + t.Errorf("a live-context lost reply should say the server gave no answer.\nstderr:\n%s", errOut.String()) + } + if strings.Contains(errOut.String(), "interrupted") { + t.Errorf("a live-context lost reply must not claim interruption.\nstderr:\n%s", errOut.String()) + } +} + +// A lost reply on a LIVE context must hand back the externalId VALUE. +// +// This was previously labelled a "positive control" for a negative test that no +// longer exists (the one asserting cancellation stays silent, deleted because it +// pinned a regression). It earns its place on its own: it is the structural +// externalId assertion for the non-cancelled branch, complementing the +// wording contrast in TestGenerate_LostReplyOnLiveContextSaysNoAnswer. +func TestGenerate_LostReplyHandsBackTheExternalID(t *testing.T) { + withStdinTTY(t, false) + s := genSeams{submitErr: errors.New("EOF")} // no HTTP status, live context + o := baseOpts() + o.assumeYes = true + + c, _, errOut := genCmd("") + if err := runGenerate(c, s.deps(t), o); err == nil { + t.Fatal("lost reply: want an error, got nil") + } + if !strings.Contains(errOut.String(), "MAY still have been accepted") { + t.Fatalf("a lost reply on a LIVE context must warn about a possible charge.\nstderr:\n%s", errOut.String()) + } + // Structural, not spelled — see the note in generate_charge_seam_test.go. + if s.lastExternalID == "" { + t.Fatal("POSITIVE CONTROL FAILED: no externalId was minted, so the assertion below is vacuous") + } + if !strings.Contains(errOut.String(), s.lastExternalID) { + t.Errorf("the externalId VALUE %q must appear in the warning.\nstderr:\n%s", s.lastExternalID, errOut.String()) + } +} diff --git a/internal/cmd/generate_input.go b/internal/cmd/generate_input.go new file mode 100644 index 00000000..0e6cf15b --- /dev/null +++ b/internal/cmd/generate_input.go @@ -0,0 +1,235 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "sort" + "strings" + + "github.com/civitai/cli/internal/genapi" +) + +// inputWorkflow is the ONLY workflow `--input` accepts in this release. +// +// 🔴 This gate is a CONTENT-AUDIT guard, not a feature-completeness placeholder. +// The server audits prompts at `'prompt' in data && typeof data.prompt === +// 'string'` (civitai/civitai -> +// src/server/services/orchestrator/orchestration-new.service.ts), and the `data` +// it tests is REBUILT FROM DECLARED GRAPH NODES ONLY. A graph that carries its +// prompt somewhere other than a top-level `prompt` string node — a comfy graph's +// embedded node inputs, a nested step input — is therefore exactly the shape +// that reaches the generator with its prompt never having been seen by the +// audit. Whether that is actually exploitable is an OPEN question upstream +// (design doc §10 q4: "SUSPECTED; neither review resolved it"). Until it is +// closed, a general-purpose raw-graph CLI would be the vector that turns a +// suspected server-side gap into a shipped one, so `--input` is pinned to +// txt2img — whose prompt IS the declared top-level `prompt` node the audit +// reads. Lift this only when the upstream question is answered, not when the +// next workflow "looks like it would work". +const inputWorkflow = generateWorkflow + +// envelopeOnlyKeys are the keys the tRPC generate MUTATION destructures out of +// the wrapper AROUND the graph — they are siblings of `input`, never members of +// it (civitai/civitai -> src/server/routers/orchestrator.router.ts, +// `generateFromGraph`). +// +// 🔴 THIS IS A MONEY GUARD. `civitaiTip` and `creatorTip` are real Buzz, and the +// cost pre-flight structurally CANNOT see them: whatIf prices a strictly smaller +// body than a submit and is never sent tips at all, so `--dry-run` on a file +// carrying `civitaiTip: 5000` shows the untipped estimate and the submit charges +// the tip anyway. A `--max-cost` check compares against that same blind +// estimate. +// +// The whole set is listed, not just the two that cost money: `buzzType` selects +// WHICH balance is spent, `externalId` is the idempotency key this CLI mints and +// records itself (a file-supplied one would silently re-attach to — or collide +// with — an unrelated workflow), `tags`/`sourceMetadata`/`sourceMetadataMap`/ +// `remixOfId` are provenance the CLI does not author, and a top-level `input` +// means the file is a saved ENVELOPE rather than a graph, which would nest the +// graph one level too deep and price the server's default job instead. +var envelopeOnlyKeys = []string{ + "input", + "civitaiTip", + "creatorTip", + "tags", + "buzzType", + "externalId", + "sourceMetadata", + "sourceMetadataMap", + "remixOfId", +} + +// parsedGraphInput is a validated `--input` document. +type parsedGraphInput struct { + // raw is the graph, byte-for-byte as supplied (compacted). It is passed + // through UNCHANGED so keys this CLI does not model still reach the server — + // which is the entire point of the flag. + raw json.RawMessage + // unknownKeys are top-level keys the CLI's own Graph does not model, sorted. + // They are a WARNING, never a refusal. + unknownKeys []string +} + +// readGraphInput reads the `--input` document from a file, or from stdin when +// path is "-". +func readGraphInput(stdin io.Reader, path string) ([]byte, error) { + if strings.TrimSpace(path) == "-" { + if stdin == nil { + return nil, asUsageError(fmt.Errorf("--input - reads the graph from stdin, but this command has no stdin attached")) + } + b, err := io.ReadAll(stdin) + if err != nil { + return nil, fmt.Errorf("read --input from stdin: %w", err) + } + return b, nil + } + b, err := os.ReadFile(path) + if err != nil { + // A missing/unreadable path is the user's mistake, not the server's. + return nil, asUsageError(fmt.Errorf("read --input %s: %w", path, err)) + } + return b, nil +} + +// parseGraphInput validates a raw `--input` document and returns the graph to +// send plus the keys the CLI could not recognise. +// +// The order of the checks is deliberate: REFUSALS first (malformed, envelope +// keys, non-txt2img), and only then the advisory unknown-key survey. A file that +// is going to be refused must not first be annotated with warnings about it. +func parseGraphInput(data []byte) (*parsedGraphInput, error) { + if len(strings.TrimSpace(string(data))) == 0 { + return nil, asUsageError(fmt.Errorf("--input is empty — expected a generation-graph JSON object, e.g. the output of `civitai generate \"a cat\" --print-input`")) + } + + var obj map[string]json.RawMessage + if err := json.Unmarshal(data, &obj); err != nil { + return nil, asUsageError(fmt.Errorf( + "--input is not a JSON object: %w — expected a generation graph like {\"workflow\":\"%s\",\"prompt\":\"…\"}; produce a valid starting point with `civitai generate \"a cat\" --print-input`", + err, inputWorkflow)) + } + + // 🔴 Envelope keys are REFUSED, never stripped. See the comment on + // envelopeOnlyKeys for what they cost. A strip-and-warn would be a silent + // override of an explicit instruction in the user's own file, delivered on a + // stream (stderr) that an unattended run routinely discards — so the one + // case that most needs to be seen is the one least likely to be. Refusing is + // unmissable, costs the user one edit, and cannot be clicked through. It is + // also this repo's house answer to an impossible flag combination + // (validateDownloadFlags rejects six of them rather than defining subtle + // merges). + var found []string + for _, k := range envelopeOnlyKeys { + if _, ok := obj[k]; ok { + found = append(found, k) + } + } + if len(found) > 0 { + return nil, asUsageError(fmt.Errorf( + "--input contains %s, which %s NOT part of the generation graph: %s %s beside the graph in the request envelope, and this CLI owns %s. "+ + "Tips (civitaiTip/creatorTip) are real Buzz that the cost estimate cannot see, so a file setting one would charge more than --dry-run showed. "+ + "Remove %s from the file", + joinQuoted(found), + plural(len(found), "is", "are"), + plural(len(found), "it", "they"), + plural(len(found), "belongs", "belong"), + plural(len(found), "it", "them"), + plural(len(found), "it", "them"))) + } + + // 🔴 txt2img only. See inputWorkflow. + rawWorkflow, ok := obj["workflow"] + if !ok { + return nil, asUsageError(fmt.Errorf( + "--input has no \"workflow\" key — this CLI only submits %q graphs, and it will not let the server pick a default it cannot verify. Add \"workflow\": %q", + inputWorkflow, inputWorkflow)) + } + var workflow string + if err := json.Unmarshal(rawWorkflow, &workflow); err != nil { + return nil, asUsageError(fmt.Errorf( + "--input has a non-string \"workflow\" value (%s) — expected %q", strings.TrimSpace(string(rawWorkflow)), inputWorkflow)) + } + if workflow != inputWorkflow { + return nil, asUsageError(fmt.Errorf( + "--input declares workflow %q, but this CLI only submits %q. Other workflows (img2img, video, comfy, …) are not supported yet: their prompts do not always live in the top-level \"prompt\" node the server's content audit reads, and this CLI will not be the path that bypasses it", + safeTerm(workflow), inputWorkflow)) + } + + // Advisory only. The CLI reports what IT does not recognise; it does not + // vendor the server's node registry to decide what is valid (design §5's + // anti-mirror rule — the platform owns ~51 ecosystem graphs, and a vendored + // copy would go stale and start refusing valid new nodes). + known := genapi.KnownGraphKeys() + var unknown []string + for k := range obj { + if !known[k] { + unknown = append(unknown, k) + } + } + sort.Strings(unknown) + + // Compact so the recorded payload hash and the outgoing body do not depend + // on the file's whitespace. + compact, err := compactJSON(data) + if err != nil { + return nil, asUsageError(fmt.Errorf("--input is not valid JSON: %w", err)) + } + return &parsedGraphInput{raw: compact, unknownKeys: unknown}, nil +} + +// unknownKeyWarning renders the advisory for keys the CLI does not model, or "" +// when there are none. +// +// 🔴 The wording is a statement about THIS CLI'S OWN KNOWLEDGE, not about the +// key's validity, and it must stay one. The CLI has no authority to say whether +// the server accepts a key — it does not vendor the node registry, and the +// platform's ~51 ecosystem graphs declare far more nodes than the five flags +// model. What it CAN say, and what the user needs, is: this key is being sent +// verbatim, nothing here checked it, and the server's failure mode for a key it +// does not declare is to DROP IT SILENTLY at HTTP 200 — measured: `foobar:123` +// returns 200, prices identically, and the parameter simply vanishes. So a typo +// costs money and produces a job that ran without it, with no error anywhere. +func unknownKeyWarning(keys []string) string { + if len(keys) == 0 { + return "" + } + return fmt.Sprintf( + "--input carries %s that this CLI does not recognise and therefore cannot verify: %s. %s sent to the server as-is. "+ + "This is NOT a claim that %s invalid — the server declares many more graph nodes than this CLI models. "+ + "But the server SILENTLY IGNORES keys it does not declare: an unrecognised key returns HTTP 200, prices the same, and simply has no effect, so a typo here costs Buzz and produces a job that ran without it. Check the spelling against the graph you copied it from", + plural(len(keys), "a key", "keys"), joinQuoted(keys), + plural(len(keys), "It is", "They are"), plural(len(keys), "it is", "they are")) +} + +// compactJSON validates and whitespace-normalises a JSON document. json.Compact +// is used rather than a RawMessage round-trip: unmarshalling into a RawMessage +// copies the bytes VERBATIM (interior whitespace and all) and so normalises +// nothing, which would leave the recorded payload hash sensitive to how the file +// happened to be indented. +func compactJSON(data []byte) (json.RawMessage, error) { + var buf bytes.Buffer + if err := json.Compact(&buf, data); err != nil { + return nil, err + } + return json.RawMessage(buf.Bytes()), nil +} + +// joinQuoted renders a key list as `"a", "b"`. +func joinQuoted(keys []string) string { + q := make([]string, 0, len(keys)) + for _, k := range keys { + q = append(q, fmt.Sprintf("%q", safeTerm(k))) + } + return strings.Join(q, ", ") +} + +// plural picks the singular or plural form for n. +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} diff --git a/internal/cmd/generate_input_test.go b/internal/cmd/generate_input_test.go new file mode 100644 index 00000000..8a68c05b --- /dev/null +++ b/internal/cmd/generate_input_test.go @@ -0,0 +1,601 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" +) + +// --- harness ----------------------------------------------------------------- + +// writeGraphFile writes a --input document into a temp dir and returns its path. +func writeGraphFile(t *testing.T, body string) string { + t.Helper() + p := filepath.Join(t.TempDir(), "graph.json") + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatalf("write graph fixture: %v", err) + } + return p +} + +// inputOpts is a valid minimal --input invocation: no prompt, --no-wait so the +// case stops at the submit seam, --yes so the money prompt is not the subject. +func inputOpts(path string) generateOpts { + return generateOpts{ + inputPath: path, + baseURL: "https://civitai.com", + noWait: true, + assumeYes: true, + outDir: ".", + } +} + +const cleanGraph = `{"workflow":"txt2img","prompt":"a cat","quantity":2}` + +// --- happy paths ------------------------------------------------------------- + +// The graph in the file is what reaches the whatIf seam, verbatim — including a +// key this CLI does not model. Round-tripping through the typed Graph would +// delete it, which would make --input strictly worse than useless: the user's +// parameter would vanish before the request was even built. +func TestGenerateInput_FileIsSentVerbatim(t *testing.T) { + path := writeGraphFile(t, `{ + "workflow": "txt2img", + "prompt": "a cat", + "someFutureNode": {"shift": 3} + }`) + s := &genSeams{} + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), inputOpts(path)); err != nil { + t.Fatalf("--input: %v", err) + } + if s.whatIfCalls != 1 || s.submitCalls != 1 { + t.Fatalf("whatIf=%d submit=%d, want 1/1", s.whatIfCalls, s.submitCalls) + } + raw, err := json.Marshal(s.lastGraph) + if err != nil { + t.Fatalf("marshal captured graph: %v", err) + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatalf("captured graph is not an object: %v", err) + } + for _, k := range []string{"workflow", "prompt", "someFutureNode"} { + if _, ok := m[k]; !ok { + t.Errorf("key %q from the input file never reached the wire: %v", k, m) + } + } + // No model-version resolution happens on this path: there is nothing typed + // to resolve. + if s.resolveCalls != 0 { + t.Errorf("--input resolved %d model versions; it does not interpret the graph", s.resolveCalls) + } +} + +func TestGenerateInput_StdinIsAccepted(t *testing.T) { + s := &genSeams{} + c, _, _ := genCmd(cleanGraph) + if err := runGenerate(c, s.deps(t), inputOpts("-")); err != nil { + t.Fatalf("--input -: %v", err) + } + if s.submitCalls != 1 { + t.Fatalf("submit calls = %d, want 1", s.submitCalls) + } + if s.lastGraph.Raw == nil || !strings.Contains(string(s.lastGraph.Raw), `"a cat"`) { + t.Errorf("the stdin graph did not reach the seam: %s", s.lastGraph.Raw) + } +} + +// --- refusals ---------------------------------------------------------------- + +func TestGenerateInput_MalformedJSONIsAUsageError(t *testing.T) { + for name, body := range map[string]string{ + "truncated": `{"workflow":"txt2img",`, + "not-object": `["txt2img"]`, + "scalar": `42`, + "empty": " \n", + } { + t.Run(name, func(t *testing.T) { + s := &genSeams{} + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, body))) + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 { + t.Errorf("a malformed graph reached the network: whatIf=%d submit=%d", s.whatIfCalls, s.submitCalls) + } + }) + } +} + +func TestGenerateInput_MissingFileIsAUsageError(t *testing.T) { + s := &genSeams{} + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), inputOpts(filepath.Join(t.TempDir(), "nope.json"))) + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage, got %v", err) + } +} + +// 🔴 The content-audit gate. A graph whose workflow is anything but txt2img is +// refused because the server's prompt audit is keyed on a top-level `prompt` +// string node and rebuilds its `data` from DECLARED nodes only — a graph +// carrying its prompt elsewhere is the shape that could slip it. Until that is +// resolved upstream this CLI must not be the vector. +func TestGenerateInput_NonTxt2ImgWorkflowIsRefused(t *testing.T) { + // 🔴 Each case asserts THIS branch's own message, not merely "some error". + // Measured while mutation-testing the gate: with the presence check and the + // type check individually defeated, every case still came back ErrUsage — + // the equality check catches them all, because an absent or non-string + // `workflow` leaves the decoded value "" and "" != "txt2img". A test that + // asserted only the kind was therefore green for the wrong reason on two of + // the three branches, and would have passed with either deleted. + cases := []struct { + name string + body string + want string + }{ + {"img2img", `{"workflow":"img2img","prompt":"a cat"}`, `declares workflow "img2img"`}, + {"comfy", `{"workflow":"comfy","nodes":{"3":{"inputs":{"text":"a cat"}}}}`, `declares workflow "comfy"`}, + {"txt2vid", `{"workflow":"txt2vid","prompt":"a cat"}`, `declares workflow "txt2vid"`}, + {"absent", `{"prompt":"a cat"}`, `has no "workflow" key`}, + {"non-string", `{"workflow":123,"prompt":"a cat"}`, `non-string "workflow" value`}, + {"case-variant", `{"workflow":"TXT2IMG","prompt":"a cat"}`, `declares workflow "TXT2IMG"`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := &genSeams{} + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, tc.body))) + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } + if !strings.Contains(err.Error(), tc.want) { + t.Errorf("the refusal came from a different guard than this case exercises\n want message containing: %s\n got: %v", tc.want, err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 { + t.Errorf("a non-txt2img graph reached the network: whatIf=%d submit=%d", s.whatIfCalls, s.submitCalls) + } + }) + } + // Positive control: the SAME path accepts txt2img and reaches the seams, so + // the zeros above are not a harness that never runs anything. + s := &genSeams{} + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, cleanGraph))); err != nil { + t.Fatalf("control txt2img run: %v", err) + } + if s.whatIfCalls != 1 || s.submitCalls != 1 { + t.Fatalf("control: whatIf=%d submit=%d, want 1/1", s.whatIfCalls, s.submitCalls) + } +} + +// --- the envelope-key money guard -------------------------------------------- + +// envelopeMoneyKeys reports which envelope-only keys are present at the TOP +// level of a tRPC generate body's `json` object — i.e. as SIBLINGS of the graph, +// where the server destructures them and where a tip would actually be charged. +// +// It deliberately does not look inside `json.input`: a key sitting inside the +// graph is inert (the server drops undeclared graph nodes), and conflating the +// two would make the guard fire on a harmless payload while still missing the +// dangerous one. +func envelopeMoneyKeys(t *testing.T, body []byte) []string { + t.Helper() + var outer map[string]any + if err := json.Unmarshal(body, &outer); err != nil { + t.Fatalf("submit body is not JSON: %v\n%s", err, body) + } + inner, ok := outer["json"].(map[string]any) + if !ok { + t.Fatalf("submit body has no \"json\" wrapper: %v", outer) + } + // 🔴 This list is written out HERE rather than read from envelopeOnlyKeys. + // Deriving it from the production constant would make the detector shrink in + // lockstep with the very list it is meant to police: dropping a key from + // production would silently stop the detector looking for it, and this test + // would go green on the exact regression it exists to catch. (Measured: with + // the detector reading envelopeOnlyKeys, deleting "civitaiTip" from + // production left this assertion unable to see a civitaiTip.) + // + // `input` and `externalId` are deliberately absent: `input` IS the graph and + // `externalId` is the idempotency key the CLI mints itself, so both are + // CORRECT on this envelope. A file-supplied value for either is stopped + // earlier, by the refusal test's guard. + forbidden := []string{"civitaiTip", "creatorTip", "buzzType", "tags", + "sourceMetadata", "sourceMetadataMap", "remixOfId"} + var found []string + for _, k := range forbidden { + if _, ok := inner[k]; ok { + found = append(found, k) + } + } + return found +} + +// 🔴 A ledger of the envelope siblings the server destructures, asserted as an +// exact SET so it fails when it grows OR shrinks. +// +// Growth matters because a new sibling added server-side is a new key that must +// be refused in an input file; shrinkage matters because deleting one from the +// production list silently reopens the hole. The source of truth is +// `generateFromGraph`'s destructure in +// civitai/civitai -> src/server/routers/orchestrator.router.ts. +func TestEnvelopeOnlyKeys_Ledger(t *testing.T) { + want := map[string]bool{ + "input": true, "civitaiTip": true, "creatorTip": true, "tags": true, + "sourceMetadata": true, "sourceMetadataMap": true, "remixOfId": true, + "buzzType": true, "externalId": true, + } + got := map[string]bool{} + for _, k := range envelopeOnlyKeys { + got[k] = true + } + for k := range want { + if !got[k] { + t.Errorf("envelopeOnlyKeys no longer refuses %q — a graph file could set it again", k) + } + } + for k := range got { + if !want[k] { + t.Errorf("envelopeOnlyKeys gained %q; confirm it against the server's generateFromGraph destructure and update this ledger", k) + } + } +} + +// 🔴 The headline money guard, asserted on the ACTUAL bytes of the outgoing +// request, with a positive control that proves the assertion can see a tip. +// +// A committed graph.json carrying `civitaiTip: 5000` must not charge a tip. And +// note WHY --dry-run cannot backstop this: whatIf prices a strictly smaller body +// than submit and is never sent tips at all, so the estimate would be the +// untipped one and --max-cost would compare against it. +func TestGenerateInput_EnvelopeKeysNeverReachTheWire(t *testing.T) { + // --- positive control: the detector CAN observe a tip ------------------- + tipped := []byte(`{"json":{"input":{"workflow":"txt2img"},"externalId":"x","civitaiTip":5000,"creatorTip":10}}`) + got := envelopeMoneyKeys(t, tipped) + if len(got) != 2 { + t.Fatalf("positive control: the detector found %v in a body that carries civitaiTip AND creatorTip — it cannot observe a tip, so the assertion below would be vacuous", got) + } + + // --- the real request --------------------------------------------------- + var submitBody []byte + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == genapi.WhatIfPath: + _, _ = w.Write([]byte(`{"result":{"data":{"json":{"ready":true,"cost":{"base":8,"total":12}}}}}`)) + case r.Method == http.MethodPost && r.URL.Path == genapi.GeneratePath: + b, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("read submit body: %v", err) + } + submitBody = b + _, _ = w.Write([]byte(`{"result":{"data":{"json":{"id":"wf_1","status":"queued"}}}}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + gen := genapi.New(srv.URL, "test-key") + deps := generateDeps{ + whatIf: gen.WhatIfFromGraph, + submit: gen.GenerateFromGraph, + buzzBalance: func(ctx context.Context) (int64, error) { return 1_000_000, nil }, + pendingDir: t.TempDir(), + } + // A graph that ALSO happens to name a graph key — the request must still + // carry no envelope tip. + c, _, _ := genCmd("") + if err := runGenerate(c, deps, inputOpts(writeGraphFile(t, cleanGraph))); err != nil { + t.Fatalf("submit: %v", err) + } + if len(submitBody) == 0 { + t.Fatal("the submit body was never captured — the assertion below would be vacuous") + } + if found := envelopeMoneyKeys(t, submitBody); len(found) != 0 { + t.Fatalf("envelope-only keys reached the outgoing request: %v\n%s", found, submitBody) + } +} + +// A file carrying an envelope-only key is REFUSED, not stripped. Stripping would +// silently override an explicit instruction in the user's own file, and the +// warning would go to a stream an unattended run discards. +func TestGenerateInput_EnvelopeKeyInTheFileIsRefused(t *testing.T) { + for _, k := range []string{"civitaiTip", "creatorTip", "buzzType", "tags", "externalId", + "sourceMetadata", "sourceMetadataMap", "remixOfId", "input"} { + t.Run(k, func(t *testing.T) { + body := fmt.Sprintf(`{"workflow":"txt2img","prompt":"a cat",%q:5000}`, k) + s := &genSeams{} + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, body))) + if !errors.Is(err, ErrUsage) { + t.Fatalf("%q must be refused with ErrUsage, got %v", k, err) + } + if !strings.Contains(err.Error(), k) { + t.Errorf("the error does not name the offending key %q: %v", k, err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 { + t.Errorf("a graph carrying %q reached the network: whatIf=%d submit=%d", k, s.whatIfCalls, s.submitCalls) + } + }) + } +} + +// --- the unknown-key warning ------------------------------------------------- + +// It WARNS and does not block: the CLI does not vendor the server's node +// registry, so it has no authority to call a key invalid — only to say it does +// not recognise it. +func TestGenerateInput_UnknownKeyWarnsAndProceeds(t *testing.T) { + s := &genSeams{} + c, _, errb := genCmd("") + err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, + `{"workflow":"txt2img","prompt":"a cat","shift":3,"foobar":123}`))) + if err != nil { + t.Fatalf("an unknown key must not block: %v", err) + } + if s.submitCalls != 1 { + t.Fatalf("submit calls = %d, want 1 — the warning must not stop the run", s.submitCalls) + } + stderr := errb.String() + for _, want := range []string{"shift", "foobar", "does not recognise", "SILENTLY IGNORES"} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + } + // 🔴 Framing: a statement about the CLI's own knowledge, never a verdict on + // the key. Claiming the key is invalid would be a mirror of a registry this + // CLI deliberately does not vendor. + for _, forbidden := range []string{"invalid key", "unsupported key", "is not a valid"} { + if strings.Contains(strings.ToLower(stderr), forbidden) { + t.Errorf("the warning asserts the key is invalid (%q); it may only report that the CLI cannot verify it:\n%s", forbidden, stderr) + } + } +} + +// Negative control: every key the CLI models must produce NO warning, or the +// advisory becomes noise everyone learns to ignore. +func TestGenerateInput_KnownKeysDoNotWarn(t *testing.T) { + s := &genSeams{} + c, _, errb := genCmd("") + body := `{"workflow":"txt2img","ecosystem":"SDXL","prompt":"a cat","negativePrompt":"blurry", + "quantity":2,"aspectRatio":"1:1","model":{"id":1},"resources":[],"steps":25,"cfgScale":7, + "sampler":"Euler","seed":42}` + if err := runGenerate(c, s.deps(t), inputOpts(writeGraphFile(t, body))); err != nil { + t.Fatalf("--input: %v", err) + } + if strings.Contains(errb.String(), "does not recognise") { + t.Errorf("a graph of only modelled keys produced an unknown-key warning:\n%s", errb.String()) + } +} + +// The warning message itself, exercised directly with both controls, so the +// "no warning" assertion above cannot pass because the renderer is inert. +func TestUnknownKeyWarning_Controls(t *testing.T) { + if got := unknownKeyWarning(nil); got != "" { + t.Errorf("no unknown keys must render no warning, got %q", got) + } + got := unknownKeyWarning([]string{"shift"}) + if got == "" { + t.Fatal("positive control: one unknown key rendered no warning — the empty case above proves nothing") + } + if !strings.Contains(got, `"shift"`) { + t.Errorf("the warning does not name the key: %s", got) + } +} + +// --- mutual exclusion -------------------------------------------------------- + +func TestGenerateInput_RejectsContentFlags(t *testing.T) { + path := writeGraphFile(t, cleanGraph) + cases := map[string]func(*generateOpts){ + "prompt argument": func(o *generateOpts) { o.prompt = "a cat" }, + "--negative-prompt": func(o *generateOpts) { o.negativePrompt = "blurry" }, + "--quantity": func(o *generateOpts) { o.quantity, o.quantitySet = 4, true }, + "--aspect-ratio": func(o *generateOpts) { o.aspectRatio = "1:1" }, + "--checkpoint": func(o *generateOpts) { o.checkpoint, o.checkpointSet = 128713, true }, + "--lora": func(o *generateOpts) { o.loras = []string{"250712:0.8"} }, + } + for name, apply := range cases { + t.Run(name, func(t *testing.T) { + o := inputOpts(path) + apply(&o) + s := &genSeams{} + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if !errors.Is(err, ErrUsage) { + t.Fatalf("--input with %s must be ErrUsage, got %v", name, err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 { + t.Errorf("the rejected combination still reached the network: whatIf=%d submit=%d", s.whatIfCalls, s.submitCalls) + } + }) + } +} + +// The execution flags stay valid with --input: they govern HOW the request is +// made, never what is in the graph. If this ever regressed, --input would become +// unusable in exactly the scripted contexts it exists for. +func TestGenerateInput_ExecutionFlagsAreAllowed(t *testing.T) { + path := writeGraphFile(t, cleanGraph) + cases := map[string]func(*generateOpts){ + "--dry-run": func(o *generateOpts) { o.dryRun = true }, + "--max-cost": func(o *generateOpts) { o.maxCost, o.maxCostSet = 1000, true }, + "--json+--yes": func(o *generateOpts) { o.jsonOut = true }, + "--force": func(o *generateOpts) { o.force = true }, + "--out-dir": func(o *generateOpts) { o.outDir = "./out" }, + "--external-id": func(o *generateOpts) { o.externalID = "reuse-me" }, + "--timeout": func(o *generateOpts) { o.timeout = 0 }, + } + for name, apply := range cases { + t.Run(name, func(t *testing.T) { + o := inputOpts(path) + apply(&o) + s := &genSeams{} + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--input with %s must be accepted, got %v", name, err) + } + if s.whatIfCalls != 1 { + t.Errorf("whatIf calls = %d, want 1", s.whatIfCalls) + } + }) + } +} + +// --- --print-input ----------------------------------------------------------- + +// 🔴 --print-input must reach NO money seam: not the submit, and not even the +// estimator. The zeros are paired with a positive control in the same test that +// drives both counters to 1. +func TestPrintInput_MakesNoNetworkCall(t *testing.T) { + s := &genSeams{} + c, out, _ := genCmd("") + o := baseOpts() + o.printInput = true + o.quantity, o.quantitySet = 2, true + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--print-input: %v", err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 || s.resolveCalls != 0 || s.balanceCalls != 0 { + t.Fatalf("--print-input made network calls: whatIf=%d submit=%d resolve=%d balance=%d", + s.whatIfCalls, s.submitCalls, s.resolveCalls, s.balanceCalls) + } + + var m map[string]any + if err := json.Unmarshal(out.Bytes(), &m); err != nil { + t.Fatalf("--print-input stdout is not JSON: %v\n%s", err, out.String()) + } + if m["workflow"] != generateWorkflow || m["prompt"] != o.prompt || m["quantity"] != float64(2) { + t.Errorf("printed graph = %v", m) + } + // The envelope siblings are CLI-owned and must NOT be printed: --input + // refuses them, so emitting them would produce a document that cannot be fed + // back in. + for _, k := range []string{"externalId", "civitaiTip", "creatorTip", "tags", "input"} { + if _, ok := m[k]; ok { + t.Errorf("--print-input emitted the envelope key %q, which --input then refuses: %v", k, m) + } + } + + // --- positive control: the SAME counters move on a normal run ----------- + s2 := &genSeams{} + c2, _, _ := genCmd("") + control := baseOpts() + control.assumeYes = true + if err := runGenerate(c2, s2.deps(t), control); err != nil { + t.Fatalf("control run: %v", err) + } + if s2.whatIfCalls != 1 || s2.submitCalls != 1 { + t.Fatalf("control: whatIf=%d submit=%d, want 1/1 — the zeros above would otherwise prove nothing", + s2.whatIfCalls, s2.submitCalls) + } +} + +// The one network call --print-input CAN make, stated rather than hidden: with +// --checkpoint/--lora it still performs the public model-version READ, because +// graph `resources[]` REQUIRE the model type and a bare {id} is rejected 400. +// Skipping it would print a document --input could not submit. No MONEY seam is +// touched either way — that is the property that matters. +func TestPrintInput_ResolvesVersionIdsButTouchesNoMoneySeam(t *testing.T) { + s := &genSeams{} + c, out, _ := genCmd("") + o := baseOpts() + o.printInput = true + o.checkpoint, o.checkpointSet = 128713, true + o.loras = []string{"250712:0.8"} + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--print-input: %v", err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 || s.balanceCalls != 0 { + t.Fatalf("--print-input reached a money seam: whatIf=%d submit=%d balance=%d", + s.whatIfCalls, s.submitCalls, s.balanceCalls) + } + if s.resolveCalls != 2 { + t.Fatalf("version resolutions = %d, want 2 (checkpoint + lora) — the printed graph would otherwise lack model.type", s.resolveCalls) + } + var m map[string]any + if err := json.Unmarshal(out.Bytes(), &m); err != nil { + t.Fatalf("--print-input stdout is not JSON: %v\n%s", err, out.String()) + } + res, _ := m["resources"].([]any) + if len(res) != 1 { + t.Fatalf("printed graph has no resources: %v", m) + } + first, _ := res[0].(map[string]any) + if first["model"] == nil { + t.Errorf("the printed LoRA carries no model.type; --input would submit it and get a 400: %v", first) + } +} + +// The round-trip the flag exists for: --print-input's output must be accepted by +// --input unchanged. A guard on the two halves agreeing, not on either alone. +func TestPrintInput_OutputRoundTripsThroughInput(t *testing.T) { + s := &genSeams{} + c, out, _ := genCmd("") + o := baseOpts() + o.printInput = true + o.negativePrompt = "blurry" + o.aspectRatio = "1:1" + o.quantity, o.quantitySet = 3, true + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--print-input: %v", err) + } + printed := out.String() + + s2 := &genSeams{} + c2, _, errb2 := genCmd(printed) + if err := runGenerate(c2, s2.deps(t), inputOpts("-")); err != nil { + t.Fatalf("--print-input output was rejected by --input: %v\n%s", err, printed) + } + if strings.Contains(errb2.String(), "does not recognise") { + t.Errorf("--print-input emitted a key --input does not recognise:\n%s\n%s", printed, errb2.String()) + } + if s2.submitCalls != 1 { + t.Fatalf("round-trip submit calls = %d, want 1", s2.submitCalls) + } +} + +// --print-input with --input echoes the file after validating it, still without +// touching the network — which is how a user checks a hand-edited graph. +func TestPrintInput_WithInputValidatesAndEchoes(t *testing.T) { + s := &genSeams{} + c, out, _ := genCmd("") + o := inputOpts(writeGraphFile(t, `{"workflow":"txt2img","prompt":"a cat","someFutureNode":{"shift":3}}`)) + o.printInput = true + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--input --print-input: %v", err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 { + t.Fatalf("--input --print-input made network calls: whatIf=%d submit=%d", s.whatIfCalls, s.submitCalls) + } + if !strings.Contains(out.String(), "someFutureNode") { + t.Errorf("the echoed graph lost an unmodelled key:\n%s", out.String()) + } + + // It still REFUSES a bad graph rather than printing it: --print-input is a + // preview of what would be sent, and nothing is sent for a refused file. + c2, out2, _ := genCmd("") + o2 := inputOpts(writeGraphFile(t, `{"workflow":"img2img","prompt":"a cat"}`)) + o2.printInput = true + if err := runGenerate(c2, (&genSeams{}).deps(t), o2); !errors.Is(err, ErrUsage) { + t.Fatalf("--print-input must not launder a refused graph, got %v", err) + } + if out2.Len() != 0 { + t.Errorf("a refused graph was printed anyway: %s", out2.String()) + } +} diff --git a/internal/cmd/generate_output.go b/internal/cmd/generate_output.go new file mode 100644 index 00000000..483c8195 --- /dev/null +++ b/internal/cmd/generate_output.go @@ -0,0 +1,209 @@ +package cmd + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "strings" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" + "github.com/civitai/cli/pkg/civitai" +) + +// blobFetcher issues a GET for one presigned output URL and returns the open +// response for streaming; the caller closes the body. +// +// 🔴 It is wired to civitai.Client.DownloadPresigned, NOT DownloadFile. Blob +// URLs are presigned — they carry their own authorization and need no bearer +// token — and they are served from a *.civitai.com host, which +// isTrustedDownloadHost treats as trusted. So DownloadFile would attach the +// user's FULL-SCOPE personal API key to a request that does not need it. See +// the PresignedDownloader doc in pkg/civitai for why this is a separate seam +// rather than a weakened predicate. +type blobFetcher func(ctx context.Context, fileURL string) (*http.Response, error) + +// safeExtension bounds an extension taken from a SERVER-supplied URL: a leading +// dot and 1-8 alphanumerics. Anything else is replaced with .bin rather than +// pasted into a filename. +var safeExtension = regexp.MustCompile(`^\.[A-Za-z0-9]{1,8}$`) + +// blobExtension derives an output file's extension from its URL path. +// +// It is deliberately derived from the URL and not from the response's +// Content-Type: the target path has to be known BEFORE the request, so that a +// collision with an existing file is refused without any bytes moving (and +// without burning a presigned URL that is already counting down to expiry). +func blobExtension(rawURL string) string { + u, err := url.Parse(rawURL) + if err != nil { + return ".bin" + } + ext := path.Ext(u.Path) + if !safeExtension.MatchString(ext) { + return ".bin" + } + return strings.ToLower(ext) +} + +// blobFileName builds `-.`. +// +// The workflow id is SERVER-supplied, so it is reduced to a bare basename and +// rejected if it degenerates — the same rule `civitai download` applies to +// server-supplied file names, for the same reason: a value like "../../.bashrc" +// must never be able to write outside the chosen directory. +func blobFileName(workflowID string, n int, rawURL string) (string, error) { + base := filepath.Base(strings.TrimSpace(workflowID)) + if base == "" || base == "." || base == ".." || base == string(filepath.Separator) || base == "/" { + return "", fmt.Errorf("the server returned an unusable workflow id %q — cannot build an output filename", workflowID) + } + return fmt.Sprintf("%s-%d%s", base, n, blobExtension(rawURL)), nil +} + +// reportExcludedOutputs prints, per excluded output, WHY it is not being saved. +// +// 🔴 This is not decoration. A `succeeded` workflow can carry outputs that are +// moderation-blocked, never landed, or user-hidden, and the CLI must not filter +// them out silently: the visible symptom of doing so is "the command said it +// worked and I got two files instead of the four I paid for", with nothing on +// screen explaining the gap. +func reportExcludedOutputs(errw io.Writer, excluded []genapi.Output) { + if len(excluded) == 0 { + return + } + st := ui.For(errw) + fmt.Fprintln(errw, st.Warn(fmt.Sprintf( + "%d output(s) will NOT be saved — they are not deliverable results:", len(excluded)))) + for _, o := range excluded { + fmt.Fprintf(errw, " - %s: %s\n", safeTerm(dashIfEmpty(o.ID)), safeTerm(genapi.ExclusionReason(o))) + } + fmt.Fprintln(errw, st.Dim( + "These were still part of the workflow you were charged for — a blocked or missing output is not refunded.")) +} + +// reportOutputCountMismatch warns when fewer deliverable outputs came back than +// were asked for. requested <= 0 means the user did not pass --quantity, so +// there is no number to compare against and nothing is claimed. +func reportOutputCountMismatch(errw io.Writer, requested, delivered int) { + if requested <= 0 || delivered == requested { + return + } + fmt.Fprintln(errw, ui.For(errw).Warn(fmt.Sprintf( + "you asked for %d output(s) and %d are deliverable — the difference was charged for either way", + requested, delivered))) +} + +// blobStatusError maps a non-2xx blob fetch to an actionable error. +// +// It is separate from downloadStatusError (the model-file one) because the +// remedies are different: a blob URL is PRESIGNED and short-lived, so a 401/403 +// here means the signature expired or was never valid — `civitai login` is not +// the answer, re-reading the workflow for a fresh URL is. +func blobStatusError(status int, name string) (err error) { + defer func() { err = civitai.TagStatus(status, err) }() + switch { + case status >= 200 && status < 300: + return nil + case status == http.StatusUnauthorized || status == http.StatusForbidden: + return fmt.Errorf("the download link for %s was refused (HTTP %d) — output URLs are presigned and expire, so this usually means the link went stale; re-read the workflow with `civitai workflows get ` to get fresh links", name, status) + case status == http.StatusNotFound: + return fmt.Errorf("the download link for %s returned 404 — the output may have expired or been removed", name) + default: + return fmt.Errorf("download of %s failed (HTTP %d)", name, status) + } +} + +// downloadBlobTo streams one presigned URL to target. +// +// It deliberately reuses the existing machinery rather than reimplementing it: +// the transport (SSRF dial guard, https-per-redirect-hop, hop cap) comes from +// pkg/civitai via the fetcher, and the on-disk half — stale-.part self-heal, +// progress meter, cleanup-on-failure, atomic rename — is writePart, the same +// function `civitai download` uses. A fresh downloader would have discarded all +// of it. +func downloadBlobTo(ctx context.Context, fetch blobFetcher, out, errw io.Writer, fileURL, target string, force bool) error { + name := filepath.Base(target) + if !force { + if info, err := os.Stat(target); err == nil && !info.IsDir() { + return fmt.Errorf("refusing to overwrite the existing file %s — pass --force to replace it, or --out-dir to write somewhere else", target) + } + } + if dir := filepath.Dir(target); dir != "" && dir != "." { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create output directory %s: %w", dir, err) + } + } + + resp, err := fetch(ctx, fileURL) + if err != nil { + return fmt.Errorf("download %s: %w", name, err) + } + defer resp.Body.Close() + if err := blobStatusError(resp.StatusCode, name); err != nil { + return err + } + + partPath := target + ".part" + written, _, err := writePart(resp.Body, partPath, errw, name, resp.ContentLength, false) + if err != nil { + return err + } + if err := os.Rename(partPath, target); err != nil { + _ = os.Remove(partPath) + return fmt.Errorf("install %s: %w", target, err) + } + fmt.Fprintf(out, "Saved %s (%s)\n", safeTerm(target), humanBytes(written)) + return nil +} + +// downloadOutputs writes every deliverable output into outDir as +// `-.` and returns the paths written. +// +// Target collisions are checked for EVERY file before the first byte moves, the +// same fail-safe ordering `civitai download` uses: a run that would overwrite an +// existing result must not first spend half the presigned URLs' remaining life +// downloading the ones that happened to come earlier. +func downloadOutputs(ctx context.Context, fetch blobFetcher, out, errw io.Writer, workflowID string, outputs []genapi.Output, outDir string, force bool) ([]string, error) { + type job struct { + url string + target string + } + jobs := make([]job, 0, len(outputs)) + for i, o := range outputs { + if o.URL == nil || strings.TrimSpace(*o.URL) == "" { + return nil, fmt.Errorf("output %s is marked available but carries no URL — nothing to download", safeTerm(dashIfEmpty(o.ID))) + } + name, err := blobFileName(workflowID, i+1, *o.URL) + if err != nil { + return nil, err + } + jobs = append(jobs, job{url: *o.URL, target: filepath.Join(outDir, name)}) + } + if !force { + var clashes []string + for _, j := range jobs { + if info, err := os.Stat(j.target); err == nil && !info.IsDir() { + clashes = append(clashes, j.target) + } + } + if len(clashes) > 0 { + return nil, fmt.Errorf("refusing to overwrite %d existing file(s):\n %s\nPass --force to replace them, or --out-dir to write somewhere else", + len(clashes), strings.Join(clashes, "\n ")) + } + } + + written := make([]string, 0, len(jobs)) + for _, j := range jobs { + if err := downloadBlobTo(ctx, fetch, out, errw, j.url, j.target, force); err != nil { + return written, err + } + written = append(written, j.target) + } + return written, nil +} diff --git a/internal/cmd/generate_output_test.go b/internal/cmd/generate_output_test.go new file mode 100644 index 00000000..68af5451 --- /dev/null +++ b/internal/cmd/generate_output_test.go @@ -0,0 +1,468 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/pkg/civitai" +) + +// blobServer serves image bytes for any path and records the Authorization +// header of every request it sees. +func blobServer(t *testing.T, seen *[]string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *seen = append(*seen, r.Header.Get("Authorization")) + _, _ = io.WriteString(w, "image-bytes-"+filepath.Base(r.URL.Path)) + })) + t.Cleanup(srv.Close) + return srv +} + +// presignedFetcher wires the real credential-free downloader at a loopback +// httptest server (plain http, so private hosts must be allowed). +func presignedFetcher(t *testing.T, baseURL, token string) blobFetcher { + t.Helper() + c := civitai.New(baseURL, token) + c.AllowPrivateDownloadHosts = true + return c.DownloadPresigned +} + +// succeededWorkflow builds a succeeded workflow whose step yields n available +// image outputs served by srv. +func succeededWorkflow(srvURL string, n int) *genapi.Workflow { + imgs := make([]string, 0, n) + for i := 0; i < n; i++ { + imgs = append(imgs, `{"id":"blob`+string(rune('a'+i))+`","type":"image","available":true,"url":"`+srvURL+`/o/`+string(rune('a'+i))+`.jpeg"}`) + } + payload := `{"id":"wf_123","status":"succeeded","steps":[{"$type":"textToImage","name":"s","status":"succeeded","metadata":{},"output":{"images":[` + + strings.Join(imgs, ",") + `]}}]}` + var wf genapi.Workflow + if err := json.Unmarshal([]byte(payload), &wf); err != nil { + panic(err) + } + return &wf +} + +// --- 🔴 the credential guard, at the COMMAND layer --------------------------- + +// The command's blob fetcher must reach the blob host with NO Authorization +// header — paired, in this same test, with a positive control proving the +// recorder can see one. +// +// The hazardous configuration is reproduced deliberately: the token is +// non-empty and the base URL EQUALS the blob host, so the trusted-host +// predicate would attach the key if the wrong seam were wired. +func TestDownloadOutputs_SendsNoAuthorizationHeader(t *testing.T) { + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + + wf := succeededWorkflow(srv.URL, 2) + kept, _ := genapi.PartitionOutputs(wf) + if len(kept) != 2 { + t.Fatalf("fixture: %d deliverable outputs, want 2", len(kept)) + } + + paths, err := downloadOutputs(context.Background(), presignedFetcher(t, srv.URL, "secret-api-key"), + io.Discard, io.Discard, "wf_123", kept, dir, false) + if err != nil { + t.Fatalf("downloadOutputs: %v", err) + } + if len(paths) != 2 { + t.Fatalf("wrote %d files, want 2", len(paths)) + } + if len(seen) != 2 { + t.Fatalf("the server saw %d requests, want 2", len(seen)) + } + for i, h := range seen { + if h != "" { + t.Errorf("blob request %d carried a credential: Authorization = %q", i, h) + } + } + + // POSITIVE CONTROL: the SAME recorder, the SAME server, the SAME token — + // via the token-attaching path. Without this, "0 auth headers" is + // indistinguishable from a recorder wired to nothing. + c := civitai.New(srv.URL, "secret-api-key") + c.AllowPrivateDownloadHosts = true + resp, err := c.DownloadFile(context.Background(), srv.URL+"/o/a.jpeg") + if err != nil { + t.Fatalf("positive control fetch: %v", err) + } + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + if len(seen) != 3 { + t.Fatalf("the server saw %d requests after the control, want 3", len(seen)) + } + if !strings.Contains(seen[2], "Bearer secret-api-key") { + t.Fatalf("POSITIVE CONTROL FAILED: the authenticated fetch sent Authorization = %q — "+ + "the recorder cannot observe the header, so the empty values above prove nothing", seen[2]) + } +} + +// --- download behaviour ------------------------------------------------------ + +func TestDownloadOutputs_HappyPathNamesFilesByWorkflowAndIndex(t *testing.T) { + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + kept, _ := genapi.PartitionOutputs(succeededWorkflow(srv.URL, 3)) + + var out bytes.Buffer + paths, err := downloadOutputs(context.Background(), presignedFetcher(t, srv.URL, ""), &out, io.Discard, "wf_123", kept, dir, false) + if err != nil { + t.Fatalf("downloadOutputs: %v", err) + } + want := []string{"wf_123-1.jpeg", "wf_123-2.jpeg", "wf_123-3.jpeg"} + for i, p := range paths { + if filepath.Base(p) != want[i] { + t.Errorf("file %d = %s, want %s", i, filepath.Base(p), want[i]) + } + if _, err := os.Stat(p); err != nil { + t.Errorf("%s not on disk: %v", p, err) + } + if _, err := os.Stat(p + ".part"); !os.IsNotExist(err) { + t.Errorf("a .part survived next to %s", p) + } + } + if !strings.Contains(out.String(), "Saved") { + t.Errorf("no save line printed: %q", out.String()) + } +} + +// A collision must be refused BEFORE any bytes move — a presigned URL is +// expiring while the command dithers, and a half-done overwrite is worse than a +// clean refusal. +func TestDownloadOutputs_CollisionWithoutForceRefusesBeforeAnyTransfer(t *testing.T) { + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + kept, _ := genapi.PartitionOutputs(succeededWorkflow(srv.URL, 2)) + + // Pre-create the SECOND target, so a per-file loop would already have + // fetched the first before noticing. + existing := filepath.Join(dir, "wf_123-2.jpeg") + if err := os.WriteFile(existing, []byte("keep me"), 0o600); err != nil { + t.Fatal(err) + } + + _, err := downloadOutputs(context.Background(), presignedFetcher(t, srv.URL, ""), io.Discard, io.Discard, "wf_123", kept, dir, false) + if err == nil { + t.Fatal("collision without --force: want a refusal, got nil") + } + if !strings.Contains(err.Error(), "--force") { + t.Errorf("the refusal must name --force: %v", err) + } + if len(seen) != 0 { + t.Errorf("the collision check ran AFTER %d transfer(s) — it must run first", len(seen)) + } + if b, _ := os.ReadFile(existing); string(b) != "keep me" { + t.Errorf("the existing file was modified: %q", b) + } + if _, err := os.Stat(filepath.Join(dir, "wf_123-1.jpeg")); !os.IsNotExist(err) { + t.Error("no file should have been written") + } +} + +func TestDownloadOutputs_ForceOverwrites(t *testing.T) { + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + kept, _ := genapi.PartitionOutputs(succeededWorkflow(srv.URL, 1)) + + target := filepath.Join(dir, "wf_123-1.jpeg") + if err := os.WriteFile(target, []byte("stale"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := downloadOutputs(context.Background(), presignedFetcher(t, srv.URL, ""), io.Discard, io.Discard, "wf_123", kept, dir, true); err != nil { + t.Fatalf("--force: %v", err) + } + b, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + if string(b) == "stale" { + t.Error("--force did not overwrite the existing file") + } + if !strings.HasPrefix(string(b), "image-bytes") { + t.Errorf("unexpected content %q", b) + } +} + +// Cancelling mid-transfer (what Ctrl-C does through signal.NotifyContext) must +// leave neither a truncated final file nor a stray .part. +func TestDownloadBlobTo_CancelCleansThePartFile(t *testing.T) { + streaming := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "1000000") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "partial") + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + close(streaming) + <-r.Context().Done() + })) + defer srv.Close() + + dir := t.TempDir() + target := filepath.Join(dir, "wf_123-1.jpeg") + fetch := presignedFetcher(t, srv.URL, "") + + ctx, cancel := context.WithCancel(context.Background()) + errc := make(chan error, 1) + go func() { + errc <- downloadBlobTo(ctx, fetch, io.Discard, io.Discard, srv.URL+"/o/a.jpeg", target, false) + }() + + <-streaming + cancel() + + if err := <-errc; err == nil { + t.Fatal("expected a cancellation error from the interrupted transfer") + } + if _, err := os.Stat(target + ".part"); !os.IsNotExist(err) { + t.Errorf(".part should be removed on cancel; stat err = %v", err) + } + if _, err := os.Stat(target); !os.IsNotExist(err) { + t.Errorf("no final file should exist on cancel; stat err = %v", err) + } +} + +// A non-2xx blob fetch must point at the EXPIRY remedy, not at `civitai login` — +// a presigned URL is not an auth problem. +func TestBlobStatusError_PointsAtTheExpiryRemedy(t *testing.T) { + err := blobStatusError(http.StatusForbidden, "wf_123-1.jpeg") + if err == nil { + t.Fatal("403 must be an error") + } + if !strings.Contains(err.Error(), "expire") || !strings.Contains(err.Error(), "civitai workflows get") { + t.Errorf("403 remedy = %v", err) + } + if strings.Contains(err.Error(), "civitai login") { + t.Errorf("a presigned-URL 403 must not send the user to login: %v", err) + } + if blobStatusError(http.StatusOK, "x") != nil { + t.Error("200 must not be an error") + } +} + +// The workflow id is server-supplied, so it must not be able to steer the write. +func TestBlobFileName_RejectsAHostileWorkflowId(t *testing.T) { + if _, err := blobFileName("/", 1, "https://x/a.jpeg"); err == nil { + t.Error("a degenerate workflow id must be rejected") + } + got, err := blobFileName("../../etc/passwd", 1, "https://x/a.jpeg") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if strings.ContainsRune(got, filepath.Separator) { + t.Errorf("a traversal in the workflow id survived into the filename: %q", got) + } + if got != "passwd-1.jpeg" { + t.Errorf("filename = %q, want passwd-1.jpeg", got) + } +} + +func TestBlobExtension(t *testing.T) { + cases := map[string]string{ + "https://x/a.jpeg?sig=1": ".jpeg", + "https://x/a.PNG": ".png", + "https://x/a": ".bin", + "https://x/a.": ".bin", + "https://x/a.verylongextens": ".bin", + "://nonsense": ".bin", + } + for in, want := range cases { + if got := blobExtension(in); got != want { + t.Errorf("blobExtension(%q) = %q, want %q", in, got, want) + } + } +} + +// --- filtering reported at the command layer --------------------------------- + +// A succeeded workflow with blocked/unavailable/hidden outputs must download +// only the deliverable ones AND say so, with the count mismatch called out. +func TestGenerate_FilteredOutputsAreReportedAndOnlyDeliverablesDownload(t *testing.T) { + withStdinTTY(t, false) + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + + payload := `{"id":"wf_123","status":"succeeded","steps":[{ + "$type":"textToImage","name":"s","status":"succeeded", + "metadata":{"output":{"c":{"hidden":true}}}, + "output":{"images":[ + {"id":"a","type":"image","available":true,"url":"` + srv.URL + `/o/a.jpeg"}, + {"id":"b","type":"image","available":true,"url":"` + srv.URL + `/o/b.jpeg","blockedReason":"minor"}, + {"id":"c","type":"image","available":true,"url":"` + srv.URL + `/o/c.jpeg"}, + {"id":"d","type":"image","available":false,"url":null} + ]}}]}` + + clock := newFakeClock() + calls := 0 + var s genSeams + s.poll = clock.cfg() + s.getWorkflow = scriptedWorkflows(&calls, payload) + s.downloadBlob = presignedFetcher(t, srv.URL, "tok") + + o := waitOpts(dir) + o.quantity, o.quantitySet = 4, true + + c, out, errb := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("generate: %v", err) + } + + // Exactly ONE file, from the one deliverable output. + entries, err := filepath.Glob(filepath.Join(dir, "*")) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || filepath.Base(entries[0]) != "wf_123-1.jpeg" { + t.Fatalf("files written = %v, want exactly [wf_123-1.jpeg]", entries) + } + if len(seen) != 1 { + t.Errorf("the blob host saw %d requests, want 1 — a blocked/hidden/unavailable output must never be fetched", len(seen)) + } + + stderr := errb.String() + // Each exclusion must be reported WITH its own reason. + for _, want := range []string{"3 output(s) will NOT be saved", "moderation", "minor", "hidden", "not available"} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + } + // And the count gap must be stated explicitly. + if !strings.Contains(stderr, "you asked for 4 output(s) and 1 are deliverable") { + t.Errorf("the count mismatch was not reported:\n%s", stderr) + } + if !strings.Contains(out.String(), "wf_123-1.jpeg") { + t.Errorf("stdout should name the saved file: %q", out.String()) + } +} + +// POSITIVE CONTROL for the filter: with the SAME wiring and no excluded +// outputs, all four download and neither warning is printed. A test that only +// ever sees the filtered case cannot tell "the filter works" from "downloading +// is broken". +func TestGenerate_UnfilteredWorkflowDownloadsEverythingAndWarnsNothing(t *testing.T) { + withStdinTTY(t, false) + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + + wf := succeededWorkflow(srv.URL, 4) + raw, _ := json.Marshal(wf) + clock := newFakeClock() + calls := 0 + var s genSeams + s.poll = clock.cfg() + s.getWorkflow = scriptedWorkflows(&calls, string(raw)) + s.downloadBlob = presignedFetcher(t, srv.URL, "tok") + + o := waitOpts(dir) + o.quantity, o.quantitySet = 4, true + + c, _, errb := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("generate: %v", err) + } + entries, _ := filepath.Glob(filepath.Join(dir, "*")) + if len(entries) != 4 { + t.Fatalf("POSITIVE CONTROL FAILED: %d files written, want 4 — if the happy path cannot write 4, the filtered case proves nothing", len(entries)) + } + if len(seen) != 4 { + t.Errorf("the blob host saw %d requests, want 4", len(seen)) + } + if strings.Contains(errb.String(), "will NOT be saved") { + t.Errorf("nothing was excluded, so no exclusion warning may print:\n%s", errb.String()) + } + if strings.Contains(errb.String(), "are deliverable") { + t.Errorf("the counts match, so no mismatch warning may print:\n%s", errb.String()) + } +} + +// --no-download waits and prints the URLs without touching the disk. +func TestGenerate_NoDownloadPrintsURLsAndWritesNothing(t *testing.T) { + withStdinTTY(t, false) + var seen []string + srv := blobServer(t, &seen) + dir := t.TempDir() + + wf := succeededWorkflow(srv.URL, 2) + raw, _ := json.Marshal(wf) + clock := newFakeClock() + calls := 0 + var s genSeams + s.poll = clock.cfg() + s.getWorkflow = scriptedWorkflows(&calls, string(raw)) + + o := waitOpts(dir) + o.noDownload = true + + c, out, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("generate: %v", err) + } + if len(seen) != 0 { + t.Errorf("--no-download fetched %d blob(s), want 0", len(seen)) + } + entries, _ := filepath.Glob(filepath.Join(dir, "*")) + if len(entries) != 0 { + t.Errorf("--no-download wrote %v", entries) + } + if !strings.Contains(out.String(), srv.URL+"/o/a.jpeg") { + t.Errorf("the output URLs should be on stdout: %q", out.String()) + } +} + +// A succeeded workflow whose every output was filtered out must FAIL — reporting +// success with no files is the exact silent degradation the filter exists to +// surface. +func TestGenerate_AllOutputsFilteredIsAnError(t *testing.T) { + withStdinTTY(t, false) + payload := `{"id":"wf_123","status":"succeeded","steps":[{ + "$type":"textToImage","name":"s","status":"succeeded","metadata":{}, + "output":{"images":[{"id":"a","type":"image","available":true,"url":"https://x/a.jpeg","blockedReason":"minor"}]}}]}` + clock := newFakeClock() + calls := 0 + var s genSeams + s.poll = clock.cfg() + s.getWorkflow = scriptedWorkflows(&calls, payload) + // Wire a fetcher that must never be called, rather than leaving it nil: a + // nil seam turns "the filter regressed" into a panic instead of a readable + // assertion failure. + fetched := 0 + s.downloadBlob = func(ctx context.Context, u string) (*http.Response, error) { + fetched++ + return nil, errors.New("no deliverable output should ever be fetched here") + } + + c, _, errb := genCmd("") + err := runGenerate(c, s.deps(t), waitOpts(t.TempDir())) + if err == nil { + t.Fatal("a workflow with no deliverable outputs must not report success") + } + if fetched != 0 { + t.Errorf("a blocked output was fetched %d time(s) — the filter did not exclude it", fetched) + } + if !strings.Contains(err.Error(), "charged") { + t.Errorf("the error must say it was charged: %v", err) + } + if !strings.Contains(errb.String(), "moderation") { + t.Errorf("the reason must still be reported:\n%s", errb.String()) + } +} diff --git a/internal/cmd/generate_state.go b/internal/cmd/generate_state.go new file mode 100644 index 00000000..9109d15c --- /dev/null +++ b/internal/cmd/generate_state.go @@ -0,0 +1,144 @@ +package cmd + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/civitai/cli/internal/config" +) + +// pendingGeneration is the crash-recovery record for a submit. +// +// 🔴 It is written BEFORE the POST, not after. The money moves SERVER-SIDE the +// moment the orchestrator accepts the workflow, so every window in which the +// process can die — the POST's own round trip, a slow reply, Ctrl-C two seconds +// in, an OOM — is a window in which the user has been charged and, without this +// file, holds no handle to what they bought. Writing it afterwards would record +// exactly the cases that did not need recording. +// +// The externalId is the durable handle: the orchestrator dedupes on +// (userId, externalId) and answers a duplicate with HTTP 200 and the PRE-EXISTING +// workflow — there is no 409 — so re-submitting with the same key re-attaches +// instead of charging again. That is why it is minted before the request rather +// than read out of the reply. +type pendingGeneration struct { + // ExternalID is the orchestrator idempotency key (see above). + ExternalID string `json:"externalId"` + // SubmittedAt is when the CLI was about to POST, in RFC3339. + SubmittedAt string `json:"submittedAt"` + // PayloadHash is the SHA-256 of the marshalled GRAPH. It exists so a + // re-attach can tell "the same job" from "a different job that reused the + // key" — the orchestrator would silently return the FIRST workflow either + // way, so a mismatch here is the only local signal that the key no longer + // describes what the user is asking for. + PayloadHash string `json:"payloadHash"` + // BaseURL records which server was charged. + BaseURL string `json:"baseUrl,omitempty"` + // WorkflowID is filled in once the submit replies. Empty means the reply + // never arrived — the run may still have been charged. + WorkflowID string `json:"workflowId,omitempty"` +} + +// pendingDirName is the subdirectory of the CLI config dir holding these +// records. +const pendingDirName = "pending" + +// pendingDir returns the directory for pending-generation records, creating it. +func pendingDir() (string, error) { + base, err := config.Dir() + if err != nil { + return "", err + } + dir := filepath.Join(base, pendingDirName) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", fmt.Errorf("create %s: %w", dir, err) + } + return dir, nil +} + +// graphPayloadHash returns the SHA-256 of v's JSON encoding, lowercase hex. +func graphPayloadHash(v any) string { + b, err := json.Marshal(v) + if err != nil { + // A graph that will not marshal cannot be submitted either; record the + // failure rather than a hash of nothing. + return "unhashable:" + err.Error() + } + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:]) +} + +// pendingPath is the record's on-disk path. The externalId is CLI-minted (a v4 +// UUID), but it can also be user-supplied via --external-id, so it is reduced to +// a bare basename before joining — a value like "../../config.yaml" must not be +// able to steer the write. +func pendingPath(dir, externalID string) (string, error) { + base := filepath.Base(strings.TrimSpace(externalID)) + if base == "" || base == "." || base == ".." || base == string(filepath.Separator) { + return "", fmt.Errorf("unusable external id %q", externalID) + } + return filepath.Join(dir, base+".json"), nil +} + +// writePendingGeneration writes the record atomically (temp file + rename, 0600) +// and returns its path. It takes the directory as an argument so tests write +// into a t.TempDir() rather than the user's real config dir. +func writePendingGeneration(dir string, p pendingGeneration) (string, error) { + path, err := pendingPath(dir, p.ExternalID) + if err != nil { + return "", err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", fmt.Errorf("create %s: %w", dir, err) + } + body, err := json.MarshalIndent(p, "", " ") + if err != nil { + return "", err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, append(body, '\n'), 0o600); err != nil { + return "", fmt.Errorf("write %s: %w", tmp, err) + } + if err := os.Rename(tmp, path); err != nil { + _ = os.Remove(tmp) + return "", fmt.Errorf("install %s: %w", path, err) + } + return path, nil +} + +// readPendingGeneration loads a record written by writePendingGeneration. +func readPendingGeneration(path string) (*pendingGeneration, error) { + raw, err := os.ReadFile(path) //nolint:gosec // path is CLI-constructed + if err != nil { + return nil, err + } + var p pendingGeneration + if err := json.Unmarshal(raw, &p); err != nil { + return nil, fmt.Errorf("unreadable pending-generation record %s: %w", path, err) + } + return &p, nil +} + +// recordPendingWorkflowID re-writes the record with the workflow id the submit +// returned, so the recovery hint can name a workflow and not just a key. +// Failures are returned but are never fatal to the caller: the generation has +// already been paid for and printing its ids matters more than the bookkeeping. +func recordPendingWorkflowID(path, workflowID string) error { + p, err := readPendingGeneration(path) + if err != nil { + return err + } + p.WorkflowID = workflowID + dir, _ := filepath.Split(path) + _, werr := writePendingGeneration(strings.TrimSuffix(dir, string(filepath.Separator)), *p) + return werr +} + +// nowRFC3339 is the timestamp seam (a package var so a test can pin it). +var nowRFC3339 = func() string { return time.Now().UTC().Format(time.RFC3339) } diff --git a/internal/cmd/generate_test.go b/internal/cmd/generate_test.go new file mode 100644 index 00000000..43a834b4 --- /dev/null +++ b/internal/cmd/generate_test.go @@ -0,0 +1,865 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/pkg/civitai" + "github.com/spf13/cobra" +) + +// --- harness ----------------------------------------------------------------- + +// genSeams is a recording stand-in for generateDeps. The counters are the point: +// the safety claims this command makes are all of the form "the submit seam was +// NEVER reached", and a bare zero from a counter nothing increments would look +// identical. Every test that reads submits==0 is paired with a case in this same +// file that drives the SAME counter to 1 (see +// TestGenerate_NonTTYWithoutYesRefusesAndNeverSubmits). +type genSeams struct { + whatIfCalls int + submitCalls int + resolveCalls int + balanceCalls int + + // lastGraph is the graph handed to whatIf — captured so a test can assert on + // the payload that would go over the wire. + lastGraph genapi.Graph + // lastExternalID is the idempotency key the submit seam was handed. It must + // be non-empty: the CLI mints it BEFORE the POST so it can be recorded. + lastExternalID string + + whatIf func(ctx context.Context, g genapi.Graph) (*genapi.WhatIfResult, json.RawMessage, error) + resolve func(ctx context.Context, id int) (*genapi.ResolvedVersion, error) + balance func(ctx context.Context) (int64, error) + submitErr error + submitReply *genapi.SubmitResult + submitRaw json.RawMessage + + // getWorkflow is the poll seam; nil leaves it unwired (fine for every test + // that stops at --no-wait or never reaches a submit). + getWorkflow getWorkflowFn + // downloadBlob is the credential-free blob fetcher. + downloadBlob blobFetcher + // poll overrides the poll cadence (a test must never really sleep). + poll pollConfig + // pendingDirOverride pins the crash-recovery record's directory. Left empty + // deps() points it at a t.TempDir(): a unit test must NEVER write into the + // developer's real ~/.config/civitai. + pendingDirOverride string + // submitObserver runs INSIDE the submit seam, which is what makes the + // "state file written BEFORE the POST" claim an ordering assertion rather + // than an existence one. + submitObserver func() +} + +// deps wires the seams into the struct runGenerate consumes. +func (s *genSeams) deps(t *testing.T) generateDeps { + t.Helper() + dir := s.pendingDirOverride + if dir == "" { + dir = t.TempDir() + } + return generateDeps{ + getWorkflow: s.getWorkflow, + downloadBlob: s.downloadBlob, + pendingDir: dir, + poll: s.poll, + whatIf: func(ctx context.Context, g genapi.Graph) (*genapi.WhatIfResult, json.RawMessage, error) { + s.whatIfCalls++ + s.lastGraph = g + if s.whatIf != nil { + return s.whatIf(ctx, g) + } + return okQuote(12), okQuoteRaw(12), nil + }, + submit: func(ctx context.Context, g genapi.Graph, opts genapi.SubmitOptions) (*genapi.SubmitResult, string, json.RawMessage, error) { + s.submitCalls++ + s.lastExternalID = opts.ExternalID + if s.submitObserver != nil { + s.submitObserver() + } + if s.submitErr != nil { + return nil, opts.ExternalID, nil, s.submitErr + } + r := s.submitReply + if r == nil { + r = &genapi.SubmitResult{ID: "wf_123", Status: "queued"} + } + raw := s.submitRaw + if raw == nil { + raw = json.RawMessage(`{"id":"wf_123","status":"queued"}`) + } + return r, opts.ExternalID, raw, nil + }, + resolveVersion: func(ctx context.Context, id int) (*genapi.ResolvedVersion, error) { + s.resolveCalls++ + if s.resolve != nil { + return s.resolve(ctx, id) + } + return &genapi.ResolvedVersion{VersionID: id, ModelName: "DreamShaper", VersionName: "v8", ModelType: "Checkpoint"}, nil + }, + buzzBalance: func(ctx context.Context) (int64, error) { + s.balanceCalls++ + if s.balance != nil { + return s.balance(ctx) + } + return 1_000_000, nil + }, + } +} + +func okQuote(total float64) *genapi.WhatIfResult { + return &genapi.WhatIfResult{Ready: true, Cost: &genapi.WorkflowCost{ + Base: 8, Total: total, Factors: map[string]float64{"quantity": 1.5}}} +} + +func okQuoteRaw(total float64) json.RawMessage { + return json.RawMessage(fmt.Sprintf(`{"ready":true,"cost":{"base":8,"total":%g,"factors":{"quantity":1.5}},"serverOnlyField":"kept"}`, total)) +} + +// genCmd builds a bare command with captured streams and a scripted stdin. +func genCmd(stdin string) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) { + c := &cobra.Command{} + var out, errb bytes.Buffer + c.SetOut(&out) + c.SetErr(&errb) + c.SetIn(strings.NewReader(stdin)) + return c, &out, &errb +} + +// baseOpts is a valid, minimal invocation. +// +// It sets --no-wait because these cases are about the SPEND GATE — what reaches +// the submit seam and what does not. The wait/poll/download half has its own +// tests (generate_wait_test.go, generate_output_test.go) which wire the poll +// seam explicitly. Leaving noWait off here would make every spend-gate case +// depend on an unrelated poll seam. +func baseOpts() generateOpts { + return generateOpts{ + prompt: "a cat wearing sunglasses", + baseURL: "https://civitai.com", + noWait: true, + outDir: ".", + } +} + +// --- the spend gate ---------------------------------------------------------- + +// 🔴 The headline safety property, WITH its own positive control. +// +// Case A asserts the submit seam is never reached in a non-interactive shell +// without --yes. On its own that assertion is worthless — a counter wired to +// nothing reads zero too. Case B drives the SAME counter, through the SAME deps +// constructor, to 1. Report the pair, never the zero alone. +func TestGenerate_NonTTYWithoutYesRefusesAndNeverSubmits(t *testing.T) { + withStdinTTY(t, false) + + // (A) negative: no --yes on a non-TTY. + var refuse genSeams + c, _, errb := genCmd("") + err := runGenerate(c, refuse.deps(t), baseOpts()) + if err == nil { + t.Fatal("non-TTY without --yes: want a refusal, got nil") + } + if refuse.submitCalls != 0 { + t.Errorf("non-TTY without --yes: submit called %d times, want 0", refuse.submitCalls) + } + // The refusal must name the three escapes so the message is actionable. + for _, want := range []string{"--yes", "--max-cost", "--dry-run"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("refusal does not mention %s: %v", want, err) + } + } + if strings.Contains(errb.String(), "[y/N]") { + t.Error("non-TTY must not print a prompt") + } + + // (B) POSITIVE CONTROL for the counter: identical wiring, --yes set. + var proceed genSeams + o := baseOpts() + o.assumeYes = true + c2, _, _ := genCmd("") + if err := runGenerate(c2, proceed.deps(t), o); err != nil { + t.Fatalf("positive control (--yes): %v", err) + } + if proceed.submitCalls != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: submit called %d times, want 1 — a 0 in case (A) proves nothing", proceed.submitCalls) + } +} + +// An interactive "n" cancels without submitting; the prompt is on STDERR so a +// piped stdout stays clean. +func TestGenerate_TTYDeclineCancels(t *testing.T) { + withStdinTTY(t, true) + var s genSeams + c, out, errb := genCmd("n\n") + err := runGenerate(c, s.deps(t), baseOpts()) + if err == nil || !strings.Contains(err.Error(), "cancelled") { + t.Fatalf("declined prompt: err = %v, want a cancellation", err) + } + if s.submitCalls != 0 { + t.Errorf("declined prompt: submit called %d times, want 0", s.submitCalls) + } + if !strings.Contains(errb.String(), "[y/N]") { + t.Errorf("confirmation prompt missing from stderr: %q", errb.String()) + } + if strings.Contains(out.String(), "[y/N]") { + t.Errorf("confirmation leaked to stdout: %q", out.String()) + } +} + +// An interactive "y" proceeds and prints the workflow id on stdout. +func TestGenerate_TTYAcceptSubmits(t *testing.T) { + withStdinTTY(t, true) + var s genSeams + c, out, _ := genCmd("y\n") + if err := runGenerate(c, s.deps(t), baseOpts()); err != nil { + t.Fatalf("accepted prompt: %v", err) + } + if s.submitCalls != 1 { + t.Fatalf("accepted prompt: submit called %d times, want 1", s.submitCalls) + } + if !strings.Contains(out.String(), "wf_123") { + t.Errorf("workflow id missing from stdout: %q", out.String()) + } +} + +// --max-cost below the estimate refuses locally, before any submit, and the exit +// code is pinned by errors.Is (never by the message). +func TestGenerate_MaxCostRefusesBelowEstimate(t *testing.T) { + withStdinTTY(t, true) + var s genSeams + o := baseOpts() + o.maxCost, o.maxCostSet = 5, true + c, _, _ := genCmd("y\n") + err := runGenerate(c, s.deps(t), o) + if err == nil { + t.Fatal("--max-cost below the estimate: want a refusal, got nil") + } + if !errors.Is(err, ErrUsage) { + t.Errorf("--max-cost refusal: want ErrUsage (exit 2), got %v", err) + } + if s.submitCalls != 0 { + t.Errorf("--max-cost refusal: submit called %d times, want 0", s.submitCalls) + } +} + +// --max-cost at or above the estimate does not block. +func TestGenerate_MaxCostAllowsAtOrAboveEstimate(t *testing.T) { + withStdinTTY(t, false) + var s genSeams + o := baseOpts() + o.maxCost, o.maxCostSet, o.assumeYes = 12, true, true + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--max-cost == estimate: %v", err) + } + if s.submitCalls != 1 { + t.Errorf("--max-cost == estimate: submit called %d times, want 1", s.submitCalls) + } +} + +// A cost above the balance stops before submitting, and is NOT an auth failure — +// a script must not be sent round the `civitai login` loop for being broke. +func TestGenerate_InsufficientBalanceStopsEarly(t *testing.T) { + var s genSeams + s.balance = func(context.Context) (int64, error) { return 3, nil } + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if !errors.Is(err, ErrInsufficientBuzz) { + t.Fatalf("cost > balance: want ErrInsufficientBuzz, got %v", err) + } + if errors.Is(err, civitai.ErrUnauthorized) { + t.Error("cost > balance must NOT classify as an auth failure (exit 3)") + } + if s.submitCalls != 0 { + t.Errorf("cost > balance: submit called %d times, want 0", s.submitCalls) + } +} + +// An unreadable balance is advisory: warn, keep going, and never print a number +// (an unknown balance shown as 0 reads as "you are broke"). +func TestGenerate_UnreadableBalanceWarnsAndContinues(t *testing.T) { + var s genSeams + s.balance = func(context.Context) (int64, error) { return 0, errors.New("boom") } + o := baseOpts() + o.assumeYes = true + c, _, errb := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("unreadable balance: %v", err) + } + if s.submitCalls != 1 { + t.Errorf("unreadable balance: submit called %d times, want 1", s.submitCalls) + } + if !strings.Contains(errb.String(), "could not read your Buzz balance") { + t.Errorf("missing balance warning on stderr: %q", errb.String()) + } +} + +// --- dry run ----------------------------------------------------------------- + +func TestGenerate_DryRunNeverSubmits(t *testing.T) { + withStdinTTY(t, true) + var s genSeams + o := baseOpts() + o.dryRun = true + c, out, _ := genCmd("y\n") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--dry-run: %v", err) + } + if s.submitCalls != 0 { + t.Errorf("--dry-run: submit called %d times, want 0", s.submitCalls) + } + if s.balanceCalls != 0 { + t.Errorf("--dry-run must not need the balance, called %d times", s.balanceCalls) + } + for _, want := range []string{"Estimated cost", "total", "quantity"} { + if !strings.Contains(out.String(), want) { + t.Errorf("--dry-run output missing %q:\n%s", want, out.String()) + } + } +} + +// --dry-run --json passes the SERVER's payload through on stdout, verbatim — +// including fields this CLI does not model — and prints nothing else there. +func TestGenerate_DryRunJSONEmitsRawPayloadOnStdout(t *testing.T) { + var s genSeams + o := baseOpts() + o.dryRun, o.jsonOut = true, true + c, out, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--dry-run --json: %v", err) + } + if s.submitCalls != 0 { + t.Fatalf("--dry-run --json: submit called %d times, want 0", s.submitCalls) + } + var m map[string]any + if err := json.Unmarshal(out.Bytes(), &m); err != nil { + t.Fatalf("stdout is not pure JSON (%v):\n%s", err, out.String()) + } + if m["serverOnlyField"] != "kept" { + t.Errorf("raw passthrough dropped an unmodelled server field: %v", m) + } +} + +// --- payload shape ----------------------------------------------------------- + +// 🔴 An unset flag must be ABSENT from the JSON, not a Go zero value: the server +// accepts quantity 0 and silently clamps it rather than erroring. Asserted on a +// decoded map, never with strings.Contains (which cross-matches prefixes). +func TestGenerate_UnsetFlagsAreAbsentFromThePayload(t *testing.T) { + var s genSeams + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("runGenerate: %v", err) + } + raw, err := json.Marshal(s.lastGraph) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + for _, key := range []string{"quantity", "negativePrompt", "aspectRatio", "model", "resources", "steps", "cfgScale", "sampler", "seed"} { + if _, ok := m[key]; ok { + t.Errorf("unset flag produced key %q in the payload: %s", key, raw) + } + } + // Positive control: a key that IS set must be present, or the absence + // assertions above could pass against an empty object. + if m["prompt"] != "a cat wearing sunglasses" { + t.Fatalf("POSITIVE CONTROL FAILED: prompt missing from payload: %s", raw) + } + if m["workflow"] != generateWorkflow { + t.Fatalf("POSITIVE CONTROL FAILED: workflow missing from payload: %s", raw) + } +} + +// Set flags land in the payload with the resolved resource shape. +func TestGenerate_SetFlagsArePresent(t *testing.T) { + var s genSeams + s.resolve = func(_ context.Context, id int) (*genapi.ResolvedVersion, error) { + typ := "Checkpoint" + if id == 250712 { + typ = "LORA" + } + return &genapi.ResolvedVersion{VersionID: id, ModelName: "M", VersionName: "v1", ModelType: typ}, nil + } + o := baseOpts() + o.assumeYes = true + o.quantity, o.quantitySet = 4, true + o.negativePrompt = "blurry" + o.aspectRatio = "1:1" + o.checkpoint, o.checkpointSet = 128713, true + o.loras = []string{"250712:0.8"} + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("runGenerate: %v", err) + } + raw, _ := json.Marshal(s.lastGraph) + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatal(err) + } + if m["quantity"] != float64(4) || m["negativePrompt"] != "blurry" || m["aspectRatio"] != "1:1" { + t.Errorf("set flags missing/wrong: %s", raw) + } + res, ok := m["resources"].([]any) + if !ok || len(res) != 1 { + t.Fatalf("resources missing: %s", raw) + } + entry := res[0].(map[string]any) + if entry["id"] != float64(250712) || entry["strength"] != 0.8 { + t.Errorf("lora entry wrong: %s", raw) + } + // 🔴 model:{type} is REQUIRED on a resources[] entry — a bare {id} is a 400. + model, ok := entry["model"].(map[string]any) + if !ok || model["type"] != "LORA" { + t.Errorf("resource entry lacks the required model.type: %s", raw) + } +} + +// --- --lora parsing ---------------------------------------------------------- + +func TestParseLoraFlag(t *testing.T) { + strengthOf := func(t *testing.T, spec loraSpec) float64 { + t.Helper() + if spec.strength == nil { + t.Fatal("expected a strength, got nil") + } + return *spec.strength + } + + spec, err := parseLoraFlag("250712") + if err != nil { + t.Fatalf("bare id: %v", err) + } + if spec.versionID != 250712 { + t.Errorf("bare id: got %d", spec.versionID) + } + if spec.strength != nil { + // Unset strength must stay ABSENT so the server applies its own default. + t.Errorf("bare id must not invent a strength, got %v", *spec.strength) + } + + spec, err = parseLoraFlag("123:0.8") + if err != nil { + t.Fatalf("id:strength: %v", err) + } + if spec.versionID != 123 || strengthOf(t, spec) != 0.8 { + t.Errorf("id:strength parsed wrong: %+v", spec) + } + + if spec, err := parseLoraFlag(" 123 : -0.5 "); err != nil || strengthOf(t, spec) != -0.5 { + // Negative strengths are meaningful to the generator; whitespace is not. + t.Errorf("whitespace/negative: spec=%+v err=%v", spec, err) + } + + for _, bad := range []string{"", " ", "abc", "123:", ":0.8", "123:abc", "123:0.8:0.9", "0", "-1", "1e3"} { + if _, err := parseLoraFlag(bad); err == nil { + t.Errorf("--lora %q: want a usage error, got nil", bad) + } else if !errors.Is(err, ErrUsage) { + t.Errorf("--lora %q: want ErrUsage, got %v", bad, err) + } + } +} + +// A nonexistent version id must fail LOCALLY, before the estimate and before any +// submit — that is the whole point of resolving it (the generator would have +// accepted it, substituted a default model, and billed for it). +func TestGenerate_NonexistentVersionIDFailsBeforeAnySubmit(t *testing.T) { + var s genSeams + s.resolve = func(context.Context, int) (*genapi.ResolvedVersion, error) { + return nil, civitai.Tag(civitai.ErrNotFound, errors.New("model version 999999 not found")) + } + o := baseOpts() + o.assumeYes = true + o.checkpoint, o.checkpointSet = 999999, true + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if !errors.Is(err, civitai.ErrNotFound) { + t.Fatalf("nonexistent checkpoint: want ErrNotFound (exit 4), got %v", err) + } + if s.submitCalls != 0 || s.whatIfCalls != 0 { + t.Errorf("nonexistent checkpoint: submit=%d whatIf=%d, want 0/0", s.submitCalls, s.whatIfCalls) + } +} + +// --- flag validation --------------------------------------------------------- + +func TestGenerate_UsageErrors(t *testing.T) { + cases := []struct { + name string + mut func(*generateOpts) + }{ + {"no prompt", func(o *generateOpts) { o.prompt = "" }}, + {"blank prompt", func(o *generateOpts) { o.prompt = " " }}, + {"quantity 0", func(o *generateOpts) { o.quantity, o.quantitySet = 0, true }}, + {"negative quantity", func(o *generateOpts) { o.quantity, o.quantitySet = -3, true }}, + {"checkpoint 0", func(o *generateOpts) { o.checkpoint, o.checkpointSet = 0, true }}, + {"negative max-cost", func(o *generateOpts) { o.maxCost, o.maxCostSet = -1, true }}, + {"bad lora", func(o *generateOpts) { o.loras = []string{"nope"} }}, + {"json submit without yes", func(o *generateOpts) { o.jsonOut = true }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var s genSeams + o := baseOpts() + tc.mut(&o) + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } + if s.whatIfCalls != 0 || s.submitCalls != 0 || s.resolveCalls != 0 { + t.Errorf("a usage error must not touch the network: whatIf=%d submit=%d resolve=%d", + s.whatIfCalls, s.submitCalls, s.resolveCalls) + } + }) + } +} + +// A quantity above the server's clamp WARNS (money silently disappears +// otherwise) but never blocks. +func TestGenerate_OverClampQuantityWarnsButProceeds(t *testing.T) { + var s genSeams + o := baseOpts() + o.assumeYes = true + o.quantity, o.quantitySet = 40, true + c, _, errb := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("over-clamp quantity: %v", err) + } + if s.submitCalls != 1 { + t.Errorf("over-clamp quantity must not block: submit=%d", s.submitCalls) + } + if !strings.Contains(errb.String(), "CLAMPS silently") { + t.Errorf("missing clamp warning: %q", errb.String()) + } +} + +// A `ready:false` estimate is refused rather than submitted. +func TestGenerate_NotReadyRefuses(t *testing.T) { + var s genSeams + s.whatIf = func(context.Context, genapi.Graph) (*genapi.WhatIfResult, json.RawMessage, error) { + q := okQuote(12) + q.Ready = false + return q, okQuoteRaw(12), nil + } + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if !errors.Is(err, civitai.ErrBadRequest) { + t.Fatalf("ready:false: want ErrBadRequest, got %v", err) + } + if s.submitCalls != 0 { + t.Errorf("ready:false: submit called %d times, want 0", s.submitCalls) + } +} + +// A missing cost must never render as free. +func TestGenerate_MissingCostRefuses(t *testing.T) { + var s genSeams + s.whatIf = func(context.Context, genapi.Graph) (*genapi.WhatIfResult, json.RawMessage, error) { + return &genapi.WhatIfResult{Ready: true}, json.RawMessage(`{"ready":true}`), nil + } + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err == nil { + t.Fatal("cost-less estimate: want a refusal, got nil") + } + if s.submitCalls != 0 { + t.Errorf("cost-less estimate: submit called %d times, want 0", s.submitCalls) + } +} + +// --- exit-code rows (design §7), driven through a real tRPC error envelope ---- + +// trpcErrServer answers every request with the tRPC error envelope shape the +// platform really emits, at the given HTTP status. +func trpcErrServer(t *testing.T, status int, message, code string) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + body, _ := json.Marshal(map[string]any{ + "error": map[string]any{"json": map[string]any{"message": message, "code": code}}, + }) + _, _ = w.Write(body) + })) + t.Cleanup(srv.Close) + return srv +} + +// 🔴 Every row asserts errors.Is, never message text — the exit code is the +// contract, and a test on the message says nothing about it (a classification +// can be stripped while every message stays byte-identical). +// +// The statuses here are the ones the CLI actually observes: tRPC derives the +// HTTP status from the TRPCError CODE, so an upstream orchestrator 403 for +// insufficient funds reaches us as a 400, not a 403. +func TestGenerate_ErrorRowsClassification(t *testing.T) { + cases := []struct { + name string + status int + code string + message string + want error + notWant []error + }{ + { + name: "missing scope stays an auth failure", status: http.StatusForbidden, code: "FORBIDDEN", + message: "Your API key does not have the required scope for this action", + want: civitai.ErrUnauthorized, + }, + { + name: "unauthenticated", status: http.StatusUnauthorized, code: "UNAUTHORIZED", + message: "UNAUTHORIZED", want: civitai.ErrUnauthorized, + }, + { + name: "muted account is NOT an auth failure", status: http.StatusForbidden, code: "FORBIDDEN", + message: "You cannot perform this action because your account has been restricted", + want: ErrAccountRestricted, notWant: []error{civitai.ErrUnauthorized}, + }, + { + name: "onboarding incomplete is NOT an auth failure", status: http.StatusForbidden, code: "FORBIDDEN", + message: "You must complete the onboarding process before performing this action", + want: ErrAccountRestricted, notWant: []error{civitai.ErrUnauthorized}, + }, + { + name: "insufficient funds (default text)", status: http.StatusBadRequest, code: "BAD_REQUEST", + message: "Hey buddy, seems like you don't have enough funds to perform this action.", + want: ErrInsufficientBuzz, notWant: []error{civitai.ErrUnauthorized, civitai.ErrBadRequest, ErrUsage}, + }, + { + name: "insufficient funds arriving as a 403", status: http.StatusForbidden, code: "FORBIDDEN", + message: "Insufficient funds", + want: ErrInsufficientBuzz, notWant: []error{civitai.ErrUnauthorized}, + }, + { + name: "generation disabled", status: http.StatusBadRequest, code: "BAD_REQUEST", + message: "Generation is currently disabled", + want: ErrGenerationDisabled, notWant: []error{civitai.ErrUnauthorized, ErrUsage}, + }, + { + name: "prompt blocked", status: http.StatusBadRequest, code: "BAD_REQUEST", + message: "Your prompt was flagged: minor", + want: ErrPromptBlocked, notWant: []error{civitai.ErrUnauthorized, ErrUsage}, + }, + { + // DECISION: a resource that resolved fine but is not generatable stays + // ErrBadRequest -> exit 2, NOT ErrNotFound -> exit 4. Exit 4 on this + // command already means "no such version id", produced locally by the + // --checkpoint/--lora resolution; conflating the two would make exit 4 + // unactionable. + name: "resource not generatable", status: http.StatusBadRequest, code: "BAD_REQUEST", + message: "Some Model is not enabled for generation. Please contact support", + want: civitai.ErrBadRequest, notWant: []error{civitai.ErrNotFound, civitai.ErrUnauthorized}, + }, + { + name: "unknown ecosystem is a usage mistake", status: http.StatusInternalServerError, code: "INTERNAL_SERVER_ERROR", + message: "Unknown ecosystem: SDXLL", + want: ErrUsage, + }, + { + name: "rate limited", status: http.StatusTooManyRequests, code: "TOO_MANY_REQUESTS", + message: "Slow down!", want: civitai.ErrRateLimited, + }, + { + name: "service unavailable", status: http.StatusServiceUnavailable, code: "INTERNAL_SERVER_ERROR", + message: "The orchestrator is unavailable", want: civitai.ErrNetwork, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := trpcErrServer(t, tc.status, tc.message, tc.code) + client := genapi.New(srv.URL, "test-token") + + var s genSeams + s.whatIf = client.WhatIfFromGraph + o := baseOpts() + o.assumeYes = true + o.baseURL = srv.URL + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), o) + if err == nil { + t.Fatalf("%s: want an error, got nil", tc.name) + } + if !errors.Is(err, tc.want) { + t.Errorf("%s: errors.Is(err, %v) = false; err = %v", tc.name, tc.want, err) + } + for _, nw := range tc.notWant { + if errors.Is(err, nw) { + t.Errorf("%s: err must NOT classify as %v; err = %v", tc.name, nw, err) + } + } + if s.submitCalls != 0 { + t.Errorf("%s: submit called %d times after an estimate failure, want 0", tc.name, s.submitCalls) + } + }) + } +} + +// The same re-classification must apply on the SUBMIT seam, not just the +// estimate — that is the path where the money already moved. +func TestGenerate_SubmitErrorIsClassifiedToo(t *testing.T) { + srv := trpcErrServer(t, http.StatusForbidden, "You cannot perform this action because your account has been restricted", "FORBIDDEN") + client := genapi.New(srv.URL, "test-token") + + var s genSeams + s.submitErr = nil + deps := s.deps(t) + // Point ONLY the submit seam at the failing server; the estimate succeeds. + deps.submit = client.GenerateFromGraph + + o := baseOpts() + o.assumeYes = true + o.baseURL = srv.URL + c, _, _ := genCmd("") + err := runGenerate(c, deps, o) + if !errors.Is(err, ErrAccountRestricted) { + t.Fatalf("submit-path muted account: want ErrAccountRestricted, got %v", err) + } + if errors.Is(err, civitai.ErrUnauthorized) { + t.Error("submit-path muted account must NOT classify as an auth failure (exit 3)") + } +} + +// An unrecognised server message must keep its status-derived classification — +// the classifier fails soft, so a server-side rewording degrades to today's +// behaviour rather than to a wrong kind. +func TestClassifyGenerateError_UnknownMessageKeepsStatusKind(t *testing.T) { + srv := trpcErrServer(t, http.StatusForbidden, "something nobody has ever seen", "FORBIDDEN") + client := genapi.New(srv.URL, "test-token") + _, _, err := client.WhatIfFromGraph(context.Background(), genapi.Graph{}) + got := classifyGenerateError(err) + if !errors.Is(got, civitai.ErrUnauthorized) { + t.Fatalf("unrecognised 403: want the status-derived ErrUnauthorized, got %v", got) + } +} + +// A non-APIError passes through untouched. +func TestClassifyGenerateError_PassesThroughForeignErrors(t *testing.T) { + in := civitai.Tag(civitai.ErrNotFound, errors.New("model version 1 not found")) + if got := classifyGenerateError(in); got != in { + t.Fatalf("foreign error was rewritten: %v", got) + } +} + +// 🔴 The 403 message this CLI composes itself lists every cause a 403 can have. +// A classifier matching against err.Error() instead of the SERVER's message +// would therefore label every 403 as "insufficient Buzz". Pin that it doesn't. +func TestClassifyGenerateError_DoesNotMatchOurOwnAdvisoryText(t *testing.T) { + srv := trpcErrServer(t, http.StatusForbidden, "Your API key does not have the required scope for this action", "FORBIDDEN") + client := genapi.New(srv.URL, "test-token") + _, _, err := client.WhatIfFromGraph(context.Background(), genapi.Graph{}) + if !strings.Contains(err.Error(), "insufficient Buzz") { + t.Skip("the transport's 403 advisory no longer mentions insufficient Buzz — this trap is gone") + } + got := classifyGenerateError(err) + if errors.Is(got, ErrInsufficientBuzz) { + t.Fatal("classified a scope error as insufficient Buzz — the classifier is reading its own advisory text, not the server's message") + } +} + +// --- command wiring ---------------------------------------------------------- + +// 🔴 `generate` must stay a LEAF. root.go only installs the unknown-subcommand +// guard on non-runnable parents, so a subcommand here would let `civitai +// generate lst` fall through to the runnable command with "lst" as the PROMPT — +// and charge for it. +func TestGenerateCommandHasNoSubcommands(t *testing.T) { + c := newGenerateCmd() + if c.HasSubCommands() { + t.Fatalf("generate must have no subcommands, got %d", len(c.Commands())) + } + if !c.Runnable() { + t.Fatal("generate must be runnable") + } +} + +// The five content flags, and only those five. +func TestGenerateCommandFlagSurface(t *testing.T) { + c := newGenerateCmd() + for _, name := range []string{"negative-prompt", "quantity", "aspect-ratio", "checkpoint", "lora", "dry-run", "json", "yes", "max-cost"} { + if c.Flags().Lookup(name) == nil { + t.Errorf("missing flag --%s", name) + } + } + // These are deliberately absent: silently-degrading parameters, and --model, + // which means a MODEL id on `civitai download` while this takes a VERSION id. + for _, name := range []string{"model", "steps", "cfg-scale", "sampler", "priority", "clip-skip"} { + if c.Flags().Lookup(name) != nil { + t.Errorf("flag --%s must not exist on generate", name) + } + } + if c.Flags().ShorthandLookup("n") != nil { + t.Error("-n must not be a shorthand next to a money prompt") + } +} + +// --max-cost must describe itself as an estimate check, never as a cap. +func TestGenerateMaxCostHelpIsHonest(t *testing.T) { + c := newGenerateCmd() + usage := c.Flags().Lookup("max-cost").Usage + if !strings.Contains(usage, "NOT a spending cap") { + t.Errorf("--max-cost help must say it is not a cap: %q", usage) + } + for _, want := range []string{"SPENDS REAL BUZZ", "personal API key", "not a quote", "estimate check, NOT a spending cap"} { + if !strings.Contains(c.Long, want) && !strings.Contains(strings.ToUpper(c.Long), strings.ToUpper(want)) { + t.Errorf("Long is missing the safety statement %q", want) + } + } +} + +// The command is registered on the root. +func TestGenerateRegisteredOnRoot(t *testing.T) { + root := NewRootCmd() + for _, c := range root.Commands() { + if c.Name() == "generate" { + return + } + } + t.Fatal("generate is not registered on the root command") +} + +// Server-origin strings reach the terminal sanitised. +func TestGenerate_SanitisesServerStrings(t *testing.T) { + var s genSeams + s.resolve = func(_ context.Context, id int) (*genapi.ResolvedVersion, error) { + return &genapi.ResolvedVersion{VersionID: id, ModelName: "evil\x1b[2Kname", ModelType: "Checkpoint"}, nil + } + o := baseOpts() + o.dryRun = true + o.checkpoint, o.checkpointSet = 1, true + c, out, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--dry-run: %v", err) + } + if strings.Contains(out.String(), "\x1b") { + t.Errorf("unsanitised escape reached stdout: %q", out.String()) + } + // safeTerm removes the ESC introducer (which is what makes the sequence + // executable), not the remaining printable bytes — so the name survives as + // inert text rather than disappearing. + if !strings.Contains(out.String(), "evil[2Kname") { + t.Errorf("sanitised model name missing: %q", out.String()) + } +} diff --git a/internal/cmd/generate_wait.go b/internal/cmd/generate_wait.go new file mode 100644 index 00000000..76b46936 --- /dev/null +++ b/internal/cmd/generate_wait.go @@ -0,0 +1,330 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "time" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" +) + +// getWorkflowFn is the read-back seam. It matches genapi.Client.GetWorkflow. +type getWorkflowFn func(ctx context.Context, workflowID string) (*genapi.Workflow, json.RawMessage, error) + +// errWaitTimeout is returned by pollWorkflow when --timeout elapsed before the +// workflow reached a terminal status. +// +// 🔴 It means the CLI STOPPED WAITING. It does NOT mean the job stopped, and it +// does NOT mean the money came back: the generation keeps running server-side +// and the charge stands (a mid-run cancel bills the accrued cost, and the CLI +// cannot cancel from here anyway). Every message built from this must say so. +var errWaitTimeout = errors.New("timed out waiting for the generation to finish") + +// Poll cadence defaults. +// +// 🔴 The 5s floor is a deliberate lower bound, not a tuning knob. An earlier +// design revision argued for 3s on the strength of a "3s server-side feed +// cache" — that cache (QUERIED_WORKFLOWS_CACHE_TTL) belongs to +// `queryGeneratedImages`, a different route. `orchestrator.getWorkflow` proxies +// STRAIGHT THROUGH to the orchestrator with no cache, no cursor and no delta, +// and no tRPC-level rate limit is attached to any orchestrator procedure. So +// there is nothing between this loop and the orchestrator except this loop's own +// restraint: the CLI is the only thing that stops the CLI from being a 429 +// storm. Back off, and back off HARDER when the server actually says 429. +const ( + defaultPollInterval = 5 * time.Second + defaultMaxPollInterval = 60 * time.Second + defaultPollFactor = 1.5 + defaultRateLimitBackoff = 30 * time.Second + defaultPollHeartbeat = 15 * time.Second + // defaultWaitTimeout bounds the default wait. It is a WAITING bound: an + // unattended run must not block forever, and the re-attach path + // (`civitai workflows get `) makes giving up recoverable. + defaultWaitTimeout = 10 * time.Minute +) + +// pollConfig is the poll loop's cadence, with the clock and the sleep injected +// so a test can drive backoff and 429 handling without really sleeping (the +// precedent is app_dev_tunnel.go's interval seams). +type pollConfig struct { + interval time.Duration + maxInterval time.Duration + factor float64 + rateLimitInterval time.Duration + heartbeat time.Duration + // timeout bounds the WAIT (not the job, and not the charge). 0 waits + // indefinitely. + timeout time.Duration + + // sleep waits d or returns ctx.Err(). Injected; nil means the real timer. + sleep func(ctx context.Context, d time.Duration) error + // now reads the clock. Injected; nil means time.Now. + now func() time.Time +} + +// resolved applies the documented defaults to any unset field, so a zero-value +// config (a focused unit test) still polls sanely rather than hot-looping. +// +// 🔴 interval is CLAMPED UP to the floor, never merely defaulted: a caller +// passing 100ms would otherwise hammer an uncached orchestrator route. Tests +// that need a fast loop inject `sleep` instead — that is what the seam is for, +// and it keeps the floor from being negotiable in production code. +func (c pollConfig) resolved() pollConfig { + if c.interval < defaultPollInterval { + c.interval = defaultPollInterval + } + if c.maxInterval < c.interval { + c.maxInterval = maxDuration(defaultMaxPollInterval, c.interval) + } + if c.factor <= 1 { + c.factor = defaultPollFactor + } + if c.rateLimitInterval <= 0 { + c.rateLimitInterval = defaultRateLimitBackoff + } + if c.heartbeat <= 0 { + c.heartbeat = defaultPollHeartbeat + } + if c.sleep == nil { + c.sleep = sleepCtx + } + if c.now == nil { + c.now = time.Now + } + return c +} + +func maxDuration(a, b time.Duration) time.Duration { + if a > b { + return a + } + return b +} + +// sleepCtx waits d, returning early with ctx.Err() on cancellation (Ctrl-C). +func sleepCtx(ctx context.Context, d time.Duration) error { + if d <= 0 { + return ctx.Err() + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil + } +} + +// pollEvent is one observation handed to the reporter. +type pollEvent struct { + attempt int + elapsed time.Duration + status string + wait time.Duration + rateLimited bool + // err is the (retryable) failure this attempt hit, if any. + err error +} + +// pollReporter renders poll progress. Two implementations exist so the non-TTY +// path is fully test-drivable without a terminal, as internal/ui/CONVENTION.md +// requires (the precedent is waitTunnelQuiet / waitTunnelTTY). +type pollReporter interface { + tick(pollEvent) + finish(status string) +} + +// isRetryablePollStatus reports whether an HTTP status justifies another poll. +// +// Status 0 means the request never got a response (transport/DNS/timeout) and IS +// retried: the money has already moved, so the expensive mistake is giving up on +// a workflow the user paid for, not polling a few more times. A definite 4xx +// (401/403/404) is returned immediately — more polls cannot change it. +func isRetryablePollStatus(status int) bool { + switch { + case status == 0: // no response at all + return true + case status == http.StatusRequestTimeout, + status == http.StatusTooEarly, + status == http.StatusTooManyRequests: + return true + case status >= 500: + return true + } + return false +} + +// pollWorkflow polls until the workflow reaches a terminal status, the wait +// times out, the context is cancelled, or a non-retryable error arrives. +// +// It returns the LAST workflow it managed to read even on a timeout, so the +// caller can report the status the job had reached rather than "unknown". +func pollWorkflow(ctx context.Context, get getWorkflowFn, workflowID string, cfg pollConfig, rep pollReporter) (*genapi.Workflow, json.RawMessage, error) { + cfg = cfg.resolved() + start := cfg.now() + wait := cfg.interval + + var last *genapi.Workflow + var lastRaw json.RawMessage + + for attempt := 1; ; attempt++ { + wf, raw, err := get(ctx, workflowID) + rateLimited := false + + switch { + case err == nil: + last, lastRaw = wf, raw + if genapi.IsTerminalStatus(wf.Status) { + rep.finish(wf.Status) + return wf, raw, nil + } + default: + // A cancelled context beats every other classification: the user + // pressed Ctrl-C and the request failed BECAUSE of that. + if ctxErr := ctx.Err(); ctxErr != nil { + return last, lastRaw, ctxErr + } + st := genapi.StatusOf(err) + if !isRetryablePollStatus(st) { + return last, lastRaw, err + } + rateLimited = st == http.StatusTooManyRequests + } + + // The server said 429. Back off to at least the rate-limit interval — + // never merely to the next exponential step, which on an early attempt + // is still only a few seconds. + thisWait := wait + if rateLimited { + thisWait = maxDuration(thisWait, cfg.rateLimitInterval) + } + + elapsed := cfg.now().Sub(start) + if cfg.timeout > 0 { + if elapsed >= cfg.timeout { + rep.finish(statusOrUnknown(last)) + return last, lastRaw, errWaitTimeout + } + // Don't overshoot the deadline by a whole backoff step. + if remaining := cfg.timeout - elapsed; remaining < thisWait { + thisWait = remaining + } + } + + rep.tick(pollEvent{ + attempt: attempt, + elapsed: elapsed, + status: statusOrUnknown(last), + wait: thisWait, + rateLimited: rateLimited, + err: err, + }) + + if serr := cfg.sleep(ctx, thisWait); serr != nil { + return last, lastRaw, serr + } + + // Grow from the wait actually used, so a 429 raises the floor for every + // subsequent poll rather than decaying back to the fast cadence. + wait = time.Duration(float64(thisWait) * cfg.factor) + if wait > cfg.maxInterval { + wait = cfg.maxInterval + } + } +} + +func statusOrUnknown(w *genapi.Workflow) string { + if w == nil || w.Status == "" { + return "unknown" + } + return w.Status +} + +// ── reporters ──────────────────────────────────────────────────────────────── + +// newPollReporter picks the renderer for w. bubbletea/animation NEVER runs on a +// non-TTY writer; a pipe, a CI log and a test buffer all take the quiet path. +func newPollReporter(w io.Writer, now func() time.Time, heartbeat time.Duration) pollReporter { + if now == nil { + now = time.Now + } + if heartbeat <= 0 { + heartbeat = defaultPollHeartbeat + } + if writerIsTTY(w) { + return &ttyPollReporter{w: w} + } + return &quietPollReporter{w: w, now: now, heartbeat: heartbeat} +} + +// quietPollReporter is the non-TTY path: greppable, throttled, no animation. +// This is the path every poll unit test drives, so its behaviour is +// load-bearing. +type quietPollReporter struct { + w io.Writer + now func() time.Time + heartbeat time.Duration + lastPrint time.Time + printed bool +} + +func (r *quietPollReporter) tick(e pollEvent) { + // A 429 is always reported: it is the one event where the user's next + // question ("why is this so slow?") has a real answer. + if e.rateLimited { + fmt.Fprintln(r.w, ui.For(r.w).Warn(fmt.Sprintf( + "the server rate-limited the status poll (429) — backing off %s before the next check", e.wait.Round(time.Second)))) + r.lastPrint, r.printed = r.now(), true + return + } + now := r.now() + if r.printed && now.Sub(r.lastPrint) < r.heartbeat { + return + } + r.lastPrint, r.printed = now, true + if e.err != nil { + fmt.Fprintf(r.w, " waiting… status %s after %s (the last status check failed: %v; retrying in %s)\n", + safeTerm(e.status), e.elapsed.Round(time.Second), e.err, e.wait.Round(time.Second)) + return + } + fmt.Fprintf(r.w, " waiting… status %s after %s (next check in %s)\n", + safeTerm(e.status), e.elapsed.Round(time.Second), e.wait.Round(time.Second)) +} + +func (r *quietPollReporter) finish(status string) { + if r.printed { + fmt.Fprintf(r.w, " status %s\n", safeTerm(status)) + } +} + +// ttyPollReporter is the interactive path: one carriage-return-redrawn line, the +// same technique the download progress meter already uses in this binary. It +// emits no ANSI of its own. +type ttyPollReporter struct { + w io.Writer + live bool +} + +func (r *ttyPollReporter) tick(e pollEvent) { + r.live = true + suffix := fmt.Sprintf("next check in %s", e.wait.Round(time.Second)) + if e.rateLimited { + suffix = fmt.Sprintf("rate-limited (429) — backing off %s", e.wait.Round(time.Second)) + } else if e.err != nil { + suffix = fmt.Sprintf("status check failed, retrying in %s", e.wait.Round(time.Second)) + } + fmt.Fprintf(r.w, "\r generating… %s [%s] %s ", fmtMMSS(e.elapsed), safeTerm(e.status), suffix) +} + +func (r *ttyPollReporter) finish(status string) { + if !r.live { + return + } + fmt.Fprintf(r.w, "\r generation %s%s\n", safeTerm(status), " ") +} diff --git a/internal/cmd/generate_wait_test.go b/internal/cmd/generate_wait_test.go new file mode 100644 index 00000000..d61a8a16 --- /dev/null +++ b/internal/cmd/generate_wait_test.go @@ -0,0 +1,618 @@ +package cmd + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/civitai/cli/internal/genapi" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// --- clock + sleep seam ------------------------------------------------------ + +// fakeClock records every sleep instead of performing it, and advances a virtual +// clock by the slept amount. A poll test that really slept would take minutes +// (the floor is 5s by design) and would be timing-flaky besides. +type fakeClock struct { + now time.Time + slept []time.Duration + cancel context.CancelFunc + // cancelAfter cancels the injected context once this many sleeps have + // happened, which is how the interrupt path is driven deterministically. + cancelAfter int +} + +func newFakeClock() *fakeClock { + return &fakeClock{now: time.Date(2026, 8, 5, 12, 0, 0, 0, time.UTC)} +} + +func (c *fakeClock) Now() time.Time { return c.now } + +func (c *fakeClock) Sleep(ctx context.Context, d time.Duration) error { + if err := ctx.Err(); err != nil { + return err + } + c.slept = append(c.slept, d) + c.now = c.now.Add(d) + if c.cancelAfter > 0 && len(c.slept) >= c.cancelAfter && c.cancel != nil { + c.cancel() + return context.Canceled + } + return nil +} + +func (c *fakeClock) cfg() pollConfig { + return pollConfig{now: c.Now, sleep: c.Sleep} +} + +// scriptedWorkflows returns a getWorkflowFn that hands back one scripted reply +// per call, repeating the last one, and counts the calls. +func scriptedWorkflows(calls *int, replies ...any) getWorkflowFn { + return func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + i := *calls + *calls++ + if i >= len(replies) { + i = len(replies) - 1 + } + switch v := replies[i].(type) { + case error: + return nil, nil, v + case string: + var wf genapi.Workflow + if err := json.Unmarshal([]byte(v), &wf); err != nil { + return nil, nil, err + } + return &wf, json.RawMessage(v), nil + } + return nil, nil, fmt.Errorf("bad script entry %T", replies[i]) + } +} + +func wfJSON(status string) string { + return `{"id":"wf_1","status":"` + status + `","steps":[]}` +} + +// apiErrorWithStatus builds a real genapi.APIError by driving a scripted server, +// so the poll loop's status classification is tested against the SAME error type +// production produces rather than a hand-rolled stand-in. +func apiErrorWithStatus(t *testing.T, status int) error { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"error":{"json":{"message":"scripted"}}}`)) + })) + t.Cleanup(srv.Close) + _, _, err := genapi.New(srv.URL, "tok").GetWorkflow(context.Background(), "wf_1") + if err == nil { + t.Fatalf("expected an error for status %d", status) + } + if genapi.StatusOf(err) != status { + t.Fatalf("built error carries status %d, want %d", genapi.StatusOf(err), status) + } + return err +} + +// --- terminal statuses ------------------------------------------------------- + +// Every terminal status must STOP the loop, and every non-terminal one must not. +func TestPollWorkflow_AllTerminalStatuses(t *testing.T) { + for _, st := range []string{ + genapi.StatusSucceeded, genapi.StatusFailed, genapi.StatusExpired, genapi.StatusCanceled, + } { + t.Run(st, func(t *testing.T) { + clock := newFakeClock() + calls := 0 + wf, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, wfJSON(st)), "wf_1", clock.cfg(), &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Second}) + if err != nil { + t.Fatalf("%s: %v", st, err) + } + if wf.Status != st { + t.Errorf("status = %q, want %q", wf.Status, st) + } + if calls != 1 { + t.Errorf("%s should terminate on the FIRST poll, got %d calls", st, calls) + } + if len(clock.slept) != 0 { + t.Errorf("%s must not sleep before returning, slept %v", st, clock.slept) + } + }) + } +} + +// The transition case, and the POSITIVE CONTROL for the "terminated on the first +// poll" assertions above: this one MUST take three polls and two sleeps. Without +// it, a `calls == 1` result is indistinguishable from a loop that never runs. +func TestPollWorkflow_PendingThenProcessingThenSucceeded(t *testing.T) { + clock := newFakeClock() + calls := 0 + var errb bytes.Buffer + rep := &quietPollReporter{w: &errb, now: clock.Now, heartbeat: time.Nanosecond} + + wf, raw, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, + wfJSON(genapi.StatusScheduled), + wfJSON(genapi.StatusProcessing), + wfJSON(genapi.StatusSucceeded)), + "wf_1", clock.cfg(), rep) + if err != nil { + t.Fatalf("poll: %v", err) + } + if calls != 3 { + t.Fatalf("POSITIVE CONTROL FAILED: want 3 polls across the transition, got %d", calls) + } + if len(clock.slept) != 2 { + t.Errorf("want 2 sleeps between 3 polls, got %v", clock.slept) + } + if wf.Status != genapi.StatusSucceeded { + t.Errorf("final status = %q", wf.Status) + } + if len(raw) == 0 { + t.Error("the terminal raw payload must be returned for --json") + } + // The non-TTY reporter is the test-drivable path; it must report the + // intermediate statuses it observed. + for _, want := range []string{genapi.StatusScheduled, genapi.StatusProcessing} { + if !strings.Contains(errb.String(), want) { + t.Errorf("stderr does not mention status %q: %q", want, errb.String()) + } + } +} + +// --- backoff + 429 ----------------------------------------------------------- + +// Backoff must be exponential, must start no faster than the 5s floor, and must +// be capped. The floor is the point: getWorkflow proxies straight through to the +// orchestrator with no cache and no rate limit, so nothing but this stops the +// CLI being a 429 storm. +func TestPollWorkflow_BackoffIsExponentialAboveTheFloor(t *testing.T) { + clock := newFakeClock() + calls := 0 + replies := make([]any, 0, 9) + for i := 0; i < 8; i++ { + replies = append(replies, wfJSON(genapi.StatusProcessing)) + } + replies = append(replies, wfJSON(genapi.StatusSucceeded)) + + cfg := clock.cfg() + cfg.maxInterval = 20 * time.Second + if _, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, replies...), "wf_1", cfg, &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Hour}); err != nil { + t.Fatalf("poll: %v", err) + } + if len(clock.slept) != 8 { + t.Fatalf("want 8 sleeps, got %d (%v)", len(clock.slept), clock.slept) + } + if clock.slept[0] != defaultPollInterval { + t.Errorf("first wait = %s, want the %s floor", clock.slept[0], defaultPollInterval) + } + for i := 1; i < len(clock.slept); i++ { + if clock.slept[i] < clock.slept[i-1] { + t.Errorf("wait %d (%s) is shorter than wait %d (%s) — backoff must not shrink", i, clock.slept[i], i-1, clock.slept[i-1]) + } + if clock.slept[i] > cfg.maxInterval { + t.Errorf("wait %d = %s exceeds the cap %s", i, clock.slept[i], cfg.maxInterval) + } + } + if clock.slept[len(clock.slept)-1] <= clock.slept[0] { + t.Errorf("backoff never grew: %v", clock.slept) + } +} + +// The floor is not negotiable from the caller side: a config asking for a +// sub-floor interval is clamped UP, not honoured. +func TestPollConfig_ClampsTheIntervalUpToTheFloor(t *testing.T) { + got := pollConfig{interval: 100 * time.Millisecond}.resolved() + if got.interval != defaultPollInterval { + t.Errorf("interval = %s, want it clamped to %s", got.interval, defaultPollInterval) + } + if got.maxInterval < got.interval { + t.Errorf("maxInterval %s < interval %s", got.maxInterval, got.interval) + } +} + +// A 429 must drive a LONGER wait than the normal cadence, and must keep the +// raised floor for subsequent polls rather than decaying straight back. +func TestPollWorkflow_RateLimitDrivesALongerWait(t *testing.T) { + clock := newFakeClock() + calls := 0 + var errb bytes.Buffer + + cfg := clock.cfg() + cfg.rateLimitInterval = 45 * time.Second + cfg.maxInterval = 5 * time.Minute + + _, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, + apiErrorWithStatus(t, http.StatusTooManyRequests), + wfJSON(genapi.StatusProcessing), + wfJSON(genapi.StatusSucceeded)), + "wf_1", cfg, &quietPollReporter{w: &errb, now: clock.Now, heartbeat: time.Nanosecond}) + if err != nil { + t.Fatalf("poll: %v", err) + } + if len(clock.slept) != 2 { + t.Fatalf("want 2 sleeps, got %v", clock.slept) + } + if clock.slept[0] != 45*time.Second { + t.Errorf("wait after a 429 = %s, want the %s rate-limit backoff", clock.slept[0], cfg.rateLimitInterval) + } + // CONTRAST (the positive control for "longer"): a non-429 first poll waits + // only the floor. Same loop, same config, one different reply. + clock2 := newFakeClock() + calls2 := 0 + cfg2 := clock2.cfg() + cfg2.rateLimitInterval = 45 * time.Second + if _, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls2, wfJSON(genapi.StatusProcessing), wfJSON(genapi.StatusSucceeded)), + "wf_1", cfg2, &quietPollReporter{w: &bytes.Buffer{}, now: clock2.Now, heartbeat: time.Hour}); err != nil { + t.Fatalf("contrast poll: %v", err) + } + if clock2.slept[0] != defaultPollInterval { + t.Fatalf("CONTRAST FAILED: a non-429 poll waited %s — if this were also 45s the 429 case would prove nothing", clock2.slept[0]) + } + // And the raised floor must persist. + if clock.slept[1] < 45*time.Second { + t.Errorf("the wait after the 429 decayed to %s — the raised floor must persist", clock.slept[1]) + } + if !strings.Contains(errb.String(), "429") { + t.Errorf("the 429 must be reported to the user, stderr = %q", errb.String()) + } +} + +// A definite 4xx cannot be fixed by polling again — return it at once instead of +// hammering the endpoint until --timeout. +func TestPollWorkflow_NonRetryableStatusReturnsImmediately(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound} { + t.Run(http.StatusText(status), func(t *testing.T) { + clock := newFakeClock() + calls := 0 + _, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, apiErrorWithStatus(t, status)), "wf_1", clock.cfg(), + &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Hour}) + if err == nil { + t.Fatalf("status %d: want an error", status) + } + if calls != 1 { + t.Errorf("status %d polled %d times, want 1", status, calls) + } + if len(clock.slept) != 0 { + t.Errorf("status %d slept %v, want none", status, clock.slept) + } + }) + } + // POSITIVE CONTROL: a 5xx from the SAME builder IS retried, so the zero + // sleeps above are a property of the classification, not of the harness. + clock := newFakeClock() + calls := 0 + _, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, apiErrorWithStatus(t, http.StatusServiceUnavailable), wfJSON(genapi.StatusSucceeded)), + "wf_1", clock.cfg(), &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Hour}) + if err != nil { + t.Fatalf("503 should be retried: %v", err) + } + if calls != 2 || len(clock.slept) != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: 503 gave %d calls / %v sleeps, want 2 / one sleep", calls, clock.slept) + } +} + +// --timeout stops WAITING and returns errWaitTimeout with the last status seen. +func TestPollWorkflow_TimeoutReturnsTheLastStatus(t *testing.T) { + clock := newFakeClock() + calls := 0 + cfg := clock.cfg() + cfg.timeout = 12 * time.Second // two 5s waits, then over the line + + wf, _, err := pollWorkflow(context.Background(), + scriptedWorkflows(&calls, wfJSON(genapi.StatusProcessing)), "wf_1", cfg, + &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Hour}) + if !errors.Is(err, errWaitTimeout) { + t.Fatalf("want errWaitTimeout, got %v", err) + } + if wf == nil || wf.Status != genapi.StatusProcessing { + t.Errorf("the last-seen workflow must be returned so the caller can report its status, got %+v", wf) + } + var total time.Duration + for _, d := range clock.slept { + total += d + } + if total > cfg.timeout { + t.Errorf("slept %s in total, which overshoots the %s timeout", total, cfg.timeout) + } +} + +// Ctrl-C (a cancelled context) unblocks the wait promptly. +func TestPollWorkflow_ContextCancellationStopsTheWait(t *testing.T) { + clock := newFakeClock() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + clock.cancel, clock.cancelAfter = cancel, 1 + + calls := 0 + _, _, err := pollWorkflow(ctx, scriptedWorkflows(&calls, wfJSON(genapi.StatusProcessing)), "wf_1", + clock.cfg(), &quietPollReporter{w: &bytes.Buffer{}, now: clock.Now, heartbeat: time.Hour}) + if !errors.Is(err, context.Canceled) { + t.Fatalf("want context.Canceled, got %v", err) + } +} + +// --- the command-level wait path -------------------------------------------- + +// waitOpts is a full (non---no-wait) invocation writing into dir. +func waitOpts(dir string) generateOpts { + o := baseOpts() + o.noWait = false + o.assumeYes = true + o.outDir = dir + o.timeout = 5 * time.Minute + return o +} + +// A --timeout expiry must NOT report success, and must print the exact re-attach +// command plus both ids — the run was charged and the ids are the only way back +// to what was bought. +func TestGenerate_TimeoutPrintsReattachAndFails(t *testing.T) { + withStdinTTY(t, false) + clock := newFakeClock() + calls := 0 + + var s genSeams + s.getWorkflow = scriptedWorkflows(&calls, wfJSON(genapi.StatusProcessing)) + s.poll = clock.cfg() + + o := waitOpts(t.TempDir()) + o.timeout = 11 * time.Second + + c, out, errb := genCmd("") + err := runGenerate(c, s.deps(t), o) + if err == nil { + t.Fatal("--timeout expiry must return an error, not report success") + } + if !errors.Is(err, errWaitTimeout) { + t.Errorf("want errWaitTimeout, got %v", err) + } + // The error must be explicit that the job and the charge both survive. + for _, want := range []string{"still running", "charged", "not cancelled"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("timeout error does not say %q: %v", want, err) + } + } + stderr := errb.String() + for _, want := range []string{"wf_123", "civitai workflows get wf_123", "External ID"} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + } + if strings.Contains(out.String(), "Saved") { + t.Errorf("nothing should have been saved on a timeout: %q", out.String()) + } +} + +// --no-wait prints the workflow id and exits 0 without ever polling. +func TestGenerate_NoWaitSkipsThePoll(t *testing.T) { + withStdinTTY(t, false) + polled := 0 + var s genSeams + s.getWorkflow = func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + polled++ + return nil, nil, errors.New("the poll seam must not be reached with --no-wait") + } + o := baseOpts() + o.assumeYes = true + + c, out, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("--no-wait: %v", err) + } + if polled != 0 { + t.Errorf("--no-wait polled %d times, want 0", polled) + } + if !strings.Contains(out.String(), "wf_123") { + t.Errorf("workflow id missing from stdout: %q", out.String()) + } + + // POSITIVE CONTROL for that zero: the SAME seam, without --no-wait, IS + // reached. Otherwise "0 polls" could just mean the seam was never wired. + var s2 genSeams + reached := 0 + clock := newFakeClock() + s2.poll = clock.cfg() + s2.getWorkflow = func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + reached++ + var wf genapi.Workflow + _ = json.Unmarshal([]byte(wfJSON(genapi.StatusFailed)), &wf) + return &wf, json.RawMessage(wfJSON(genapi.StatusFailed)), nil + } + c2, _, _ := genCmd("") + _ = runGenerate(c2, s2.deps(t), waitOpts(t.TempDir())) + if reached != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: the poll seam was reached %d times without --no-wait, want 1", reached) + } +} + +// A workflow that ends failed/expired/canceled is an ERROR, and the message must +// say it was charged anyway. +func TestGenerate_NonSucceededTerminalStatusFails(t *testing.T) { + withStdinTTY(t, false) + for _, st := range []string{genapi.StatusFailed, genapi.StatusExpired, genapi.StatusCanceled} { + t.Run(st, func(t *testing.T) { + clock := newFakeClock() + calls := 0 + var s genSeams + s.poll = clock.cfg() + s.getWorkflow = scriptedWorkflows(&calls, wfJSON(st)) + c, _, _ := genCmd("") + err := runGenerate(c, s.deps(t), waitOpts(t.TempDir())) + if err == nil { + t.Fatalf("%s must not report success", st) + } + if !strings.Contains(err.Error(), "charged") { + t.Errorf("%s error must say it was charged: %v", st, err) + } + if !strings.Contains(err.Error(), "civitai workflows get") { + t.Errorf("%s error must name the re-attach command: %v", st, err) + } + }) + } +} + +// --- the pre-submit state file ---------------------------------------------- + +// 🔴 The record must exist BEFORE the POST, not merely afterwards. This asserts +// ORDERING: the observer runs INSIDE the submit seam and reads the file from +// there, so a record written after the call would be missing at that moment. +func TestGenerate_StateFileIsWrittenBeforeTheSubmit(t *testing.T) { + withStdinTTY(t, false) + dir := t.TempDir() + + var s genSeams + s.pendingDirOverride = dir + var seenAtSubmit []pendingGeneration + s.submitObserver = func() { + entries, err := recordsIn(dir) + if err != nil { + t.Errorf("reading the pending dir from inside the submit: %v", err) + return + } + seenAtSubmit = entries + } + + o := baseOpts() + o.assumeYes = true + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("generate: %v", err) + } + if len(seenAtSubmit) != 1 { + t.Fatalf("at the moment of the POST there were %d recovery records, want 1 — the record must be written BEFORE the request", len(seenAtSubmit)) + } + rec := seenAtSubmit[0] + if rec.ExternalID == "" { + t.Error("the record must carry the idempotency key") + } + if rec.ExternalID != s.lastExternalID { + t.Errorf("the recorded key %q is not the key the submit was given (%q) — a record of a DIFFERENT key cannot re-attach anything", rec.ExternalID, s.lastExternalID) + } + if rec.PayloadHash == "" || strings.HasPrefix(rec.PayloadHash, "unhashable") { + t.Errorf("payloadHash = %q", rec.PayloadHash) + } + if rec.SubmittedAt == "" { + t.Error("the record must carry submittedAt") + } + if rec.WorkflowID != "" { + t.Errorf("workflowId must be empty before the reply arrives, got %q", rec.WorkflowID) + } +} + +// --external-id overrides the minted key, which is what makes the documented +// re-attach command real rather than aspirational. +func TestGenerate_ExternalIDOverrideReachesTheSubmit(t *testing.T) { + withStdinTTY(t, false) + var s genSeams + o := baseOpts() + o.assumeYes = true + o.externalID = "11111111-2222-4333-8444-555555555555" + c, _, _ := genCmd("") + if err := runGenerate(c, s.deps(t), o); err != nil { + t.Fatalf("generate: %v", err) + } + if s.lastExternalID != o.externalID { + t.Errorf("submit got externalId %q, want the --external-id override %q", s.lastExternalID, o.externalID) + } +} + +// recordsIn reads every pending-generation record in dir. +func recordsIn(dir string) ([]pendingGeneration, error) { + matches, err := filepath.Glob(filepath.Join(dir, "*.json")) + if err != nil { + return nil, err + } + out := make([]pendingGeneration, 0, len(matches)) + for _, m := range matches { + p, err := readPendingGeneration(m) + if err != nil { + return nil, err + } + out = append(out, *p) + } + return out, nil +} + +// A submit that never got an answer is the charged-or-not-charged case: warn +// loudly and hand over the re-attach command instead of inviting a re-run. +func TestGenerate_SubmitWithNoResponseWarnsAboutAPossibleCharge(t *testing.T) { + withStdinTTY(t, false) + var s genSeams + s.submitErr = errors.New("Post \"https://civitai.com/api/trpc/...\": context deadline exceeded") + o := baseOpts() + o.assumeYes = true + c, _, errb := genCmd("") + if err := runGenerate(c, s.deps(t), o); err == nil { + t.Fatal("a failed submit must return an error") + } + stderr := errb.String() + if !strings.Contains(stderr, "MAY still have been accepted and charged") { + t.Errorf("stderr must not let a no-answer submit read as 'nothing happened':\n%s", stderr) + } + if !strings.Contains(stderr, "--external-id") { + t.Errorf("stderr must name the re-attach flag:\n%s", stderr) + } + + // CONTRAST: a submit that DID get an answer (a classified 400) must not + // print that warning — otherwise the message is noise on every failure. + var s2 genSeams + s2.submitErr = apiErrorWithStatus(t, http.StatusBadRequest) + c2, _, errb2 := genCmd("") + if err := runGenerate(c2, s2.deps(t), o); err == nil { + t.Fatal("a 400 submit must return an error") + } + if strings.Contains(errb2.String(), "MAY still have been accepted and charged") { + t.Errorf("a definite 400 must NOT claim a possible charge:\n%s", errb2.String()) + } +} + +// pflag's UnquoteUsage treats the first back-quoted span in a usage string as +// the flag's VALUE NAME. A boolean flag whose usage quoted a command therefore +// rendered as `--no-wait civitai workflows get ` in --help — measured on +// this phase's first draft, not theorised. The existing --max-cost usage +// carries the same note; this pins it for every flag on both commands at once. +func TestGenerateFlagUsageHasNoBackquotes(t *testing.T) { + checked := 0 + for _, cmd := range []*cobra.Command{newGenerateCmd(), newWorkflowsGetCmd()} { + name := cmd.Name() + cmd.Flags().VisitAll(func(f *pflag.Flag) { + checked++ + if strings.Contains(f.Usage, "`") { + t.Errorf("%s --%s: usage contains a back-quote, which pflag turns into the flag's VALUE NAME: %q", name, f.Name, f.Usage) + } + }) + } + // POSITIVE CONTROL (a): a zero here would mean VisitAll walked nothing. + if checked < 10 { + t.Fatalf("POSITIVE CONTROL FAILED: only %d flags inspected — the walk found nothing to check", checked) + } + // POSITIVE CONTROL (b): prove the predicate CAN fire, so the clean result + // above is a fact about the flags rather than about a check that never + // matches anything. + probe := &cobra.Command{Use: "probe"} + probe.Flags().Bool("bad", false, "see `civitai thing`") + hits := 0 + probe.Flags().VisitAll(func(f *pflag.Flag) { + if strings.Contains(f.Usage, "`") { + hits++ + } + }) + if hits != 1 { + t.Fatalf("POSITIVE CONTROL FAILED: the back-quote predicate matched %d times on a deliberately bad flag, want 1", hits) + } +} diff --git a/internal/cmd/root.go b/internal/cmd/root.go index fc893e9b..039dd00e 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -179,7 +179,7 @@ func NewRootCmd() *cobra.Command { Short: "Civitai CLI — browse & download models, and build Apps", Long: `civitai is the command-line interface for Civitai (https://civitai.com). -It does two things from one static binary: +It does three things from one static binary: • Browse & download the public catalog — search models, list images and articles, and fetch model files. Reading is anonymous; downloading a @@ -188,6 +188,8 @@ It does two things from one static binary: • Build & submit Apps — small, sandboxed web apps that run inside Civitai surfaces. Scaffold a correct project, validate it against the platform contract, and package it for submission. + • Generate images — civitai generate "". This SPENDS REAL BUZZ and + needs a personal API key; price a job with --dry-run first. Get started: @@ -293,6 +295,17 @@ Exit codes: root.AddCommand(newCompletionCmd()) root.AddCommand(newUpdateCheckCmd()) + // 🔴 A money-spending command, and deliberately a LEAF: it must never grow + // subcommands. enforceUsageExitCodes only installs the unknown-subcommand + // guard on non-runnable parents, so on a runnable one a typo'd subcommand + // would be swallowed as the positional PROMPT and billed. + root.AddCommand(newGenerateCmd()) + + // The read side of generation. A GROUP (no Run/RunE of its own) so + // enforceUsageExitCodes below installs the unknown-subcommand guard on it — + // the guard `generate` deliberately cannot have. + root.AddCommand(newWorkflowsCmd()) + // Read subcommands — public REST API (`/api/v1/**`) browsing. root.AddCommand(newModelsCmd()) root.AddCommand(newModelVersionsCmd()) diff --git a/internal/cmd/workflows.go b/internal/cmd/workflows.go new file mode 100644 index 00000000..1dcc1743 --- /dev/null +++ b/internal/cmd/workflows.go @@ -0,0 +1,182 @@ +package cmd + +import ( + "context" + "fmt" + "io" + "strings" + "text/tabwriter" + + "github.com/civitai/cli/internal/auth" + "github.com/civitai/cli/internal/config" + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" + "github.com/civitai/cli/pkg/civitai" + "github.com/spf13/cobra" +) + +// newWorkflowsCmd is the orchestrator-workflow command GROUP. +// +// It is a group and not a runnable command on purpose: root.go's +// enforceUsageExitCodes only installs the unknown-subcommand guard on parents +// that define no Run/RunE of their own, so keeping this non-runnable is what +// makes `civitai workflows frobnicate` a usage error (exit 2) instead of a +// silent exit 0. It is also why `generate` is deliberately NOT a parent — +// see root.go. +// +// The naming is deliberate too: these are orchestrator WORKFLOWS, not +// "generations". +func newWorkflowsCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "workflows", + Short: "List, inspect and cancel generation workflows", + Long: `Work with the generation workflows your account has submitted. + +A workflow is one submitted generation job. ` + "`civitai generate`" + ` prints a +workflow id; ` + "`list`" + ` and ` + "`get`" + ` are how you find one afterwards — which is what +makes ` + "`--no-wait`" + `, a --timeout expiry and a Ctrl-C recoverable rather than a +dead end. + +` + "`list`" + ` and ` + "`get`" + ` are reads and SPEND NOTHING. 🔴 ` + "`cancel`" + ` stops a job but does +NOT refund it — a mid-run cancel bills the accrued cost, non-refundably.`, + Example: ` civitai workflows list + civitai workflows get 01JABCXYZ + civitai workflows get 01JABCXYZ --json + civitai workflows cancel 01JABCXYZ`, + } + cmd.AddCommand(newWorkflowsListCmd()) + cmd.AddCommand(newWorkflowsGetCmd()) + cmd.AddCommand(newWorkflowsCancelCmd()) + return cmd +} + +// workflowsGetOpts is the parsed `workflows get` invocation. +type workflowsGetOpts struct { + jsonOut bool + baseURL string +} + +// workflowsGetDeps is the single network seam, injected so the renderer and +// every error path are testable against httptest with no live server. +type workflowsGetDeps struct { + getWorkflow getWorkflowFn +} + +func newWorkflowsGetCmd() *cobra.Command { + var o workflowsGetOpts + cmd := &cobra.Command{ + Use: "get ", + Short: "Show one generation workflow and its outputs", + Long: `Show one generation workflow: its status, its steps, and its outputs. + +Use it to re-attach to a job you did not wait for — after ` + "`--no-wait`" + `, after a +--timeout expiry, or after Ctrl-C. The workflow id is printed by +` + "`civitai generate`" + ` in all three cases. + +OUTPUT URLS ARE PRESIGNED AND EXPIRE. The links this prints are short-lived; +fetch them promptly or re-run this command for fresh ones. + +Outputs that are blocked by moderation, not available, or hidden are listed with +the reason rather than omitted — a finished workflow can legitimately contain +fewer usable results than it was charged for, and silently dropping them would +make that invisible. + +Reading a workflow SPENDS NOTHING. This needs the same personal API key with the +AI Services scopes that ` + "`civitai generate`" + ` needs.`, + Example: ` civitai workflows get 01JABCXYZ + civitai workflows get 01JABCXYZ --json`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + if cfg.Token() == "" { + return civitai.Tag(civitai.ErrUnauthorized, fmt.Errorf( + "no token configured — reading a workflow needs a personal API key: run `civitai login --token ` (or set CIVITAI_TOKEN)")) + } + o.baseURL = cfg.BaseURL() + gen := genapi.NewWithSource(cfg.BaseURL(), auth.New(cfg)) + return runWorkflowsGet(cmd, workflowsGetDeps{getWorkflow: gen.GetWorkflow}, o, args[0]) + }, + } + cmd.Flags().BoolVar(&o.jsonOut, "json", false, "emit the raw server payload on stdout (scriptable)") + return cmd +} + +// runWorkflowsGet is the testable core. +func runWorkflowsGet(cmd *cobra.Command, deps workflowsGetDeps, o workflowsGetOpts, workflowID string) error { + id := strings.TrimSpace(workflowID) + if id == "" { + return asUsageError(fmt.Errorf("a workflow id is required: civitai workflows get ")) + } + ctx := cmd.Context() + if ctx == nil { + ctx = context.Background() + } + wf, raw, err := deps.getWorkflow(ctx, id) + if err != nil { + return classifyGenerateError(err) + } + if o.jsonOut { + // Raw passthrough: a script sees every server field, including ones the + // CLI does not model. It must branch on the payload itself. + return writeRawJSON(cmd.OutOrStdout(), raw) + } + printWorkflow(cmd.OutOrStdout(), cmd.ErrOrStderr(), wf) + return nil +} + +// printWorkflow renders one workflow for humans. Every server string goes +// through safeTerm — workflow ids, statuses and moderation reasons are all +// server-origin text. +func printWorkflow(out, errw io.Writer, wf *genapi.Workflow) { + tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + fmt.Fprintf(tw, "Workflow ID:\t%s\n", safeTerm(wf.ID)) + fmt.Fprintf(tw, "Status:\t%s\n", safeTerm(dashIfEmpty(wf.Status))) + fmt.Fprintf(tw, "Created:\t%s\n", safeTerm(dashIfEmpty(wf.CreatedAt))) + if wf.StartedAt != nil { + fmt.Fprintf(tw, "Started:\t%s\n", safeTerm(dashIfEmpty(*wf.StartedAt))) + } + if wf.CompletedAt != nil { + fmt.Fprintf(tw, "Completed:\t%s\n", safeTerm(dashIfEmpty(*wf.CompletedAt))) + } + _ = tw.Flush() + + kept, excluded := genapi.PartitionOutputs(wf) + fmt.Fprintf(out, "\n%s\n", ui.For(out).Bold(fmt.Sprintf("Outputs (%d deliverable, %d excluded)", len(kept), len(excluded)))) + if len(kept) == 0 && len(excluded) == 0 { + if genapi.IsTerminalStatus(wf.Status) { + fmt.Fprintln(out, " (none)") + } else { + fmt.Fprintln(out, " (none yet — the workflow has not finished)") + } + } + for i, o := range kept { + fmt.Fprintf(out, "\n [%d] %s\n", i+1, safeTerm(dashIfEmpty(o.ID))) + if o.Width != nil && o.Height != nil { + fmt.Fprintf(out, " size: %dx%d\n", *o.Width, *o.Height) + } + if o.Seed != nil { + fmt.Fprintf(out, " seed: %d\n", *o.Seed) + } + if o.NSFWLevel != nil { + fmt.Fprintf(out, " rating: %s\n", safeTerm(*o.NSFWLevel)) + } + if o.URLExpiresAt != nil { + fmt.Fprintf(out, " expires: %s\n", safeTerm(*o.URLExpiresAt)) + } + if o.URL != nil { + fmt.Fprintf(out, " url: %s\n", safeTerm(*o.URL)) + } + } + reportExcludedOutputs(errw, excluded) + + if !genapi.IsTerminalStatus(wf.Status) { + fmt.Fprintln(errw, ui.For(errw).Dim( + "This workflow has not finished. Re-run this command to check again — it is a read and spends nothing.")) + } else if len(kept) > 0 { + fmt.Fprintln(errw, ui.For(errw).Dim( + "Output URLs are presigned and expire — fetch them promptly, or re-run this command for fresh links.")) + } +} diff --git a/internal/cmd/workflows_cancel.go b/internal/cmd/workflows_cancel.go new file mode 100644 index 00000000..2482c2cc --- /dev/null +++ b/internal/cmd/workflows_cancel.go @@ -0,0 +1,106 @@ +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/civitai/cli/internal/auth" + "github.com/civitai/cli/internal/config" + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" + "github.com/civitai/cli/pkg/civitai" + "github.com/spf13/cobra" +) + +// workflowsCancelOpts is the parsed `workflows cancel` invocation. +type workflowsCancelOpts struct { + jsonOut bool + baseURL string +} + +// workflowsCancelDeps is the single network seam. +// +// 🔴 cancelWorkflow is a MUTATION. A test must never point this at a real +// server; every test in this repo drives it through httptest. +type workflowsCancelDeps struct { + cancelWorkflow func(ctx context.Context, workflowID string) (json.RawMessage, error) +} + +func newWorkflowsCancelCmd() *cobra.Command { + var o workflowsCancelOpts + cmd := &cobra.Command{ + Use: "cancel ", + Short: "Cancel a running generation workflow (DOES NOT REFUND)", + Long: `Cancel a generation workflow that is still running. + +🔴 CANCELLING DOES NOT GET YOUR BUZZ BACK. A mid-run cancel BILLS THE ACCRUED +COST, orchestrator-side and non-refundably. There is no cancel-for-refund +anywhere on this platform: by the time a workflow is running, the money has +moved. Cancel a job because you no longer want its OUTPUT — never as a way to +save money, and never as a way to undo a submit you regret. + +That is also why ` + "`civitai generate --timeout`" + ` and Ctrl-C do not cancel anything: +stopping the wait costs nothing, while stopping the job would cost the same as +letting it finish and would throw away the result you already paid for. + +Cancelling an already-finished workflow is harmless — the outputs of a succeeded +workflow are not deleted by it (use the website to delete results). + +This needs the same personal API key with the AI Services scopes that +` + "`civitai generate`" + ` needs.`, + Example: ` civitai workflows cancel 01JABCXYZ + civitai workflows cancel 01JABCXYZ --json`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + if cfg.Token() == "" { + return civitai.Tag(civitai.ErrUnauthorized, fmt.Errorf( + "no token configured — cancelling a workflow needs a personal API key: run `civitai login --token ` (or set CIVITAI_TOKEN)")) + } + o.baseURL = cfg.BaseURL() + gen := genapi.NewWithSource(cfg.BaseURL(), auth.New(cfg)) + return runWorkflowsCancel(cmd, workflowsCancelDeps{cancelWorkflow: gen.CancelWorkflow}, o, args[0]) + }, + } + cmd.Flags().BoolVar(&o.jsonOut, "json", false, "emit the raw server reply on stdout (scriptable)") + return cmd +} + +// runWorkflowsCancel is the testable core. +func runWorkflowsCancel(cmd *cobra.Command, deps workflowsCancelDeps, o workflowsCancelOpts, workflowID string) error { + id := strings.TrimSpace(workflowID) + if id == "" { + return asUsageError(fmt.Errorf("a workflow id is required: civitai workflows cancel ")) + } + ctx := cmd.Context() + if ctx == nil { + ctx = context.Background() + } + raw, err := deps.cancelWorkflow(ctx, id) + if err != nil { + return classifyGenerateError(err) + } + if o.jsonOut { + if len(raw) == 0 { + // The procedure returns nothing on success, so there is genuinely no + // payload. Emit a valid document a script can parse rather than an + // empty stdout, which `jq` would treat as a hard error. + raw = json.RawMessage(`{}`) + } + return writeRawJSON(cmd.OutOrStdout(), raw) + } + out, errw := cmd.OutOrStdout(), cmd.ErrOrStderr() + fmt.Fprintf(out, "Cancelled workflow %s\n", safeTerm(id)) + // 🔴 Repeated at the point of use, not just in --help: the one place a user + // is guaranteed to read is the line printed after the thing happened. + fmt.Fprintln(errw, ui.For(errw).Warn( + "This did NOT refund anything — a mid-run cancel bills the accrued cost, non-refundably.")) + fmt.Fprintln(errw, ui.For(errw).Dim(fmt.Sprintf( + "Check what it produced before stopping with `civitai workflows get %s`.", safeTerm(id)))) + return nil +} diff --git a/internal/cmd/workflows_cancel_test.go b/internal/cmd/workflows_cancel_test.go new file mode 100644 index 00000000..d7aae7c0 --- /dev/null +++ b/internal/cmd/workflows_cancel_test.go @@ -0,0 +1,168 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/pkg/civitai" +) + +// 🔴 cancelWorkflow is a MUTATION. Every case here runs against httptest or a +// stubbed seam; nothing in this file may reach a real server. + +// wfCancelDeps wires a scripted reply into runWorkflowsCancel and records what +// the seam was asked to cancel. +func wfCancelDeps(reply string, err error, seenID *string, calls *int) workflowsCancelDeps { + return workflowsCancelDeps{cancelWorkflow: func(ctx context.Context, id string) (json.RawMessage, error) { + if calls != nil { + *calls++ + } + if seenID != nil { + *seenID = id + } + if err != nil { + return nil, err + } + return json.RawMessage(reply), nil + }} +} + +func TestWorkflowsCancel_Success(t *testing.T) { + var seen string + c, out, errb := genCmd("") + if err := runWorkflowsCancel(c, wfCancelDeps(`{"result":{"data":{}}}`, nil, &seen, nil), workflowsCancelOpts{}, " wf_1 "); err != nil { + t.Fatalf("workflows cancel: %v", err) + } + if seen != "wf_1" { + t.Errorf("the seam was handed %q, want the trimmed id", seen) + } + if !strings.Contains(out.String(), "wf_1") { + t.Errorf("stdout does not confirm the cancelled id:\n%s", out.String()) + } + // 🔴 The billing truth must be stated at the point of use, not only in + // --help: cancelling does not refund, and a user who reads only this line + // must not come away thinking it did. + stderr := errb.String() + if !strings.Contains(stderr, "did NOT refund") { + t.Errorf("stderr does not say the cancel was not refunded:\n%s", stderr) + } + for _, forbidden := range []string{"saved", "refund" + "ed you", "you will not be charged"} { + if strings.Contains(strings.ToLower(stderr), strings.ToLower(forbidden)) { + t.Errorf("stderr implies cancelling saves money (%q):\n%s", forbidden, stderr) + } + } +} + +// 🔴 The help text is part of the money contract: `cancel` must never read as a +// way to stop paying. It is asserted structurally rather than by eyeball, +// because this is precisely the sentence a later edit would "tidy". +func TestWorkflowsCancel_HelpStatesTheBillingTruth(t *testing.T) { + // Normalised: the claim is about the SENTENCE, not about where the help text + // happens to wrap or which case it shouts in. A guard that broke on a re-wrap + // would be deleted the first time someone reflowed the paragraph. + long := strings.ToLower(strings.Join(strings.Fields(newWorkflowsCancelCmd().Long), " ")) + for _, want := range []string{"does not get your buzz back", "bills the accrued cost", "non-refundab"} { + if !strings.Contains(long, want) { + t.Errorf("`workflows cancel --help` is missing %q:\n%s", want, long) + } + } + if !strings.Contains(newWorkflowsCancelCmd().Short, "DOES NOT REFUND") { + t.Errorf("the one-line summary must carry the warning too: %q", newWorkflowsCancelCmd().Short) + } +} + +func TestWorkflowsCancel_NotFound(t *testing.T) { + apiErr := apiErrorWithStatus(t, http.StatusNotFound) + c, out, _ := genCmd("") + err := runWorkflowsCancel(c, wfCancelDeps("", apiErr, nil, nil), workflowsCancelOpts{}, "wf_gone") + if err == nil { + t.Fatal("a 404 must return an error") + } + if !errors.Is(err, civitai.ErrNotFound) { + t.Errorf("want civitai.ErrNotFound (exit 4), got %v", err) + } + if out.Len() != 0 { + t.Errorf("nothing should be printed on stdout for a failed cancel: %q", out.String()) + } +} + +func TestWorkflowsCancel_EmptyIDIsAUsageError(t *testing.T) { + calls := 0 + c, _, _ := genCmd("") + err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, &calls), workflowsCancelOpts{}, " ") + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } + if calls != 0 { + t.Errorf("a mutation was issued for an empty id (%d calls)", calls) + } + // Positive control: the same seam IS reached for a real id. + if err := runWorkflowsCancel(c, wfCancelDeps(`{}`, nil, nil, &calls), workflowsCancelOpts{}, "wf_1"); err != nil { + t.Fatalf("control cancel: %v", err) + } + if calls != 1 { + t.Errorf("control: seam calls = %d, want 1", calls) + } +} + +// --json must emit a parseable document even though the server returns nothing +// on success — an empty stdout is a hard error for `jq`. +func TestWorkflowsCancel_JSONEmitsAParseableDocument(t *testing.T) { + c, out, _ := genCmd("") + if err := runWorkflowsCancel(c, wfCancelDeps("", nil, nil, nil), workflowsCancelOpts{jsonOut: true}, "wf_1"); err != nil { + t.Fatalf("--json: %v", err) + } + var decoded map[string]any + if err := json.Unmarshal(out.Bytes(), &decoded); err != nil { + t.Fatalf("--json stdout is not valid JSON: %v\n%q", err, out.String()) + } +} + +// End-to-end over httptest: the real client, the real envelope, no live server. +func TestWorkflowsCancel_AgainstHTTPTest(t *testing.T) { + var method, path string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path = r.Method, r.URL.Path + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"result":{"data":{}}}`)) + })) + defer srv.Close() + + gen := genapi.New(srv.URL, "test-key") + c, out, _ := genCmd("") + if err := runWorkflowsCancel(c, workflowsCancelDeps{cancelWorkflow: gen.CancelWorkflow}, workflowsCancelOpts{}, "wf_1"); err != nil { + t.Fatalf("cancel: %v", err) + } + if method != http.MethodPost || path != genapi.CancelWorkflowPath { + t.Errorf("request = %s %s, want POST %s", method, path, genapi.CancelWorkflowPath) + } + if !strings.Contains(out.String(), "wf_1") { + t.Errorf("stdout = %q", out.String()) + } +} + +// The command group must expose all three verbs, and `workflows` itself must +// stay NON-runnable: root.go only installs the unknown-subcommand guard on +// parents that define no Run/RunE, so making it runnable would turn +// `civitai workflows frobnicate` into a silent exit 0. +func TestWorkflowsGroup_HasListGetCancelAndIsNotRunnable(t *testing.T) { + g := newWorkflowsCmd() + if g.Runnable() { + t.Error("the `workflows` group must not be runnable") + } + want := map[string]bool{"list": false, "get": false, "cancel": false} + for _, sub := range g.Commands() { + want[sub.Name()] = true + } + for name, found := range want { + if !found { + t.Errorf("`civitai workflows %s` is not registered", name) + } + } +} diff --git a/internal/cmd/workflows_list.go b/internal/cmd/workflows_list.go new file mode 100644 index 00000000..7d0351a8 --- /dev/null +++ b/internal/cmd/workflows_list.go @@ -0,0 +1,156 @@ +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strings" + "text/tabwriter" + + "github.com/civitai/cli/internal/auth" + "github.com/civitai/cli/internal/config" + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/internal/ui" + "github.com/civitai/cli/pkg/civitai" + "github.com/spf13/cobra" +) + +// workflowsListOpts is the parsed `workflows list` invocation. +type workflowsListOpts struct { + limit int + limitSet bool + cursor string + tags []string + jsonOut bool + baseURL string +} + +// workflowsListDeps is the single network seam. +type workflowsListDeps struct { + queryWorkflows func(ctx context.Context, opts genapi.ListOptions) (*genapi.WorkflowPage, json.RawMessage, error) +} + +func newWorkflowsListCmd() *cobra.Command { + var o workflowsListOpts + cmd := &cobra.Command{ + Use: "list", + Short: "List the generation workflows you have submitted", + Long: `List your own generation workflows, newest first. + +This is the feed behind the website's generator queue: one entry per submitted +job, with its status, when it was created, what it cost and how many outputs it +produced. + +PAGING is by cursor, not page number. --limit sets the page size; when more +results exist the command prints the next cursor, which you pass back as +--cursor to fetch the following page. Deep pages are not cached server-side, so +walk them at a civil pace. + +Each row reports outputs as "/". They differ when an output +was blocked by moderation, never landed, or was hidden on the website — a +workflow you were charged for can legitimately have fewer usable results than it +produced, and collapsing the two numbers would hide that. Use +` + "`civitai workflows get `" + ` for the per-output reasons and the URLs. + +Reading SPENDS NOTHING. It needs the same personal API key with the AI Services +scopes that ` + "`civitai generate`" + ` needs.`, + Example: ` civitai workflows list + civitai workflows list --limit 5 + civitai workflows list --limit 50 --cursor + civitai workflows list --json`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + o.limitSet = cmd.Flags().Changed("limit") + cfg, err := config.Load() + if err != nil { + return err + } + if cfg.Token() == "" { + return civitai.Tag(civitai.ErrUnauthorized, fmt.Errorf( + "no token configured — listing workflows needs a personal API key: run `civitai login --token ` (or set CIVITAI_TOKEN)")) + } + o.baseURL = cfg.BaseURL() + gen := genapi.NewWithSource(cfg.BaseURL(), auth.New(cfg)) + return runWorkflowsList(cmd, workflowsListDeps{queryWorkflows: gen.QueryWorkflows}, o) + }, + } + cmd.Flags().IntVar(&o.limit, "limit", 0, "how many workflows to fetch in this page (server default when unset)") + cmd.Flags().StringVar(&o.cursor, "cursor", "", "opaque cursor from a previous page's next-cursor line") + cmd.Flags().StringArrayVar(&o.tags, "tag", nil, "only list workflows carrying this orchestrator tag. Repeatable") + cmd.Flags().BoolVar(&o.jsonOut, "json", false, "emit the raw server payload on stdout (scriptable)") + return cmd +} + +// runWorkflowsList is the testable core. +func runWorkflowsList(cmd *cobra.Command, deps workflowsListDeps, o workflowsListOpts) error { + if o.limitSet && o.limit < 1 { + return asUsageError(fmt.Errorf("--limit must be at least 1, got %d", o.limit)) + } + ctx := cmd.Context() + if ctx == nil { + ctx = context.Background() + } + page, raw, err := deps.queryWorkflows(ctx, genapi.ListOptions{ + Take: o.limit, + Cursor: o.cursor, + Tags: o.tags, + }) + if err != nil { + return classifyGenerateError(err) + } + if o.jsonOut { + // Raw passthrough: a script sees every server field, including the ones + // this CLI does not model, and reads nextCursor itself. + return writeRawJSON(cmd.OutOrStdout(), raw) + } + printWorkflowList(cmd.OutOrStdout(), cmd.ErrOrStderr(), page, o) + return nil +} + +// printWorkflowList renders the human table. Every server string goes through +// safeTerm — ids, statuses and tags are all server-origin text. +func printWorkflowList(out, errw io.Writer, page *genapi.WorkflowPage, o workflowsListOpts) { + if page == nil || len(page.Items) == 0 { + // An empty feed is a legitimate answer, not an error — but say WHICH + // question came back empty, so a mis-typed --tag or an exhausted cursor + // does not read as "you have never generated anything". + switch { + case o.cursor != "": + fmt.Fprintln(out, "No more workflows on this page.") + case len(o.tags) > 0: + fmt.Fprintf(out, "No workflows tagged %s.\n", strings.Join(o.tags, ", ")) + default: + fmt.Fprintln(out, "No workflows yet.") + fmt.Fprintln(errw, ui.For(errw).Dim("Submit one with `civitai generate \"a cat wearing sunglasses\"`.")) + } + return + } + + tw := tabwriter.NewWriter(out, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, "WORKFLOW ID\tSTATUS\tCREATED\tCOST\tOUTPUTS") + for _, w := range page.Items { + total, deliverable := w.OutputCounts() + cost := "-" + if w.Cost != nil { + cost = buzzAmount(w.Cost.Total) + } + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%d/%d\n", + safeTerm(dashIfEmpty(w.ID)), + safeTerm(dashIfEmpty(w.Status)), + safeTerm(dashIfEmpty(w.CreatedAt)), + cost, + deliverable, total) + } + _ = tw.Flush() + + st := ui.For(errw) + if page.NextCursor != nil && *page.NextCursor != "" { + // The cursor goes to STDOUT: it is data a pipeline consumes, and this + // repo's convention keeps machine-usable values off stderr. + fmt.Fprintf(out, "\nNext cursor: %s\n", safeTerm(*page.NextCursor)) + fmt.Fprintln(errw, st.Dim("More results — re-run with --cursor to continue.")) + } + fmt.Fprintln(errw, st.Dim( + "OUTPUTS is deliverable/total; they differ when an output was blocked, never landed, or you hid it. `civitai workflows get ` shows the reason and the URLs.")) +} diff --git a/internal/cmd/workflows_list_test.go b/internal/cmd/workflows_list_test.go new file mode 100644 index 00000000..d0571878 --- /dev/null +++ b/internal/cmd/workflows_list_test.go @@ -0,0 +1,187 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/pkg/civitai" +) + +// wfListDeps wires a scripted page into runWorkflowsList and records the options +// the command derived from its flags. +func wfListDeps(reply string, err error, seen *genapi.ListOptions, calls *int) workflowsListDeps { + return workflowsListDeps{queryWorkflows: func(ctx context.Context, opts genapi.ListOptions) (*genapi.WorkflowPage, json.RawMessage, error) { + if calls != nil { + *calls++ + } + if seen != nil { + *seen = opts + } + if err != nil { + return nil, nil, err + } + var page genapi.WorkflowPage + if uerr := json.Unmarshal([]byte(reply), &page); uerr != nil { + return nil, nil, uerr + } + return &page, json.RawMessage(reply), nil + }} +} + +const wfListPayload = `{ + "items":[ + {"id":"wf_1","status":"succeeded","createdAt":"2026-08-05T12:00:00Z","cost":{"base":8,"total":12}, + "steps":[{"$type":"textToImage","name":"s","status":"succeeded", + "metadata":{"output":{"c":{"hidden":true}}}, + "output":[ + {"id":"a","available":true,"url":"https://blobs.example/a.jpeg"}, + {"id":"b","available":true,"url":"https://blobs.example/b.jpeg","blockedReason":"minor"}, + {"id":"c","available":true,"url":"https://blobs.example/c.jpeg"} + ]}]}, + {"id":"wf_2","status":"processing","createdAt":"2026-08-05T12:05:00Z","steps":[]} + ], + "nextCursor":"cur_2", + "serverOnlyField":"kept"}` + +func TestWorkflowsList_Populated(t *testing.T) { + c, out, errb := genCmd("") + if err := runWorkflowsList(c, wfListDeps(wfListPayload, nil, nil, nil), workflowsListOpts{}); err != nil { + t.Fatalf("workflows list: %v", err) + } + stdout := out.String() + for _, want := range []string{"WORKFLOW ID", "wf_1", "succeeded", "wf_2", "processing", "12", "2026-08-05T12:00:00Z"} { + if !strings.Contains(stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, stdout) + } + } + // 3 outputs, of which one is blocked and one hidden — the row must report + // BOTH numbers, or a workflow whose results were all filtered out reads as a + // normal one. + if !strings.Contains(stdout, "1/3") { + t.Errorf("stdout does not report deliverable/total as 1/3:\n%s", stdout) + } + // The cursor is DATA a pipeline consumes, so it belongs on stdout. + if !strings.Contains(stdout, "cur_2") { + t.Errorf("the next cursor is missing from stdout:\n%s", stdout) + } + if !strings.Contains(errb.String(), "--cursor") { + t.Errorf("stderr does not explain how to page:\n%s", errb.String()) + } +} + +// An empty feed is an answer, not an error — but it must name which question +// came back empty, so a mis-typed --tag does not read as "you have never +// generated anything". +func TestWorkflowsList_Empty(t *testing.T) { + cases := []struct { + name string + opts workflowsListOpts + want string + }{ + {"no workflows at all", workflowsListOpts{}, "No workflows yet"}, + {"exhausted cursor", workflowsListOpts{cursor: "cur_9"}, "No more workflows"}, + {"unmatched tag", workflowsListOpts{tags: []string{"nope"}}, "No workflows tagged nope"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c, out, _ := genCmd("") + if err := runWorkflowsList(c, wfListDeps(`{"items":[]}`, nil, nil, nil), tc.opts); err != nil { + t.Fatalf("workflows list: %v", err) + } + if !strings.Contains(out.String(), tc.want) { + t.Errorf("stdout = %q, want it to contain %q", out.String(), tc.want) + } + }) + } +} + +func TestWorkflowsList_JSONIsRawPassthrough(t *testing.T) { + c, out, _ := genCmd("") + if err := runWorkflowsList(c, wfListDeps(wfListPayload, nil, nil, nil), workflowsListOpts{jsonOut: true}); err != nil { + t.Fatalf("--json: %v", err) + } + var decoded map[string]any + if err := json.Unmarshal(out.Bytes(), &decoded); err != nil { + t.Fatalf("--json stdout is not valid JSON: %v\n%s", err, out.String()) + } + if decoded["nextCursor"] != "cur_2" { + t.Errorf("--json nextCursor = %v", decoded["nextCursor"]) + } + // A field the CLI's structs never model must survive, so a script can branch + // on the server payload rather than on this CLI's view of it. + if decoded["serverOnlyField"] != "kept" { + t.Errorf("--json dropped a field the CLI does not model: %v", decoded) + } + // The human table must not leak into a machine-readable stdout. + if strings.Contains(out.String(), "WORKFLOW ID") { + t.Errorf("--json stdout carries the human table:\n%s", out.String()) + } +} + +func TestWorkflowsList_PassesPagingOptionsThrough(t *testing.T) { + var seen genapi.ListOptions + c, _, _ := genCmd("") + o := workflowsListOpts{limit: 5, limitSet: true, cursor: "cur_1", tags: []string{"a", "b"}} + if err := runWorkflowsList(c, wfListDeps(`{"items":[]}`, nil, &seen, nil), o); err != nil { + t.Fatalf("workflows list: %v", err) + } + if seen.Take != 5 || seen.Cursor != "cur_1" || len(seen.Tags) != 2 { + t.Errorf("options reaching the seam = %+v, want take 5 / cursor cur_1 / 2 tags", seen) + } +} + +func TestWorkflowsList_RejectsNonPositiveLimit(t *testing.T) { + calls := 0 + c, _, _ := genCmd("") + err := runWorkflowsList(c, wfListDeps(`{"items":[]}`, nil, nil, &calls), workflowsListOpts{limit: 0, limitSet: true}) + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } + if calls != 0 { + t.Errorf("a rejected --limit still hit the network (%d calls)", calls) + } + // Positive control: the same seam IS reached for a valid limit, so the zero + // above is a fact about the guard rather than about the harness. + if err := runWorkflowsList(c, wfListDeps(`{"items":[]}`, nil, nil, &calls), workflowsListOpts{limit: 5, limitSet: true}); err != nil { + t.Fatalf("control list: %v", err) + } + if calls != 1 { + t.Errorf("control: seam calls = %d, want 1", calls) + } +} + +func TestWorkflowsList_ErrorIsClassified(t *testing.T) { + apiErr := apiErrorWithStatus(t, http.StatusForbidden) + c, out, _ := genCmd("") + err := runWorkflowsList(c, wfListDeps("", apiErr, nil, nil), workflowsListOpts{}) + if !errors.Is(err, civitai.ErrUnauthorized) { + t.Errorf("want civitai.ErrUnauthorized (exit 3), got %v", err) + } + if out.Len() != 0 { + t.Errorf("nothing should be printed on stdout for a failed list: %q", out.String()) + } +} + +// A restricted account must classify through the same discriminator `generate` +// uses, not as "log in again". +func TestWorkflowsList_RestrictedAccountIsNotAnAuthError(t *testing.T) { + srv := trpcErrServer(t, http.StatusForbidden, + "You cannot perform this action because your account has been restricted", "FORBIDDEN") + _, _, apiErr := genapi.New(srv.URL, "tok").QueryWorkflows(context.Background(), genapi.ListOptions{}) + if apiErr == nil { + t.Fatal("fixture: expected a 403 error") + } + c, _, _ := genCmd("") + err := runWorkflowsList(c, wfListDeps("", apiErr, nil, nil), workflowsListOpts{}) + if !errors.Is(err, ErrAccountRestricted) { + t.Fatalf("want ErrAccountRestricted, got %v", err) + } + if errors.Is(err, civitai.ErrUnauthorized) { + t.Error("a restricted account must NOT read as an auth failure — `civitai login` will not help") + } +} diff --git a/internal/cmd/workflows_test.go b/internal/cmd/workflows_test.go new file mode 100644 index 00000000..2376e59b --- /dev/null +++ b/internal/cmd/workflows_test.go @@ -0,0 +1,161 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + "github.com/civitai/cli/internal/genapi" + "github.com/civitai/cli/pkg/civitai" +) + +// wfGetDeps wires a scripted reply into runWorkflowsGet. +func wfGetDeps(reply string, err error) workflowsGetDeps { + return workflowsGetDeps{getWorkflow: func(ctx context.Context, id string) (*genapi.Workflow, json.RawMessage, error) { + if err != nil { + return nil, nil, err + } + var wf genapi.Workflow + if uerr := json.Unmarshal([]byte(reply), &wf); uerr != nil { + return nil, nil, uerr + } + return &wf, json.RawMessage(reply), nil + }} +} + +const wfGetPayload = `{ + "id":"wf_123","status":"succeeded","createdAt":"2026-08-05T12:00:00Z","completedAt":"2026-08-05T12:00:30Z", + "steps":[{"$type":"textToImage","name":"s","status":"succeeded", + "metadata":{"params":{"seed":42},"output":{"c":{"hidden":true}}}, + "output":{"images":[ + {"id":"a","type":"image","available":true,"url":"https://blobs.example/a.jpeg","urlExpiresAt":"2026-08-05T13:00:00Z","nsfwLevel":"pg","width":512,"height":768}, + {"id":"b","type":"image","available":true,"url":"https://blobs.example/b.jpeg","blockedReason":"minor"}, + {"id":"c","type":"image","available":true,"url":"https://blobs.example/c.jpeg"} + ]}}]}` + +func TestWorkflowsGet_Found(t *testing.T) { + c, out, errb := genCmd("") + if err := runWorkflowsGet(c, wfGetDeps(wfGetPayload, nil), workflowsGetOpts{baseURL: "https://civitai.com"}, "wf_123"); err != nil { + t.Fatalf("workflows get: %v", err) + } + stdout := out.String() + for _, want := range []string{"wf_123", "succeeded", "512x768", "seed: 42", "https://blobs.example/a.jpeg", "2026-08-05T13:00:00Z"} { + if !strings.Contains(stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, stdout) + } + } + // One deliverable, two excluded — and the excluded ones must be REPORTED, + // not silently dropped. + if !strings.Contains(stdout, "Outputs (1 deliverable, 2 excluded)") { + t.Errorf("the deliverable/excluded counts are missing:\n%s", stdout) + } + stderr := errb.String() + for _, want := range []string{"moderation", "minor", "hidden", "expire"} { + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + } + // A blocked/hidden output's URL must not be presented as a result. + if strings.Contains(stdout, "blobs.example/b.jpeg") || strings.Contains(stdout, "blobs.example/c.jpeg") { + t.Errorf("an excluded output's URL was listed as a result:\n%s", stdout) + } +} + +func TestWorkflowsGet_NotFound(t *testing.T) { + apiErr := apiErrorWithStatus(t, http.StatusNotFound) + c, out, _ := genCmd("") + err := runWorkflowsGet(c, wfGetDeps("", apiErr), workflowsGetOpts{}, "wf_missing") + if err == nil { + t.Fatal("a 404 must return an error") + } + // The exit code is pinned by errors.Is, never by the message text. + if !errors.Is(err, civitai.ErrNotFound) { + t.Errorf("want civitai.ErrNotFound (exit 4), got %v", err) + } + if out.Len() != 0 { + t.Errorf("nothing should be printed on stdout for a 404: %q", out.String()) + } +} + +// A 403 that is really a muted account must classify as ErrAccountRestricted, not +// as "log in again" — the same discrimination `generate` makes, via the same +// classifier. +func TestWorkflowsGet_RestrictedAccountIsNotAnAuthError(t *testing.T) { + // Build the error from a REAL 403 reply carrying the muted-account wording, + // so the classifier is exercised against the same *genapi.APIError + // production produces. + srv := trpcErrServer(t, http.StatusForbidden, + "You cannot perform this action because your account has been restricted", "FORBIDDEN") + _, _, apiErr := genapi.New(srv.URL, "tok").GetWorkflow(context.Background(), "wf_1") + if apiErr == nil { + t.Fatal("fixture: expected a 403 error") + } + + c, _, _ := genCmd("") + err := runWorkflowsGet(c, wfGetDeps("", apiErr), workflowsGetOpts{}, "wf_1") + if !errors.Is(err, ErrAccountRestricted) { + t.Fatalf("want ErrAccountRestricted, got %v", err) + } + if errors.Is(err, civitai.ErrUnauthorized) { + t.Error("a restricted account must NOT read as an auth failure (exit 3) — `civitai login` will not help") + } +} + +func TestWorkflowsGet_JSONIsRawPassthrough(t *testing.T) { + c, out, _ := genCmd("") + if err := runWorkflowsGet(c, wfGetDeps(wfGetPayload, nil), workflowsGetOpts{jsonOut: true}, "wf_123"); err != nil { + t.Fatalf("--json: %v", err) + } + var decoded map[string]any + if err := json.Unmarshal(out.Bytes(), &decoded); err != nil { + t.Fatalf("--json stdout is not valid JSON: %v\n%s", err, out.String()) + } + if decoded["id"] != "wf_123" { + t.Errorf("--json id = %v", decoded["id"]) + } + // Raw passthrough: a field the CLI's struct never models must survive, so a + // script can branch on the server payload rather than on this CLI's view. + steps, ok := decoded["steps"].([]any) + if !ok || len(steps) != 1 { + t.Fatalf("--json lost the steps array: %v", decoded["steps"]) + } + if strings.Contains(out.String(), "\x1b[") { + t.Error("--json must emit no ANSI styling") + } +} + +func TestWorkflowsGet_EmptyIDIsAUsageError(t *testing.T) { + c, _, _ := genCmd("") + err := runWorkflowsGet(c, wfGetDeps(wfGetPayload, nil), workflowsGetOpts{}, " ") + if !errors.Is(err, ErrUsage) { + t.Fatalf("want ErrUsage (exit 2), got %v", err) + } +} + +// An unfinished workflow says so instead of rendering "0 outputs" as a result. +func TestWorkflowsGet_UnfinishedWorkflowSaysSo(t *testing.T) { + c, out, errb := genCmd("") + payload := `{"id":"wf_9","status":"processing","createdAt":"2026-08-05T12:00:00Z","steps":[]}` + if err := runWorkflowsGet(c, wfGetDeps(payload, nil), workflowsGetOpts{}, "wf_9"); err != nil { + t.Fatalf("workflows get: %v", err) + } + if !strings.Contains(out.String(), "not finished") { + t.Errorf("stdout should say the workflow has not finished:\n%s", out.String()) + } + if !strings.Contains(errb.String(), "spends nothing") { + t.Errorf("stderr should say re-checking is free:\n%s", errb.String()) + } +} + +// The command group must reject an unknown subcommand as a usage error rather +// than printing help and exiting 0 (root.go's enforceUsageExitCodes only covers +// non-runnable parents — this pins that `workflows` stays one). +func TestWorkflowsGroup_UnknownSubcommandIsAUsageError(t *testing.T) { + _, _, err := run(t, "workflows", "frobnicate") + if !errors.Is(err, ErrUsage) { + t.Fatalf("unknown subcommand: want ErrUsage (exit 2), got %v", err) + } +} diff --git a/internal/genapi/client.go b/internal/genapi/client.go new file mode 100644 index 00000000..41165140 --- /dev/null +++ b/internal/genapi/client.go @@ -0,0 +1,202 @@ +// Package genapi is the CLI-internal client for the orchestrator generation +// graph (the tRPC `orchestrator.*` procedures behind `civitai generate`). +// +// It is deliberately NOT part of pkg/civitai: that package is the public +// read/download SDK (see pkg/civitai/api.go), and generation is a +// money-spending developer surface whose wire shape is not a public contract. +// It shares only the SDK's exported TokenSource contract, its error-kind +// helpers, and the existing public model-version read route. +// +// The package mirrors internal/appapi's shape on purpose — same TokenSource +// seam, same authedDo/doOnceWith transparent-401-refresh plumbing, same +// response-body cap — so there is one auth/transport pattern in the CLI rather +// than two. +package genapi + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/civitai/cli/pkg/civitai" +) + +// defaultTimeout governs the fast, interactive calls (whatIf cost estimation, +// model-version resolution). Kept short so a hung connection surfaces quickly. +const defaultTimeout = 30 * time.Second + +// submitTimeout governs the generate submit specifically. The procedure does a +// synchronous orchestrator hop (validate graph -> build steps -> submitWorkflow, +// itself retried up to 3x server-side), so it can take well over the fast-call +// timeout. Scope this longer window to the submit only — do NOT lengthen the +// interactive calls. +const submitTimeout = 120 * time.Second + +// maxResponseBody bounds a response read (mirrors the SDK's read cap). A real +// orchestrator JSON body is far below this; the cap only guards against a +// pathological body. +const maxResponseBody = 64 << 20 // 64 MiB + +// VersionGetter is the seam for resolving a model-version id. It is satisfied +// by *civitai.Client — the generation client REUSES the existing public +// `GET /api/v1/model-versions/{id}` route rather than duplicating it, so the +// SSRF/retry/error-kind behaviour of the read SDK is inherited unchanged. +type VersionGetter interface { + GetModelVersion(ctx context.Context, id string) (*civitai.ModelVersionDetail, []byte, error) +} + +// Client is the CLI-internal orchestrator-generation HTTP client. +type Client struct { + BaseURL string + Tokens civitai.TokenSource + HTTP *http.Client + // Versions resolves a model-version id to its model TYPE + display name + // (see versions.go). nil falls back to a client built from BaseURL/Tokens. + Versions VersionGetter + // SubmitTimeout overrides the submit timeout when non-zero; it defaults to + // submitTimeout. Tests set it to avoid depending on the production window. + SubmitTimeout time.Duration + // MaxResponseBody overrides the per-response body read cap (see + // maxResponseBody) when > 0. Tests set a small value to exercise the + // over-cap guard without allocating 64 MiB. + MaxResponseBody int64 +} + +// New builds a Client from a static token (personal API key). Generation is +// personal-key-only today: the `civitai login` OAuth client does not carry the +// AI Services scopes the orchestrator procedures require. +func New(baseURL, token string) *Client { + return NewWithSource(baseURL, civitai.StaticToken(token)) +} + +// NewWithSource builds a Client backed by a TokenSource (which may refresh). +func NewWithSource(baseURL string, src civitai.TokenSource) *Client { + base := strings.TrimRight(baseURL, "/") + return &Client{ + BaseURL: base, + Tokens: src, + HTTP: &http.Client{Timeout: defaultTimeout}, + Versions: civitai.NewWithSource(base, src), + } +} + +// maxBody returns the effective response-body cap for this client. +func (c *Client) maxBody() int64 { + if c.MaxResponseBody > 0 { + return c.MaxResponseBody + } + return maxResponseBody +} + +// readBody reads an entire HTTP response body, bounded by the client's cap. It +// reads one byte past the cap so it can DETECT an over-limit body and return a +// clear error instead of silently handing truncated bytes to json.Unmarshal. +func (c *Client) readBody(body io.Reader) ([]byte, error) { + limit := c.maxBody() + raw, err := io.ReadAll(io.LimitReader(body, limit+1)) + if err != nil { + return raw, err + } + if int64(len(raw)) > limit { + return raw[:limit], fmt.Errorf("response body exceeded %d MiB limit", limit>>20) + } + return raw, nil +} + +// submitClient returns an *http.Client for the generate submit: it mirrors the +// shared client's transport but uses the longer submitTimeout. +func (c *Client) submitClient() *http.Client { + base := c.HTTP + if base == nil { + base = &http.Client{} + } + timeout := submitTimeout + if c.SubmitTimeout > 0 { + timeout = c.SubmitTimeout + } + return &http.Client{ + Timeout: timeout, + Transport: base.Transport, + CheckRedirect: base.CheckRedirect, + Jar: base.Jar, + } +} + +// httpClient returns the shared client, tolerating a zero-value Client. +func (c *Client) httpClient() *http.Client { + if c.HTTP == nil { + return &http.Client{Timeout: defaultTimeout} + } + return c.HTTP +} + +// token returns the bearer token, refusing an unauthenticated call up front +// with an ErrUnauthorized-tagged error (every orchestrator procedure is +// scope-gated, so an anonymous call can only 401). +func (c *Client) token(ctx context.Context) (string, error) { + tok, err := c.Tokens.Token(ctx) + if err != nil { + return "", err + } + if tok == "" { + return "", civitai.Tag(civitai.ErrUnauthorized, + fmt.Errorf("no token configured — run `civitai login --token ` (or set CIVITAI_TOKEN)")) + } + return tok, nil +} + +// authedDo performs build()'s request with the current token, refreshing once +// and replaying on a 401 (a non-refreshable personal-key source returns +// ErrNoRefresh and the original 401 stands). +// +// 🔴 The replay re-sends the request body. That is safe for the calls in this +// package only because every mutation carries an unconditional `externalId` +// (see generate.go): the orchestrator dedupes on (userId, externalId), so a +// replayed submit returns the pre-existing workflow instead of charging twice. +// Do not add a mutation here that omits it. +func (c *Client) authedDo(ctx context.Context, build func() (*http.Request, error)) (int, []byte, error) { + return c.authedDoWith(ctx, c.httpClient(), build) +} + +// authedDoWith is authedDo against a specific *http.Client, so the slow submit +// can use a longer-timeout client without affecting the fast interactive calls. +func (c *Client) authedDoWith(ctx context.Context, httpClient *http.Client, build func() (*http.Request, error)) (int, []byte, error) { + tok, err := c.token(ctx) + if err != nil { + return 0, nil, err + } + status, raw, err := c.doOnceWith(httpClient, build, tok) + if err != nil { + return 0, nil, err + } + if status == http.StatusUnauthorized { + newTok, rerr := c.Tokens.Refresh(ctx) + if rerr == nil && newTok != "" { + return c.doOnceWith(httpClient, build, newTok) + } + } + return status, raw, nil +} + +func (c *Client) doOnceWith(httpClient *http.Client, build func() (*http.Request, error), token string) (int, []byte, error) { + req, err := build() + if err != nil { + return 0, nil, err + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := httpClient.Do(req) + if err != nil { + return 0, nil, err + } + defer resp.Body.Close() + raw, err := c.readBody(resp.Body) + if err != nil { + return resp.StatusCode, raw, err + } + return resp.StatusCode, raw, nil +} diff --git a/internal/genapi/errors.go b/internal/genapi/errors.go new file mode 100644 index 00000000..dd666ce2 --- /dev/null +++ b/internal/genapi/errors.go @@ -0,0 +1,124 @@ +package genapi + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/civitai/cli/pkg/civitai" +) + +// serverMessage extracts a tRPC error body's message +// ({"error":{"json":{"message":...}}}), falling back to a plain +// {"message"|"error": ...} body and then to the trimmed raw bytes. +func serverMessage(raw []byte) string { + var trpc struct { + Error struct { + JSON struct { + Message string `json:"message"` + } `json:"json"` + } `json:"error"` + } + if json.Unmarshal(raw, &trpc) == nil && trpc.Error.JSON.Message != "" { + return trpc.Error.JSON.Message + } + var plain struct { + Message string `json:"message"` + Error string `json:"error"` + } + if json.Unmarshal(raw, &plain) == nil { + if plain.Message != "" { + return plain.Message + } + if plain.Error != "" { + return plain.Error + } + } + return strings.TrimSpace(string(raw)) +} + +// APIError is the structured form of a non-200 from an orchestrator generation +// procedure. It exists so a caller can discriminate on the SERVER's own message +// without re-parsing the formatted error string. +// +// 🔴 Read ServerMessage, never Error(), when classifying. Error() is the +// ACTIONABLE text this package builds, and for a 403 that text deliberately +// lists every cause a 403 can have ("a missing AI Services scope, insufficient +// Buzz, a muted account, or generation being disabled") — so a substring match +// against Error() matches ALL of them for EVERY 403 and classifies nothing. +// ServerMessage is only what the server said. +// +// Error() delegates unchanged, so the user-visible message and the +// civitai.TagStatus classification are byte-for-byte what they were before this +// type existed; it only adds an errors.As handle. +type APIError struct { + // Proc is the orchestrator procedure that failed. + Proc string + // Status is the HTTP status the tRPC endpoint answered with. Note this is + // derived server-side from the TRPCError CODE, not from whatever status an + // upstream service used — see the mapping notes in generateError. + Status int + // ServerMessage is the server's own message, unwrapped from the tRPC error + // envelope ({"error":{"json":{"message":…}}}). It is UNTRUSTED, server-origin + // text: route it through the presentation layer's terminal sanitiser before + // printing it. + ServerMessage string + + err error +} + +func (e *APIError) Error() string { return e.err.Error() } +func (e *APIError) Unwrap() error { return e.err } + +// generateError turns a non-200 from an orchestrator generation procedure into +// an actionable error, classified by HTTP status via civitai.TagStatus so the +// process exit code is pinned by errors.Is and never by message text. +// +// 🔴 This layer classifies FAITHFULLY BY STATUS and nothing else. civitai.TagStatus +// maps BOTH 401 and 403 to ErrUnauthorized -> exit 3 ("login required / credential +// lacks scope"), and several generation failures are not that. Discriminating them +// needs the server's message text, which is a presentation concern — so the +// re-mapping lives at the surface that owns the exit-code contract +// (internal/cmd/generate.go, classifyGenerateError), reading APIError.ServerMessage. +// Do not move it here: this function's status->kind mapping is pinned by tests. +// +// Which failures actually need re-mapping was MEASURED against the platform +// source, and the design doc's §7 table is wrong about two of them. tRPC derives +// the HTTP status from the TRPCError CODE, so an upstream orchestrator 403 does +// NOT reach the CLI as a 403: +// +// - insufficient Buzz: the orchestrator's 403 is caught and re-thrown as +// `throwInsufficientFundsError` -> code BAD_REQUEST -> the CLI sees **400** +// (civitai/civitai -> src/server/services/orchestrator/workflows.ts:385, +// src/server/utils/errorHandling.ts:218). So it exits 2 today, not 3. +// - generation disabled / memberOnly: thrown as BAD_REQUEST -> **400** +// (orchestrator.router.ts:379-390). Also not 3 today. +// - account muted, and onboarding incomplete: bare FORBIDDEN -> **403** +// (trpc.ts:389-401, :423-435). THESE are the ones that read byte-identical +// to a scope error and would tell a restricted user to re-run `civitai login` +// forever. +// - prompt flagged: BAD_REQUEST -> **400**, and must never be retried. +// - unknown ecosystem: a bare Error -> **500**, so it has no sentinel (exit 1). +func generateError(proc string, status int, raw []byte) (err error) { + msg := serverMessage(raw) + defer func() { + err = civitai.TagStatus(status, &APIError{Proc: proc, Status: status, ServerMessage: msg, err: err}) + }() + switch status { + case http.StatusUnauthorized: + return fmt.Errorf("not authenticated for %s (401): %s — generation needs a personal API key with the AI Services scopes; create one at https://civitai.com/user/account, then run `civitai login --token `", proc, msg) + case http.StatusForbidden: + return fmt.Errorf("refused by the server for %s (403): %s — this can be a missing AI Services scope, insufficient Buzz, a muted account, or generation being disabled; check your credential with `civitai whoami`", proc, msg) + case http.StatusBadRequest: + return fmt.Errorf("the server rejected the generation request (400): %s", msg) + case http.StatusNotFound: + return fmt.Errorf("no such generation procedure or resource (404): %s", msg) + case http.StatusTooManyRequests: + return fmt.Errorf("rate limited (429): %s — back off before retrying", msg) + case http.StatusServiceUnavailable: + return fmt.Errorf("generation is unavailable (503): %s", msg) + default: + return fmt.Errorf("server returned %d for %s: %s", status, proc, msg) + } +} diff --git a/internal/genapi/generate.go b/internal/genapi/generate.go new file mode 100644 index 00000000..5b9376f9 --- /dev/null +++ b/internal/genapi/generate.go @@ -0,0 +1,268 @@ +package genapi + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "fmt" + "net/http" + "net/url" +) + +// The two orchestrator generation-graph procedures. +// +// 🔴 They take DIFFERENT ENVELOPES for the SAME graph, and the mismatch is +// SILENT — it returns HTTP 200 with a plausible, wrong cost. This is the single +// most important fact in this package. +// +// whatIfFromGraph GET ?input={"json": } graph FLAT +// generateFromGraph POST {"json":{"input": , ...}} graph NESTED +// +// The server destructures the graph out of a wrapper on the mutation +// (`const { input: formInput, ..., externalId } = input`) and takes it flat on +// the query (civitai/civitai -> src/server/routers/orchestrator.router.ts). +// The web mirrors the asymmetry deliberately. +// +// Measured against civitai.com: a NESTED payload sent to whatIf is never parsed +// at all — every nested body prices the default job (total 8) byte-identically +// to `{}`, while the same graph sent flat priced 60. The discriminating control +// was an ecosystem that 500s "Unknown ecosystem" when sent flat and returns a +// clean `200 ready:true` when sent nested. So a builder wired to the wrong +// nesting keeps every "did it 200?" assertion green while quoting a constant — +// which would let a `--max-cost` pre-flight wave through an arbitrarily +// expensive job. The envelope shapes are pinned by tests for this reason. +const ( + // WhatIfPath is the cost-estimate query. It spends nothing. + WhatIfPath = "/api/trpc/orchestrator.whatIfFromGraph" + // GeneratePath is the SUBMIT mutation. It SPENDS BUZZ. + GeneratePath = "/api/trpc/orchestrator.generateFromGraph" +) + +// WorkflowCost is the orchestrator's cost breakdown. Factors are multipliers +// (e.g. quantity/size/steps/scheduler/popularity) and Fixed are flat additions +// (e.g. additionalNetworks/priority/format); both are open maps because the key +// set is server-owned and must be echoed VERBATIM, never relabelled. +// +// Total is documented server-side as "including tips" — but the whatIf request +// prices a strictly smaller body than a submit (it sends no tips), so a caller +// that passes any tip cannot trust this total by arithmetic. This package does +// not send tips at all (see generateEnvelope). +type WorkflowCost struct { + Base float64 `json:"base"` + Total float64 `json:"total"` + Factors map[string]float64 `json:"factors,omitempty"` + Fixed map[string]float64 `json:"fixed,omitempty"` + Tips map[string]float64 `json:"tips,omitempty"` +} + +// WhatIfResult is the whatIfFromGraph reply. +// +// 🔴 It is an ESTIMATE, not a quote: it carries no id, nonce, signed price or +// expiry, so there is nothing to hand back to the submit. No server-side spend +// ceiling is reachable from a personal API key, and realized cost can exceed +// this figure with no refund. Never present it as a cap. +type WhatIfResult struct { + // Ready is false when some job in the workflow has no available support + // (i.e. the resources are not currently generatable). + Ready bool `json:"ready"` + Cost *WorkflowCost `json:"cost"` + AllowMatureContent *bool `json:"allowMatureContent,omitempty"` + // Transactions is passed through untyped; its shape is orchestrator-owned. + Transactions json.RawMessage `json:"transactions,omitempty"` +} + +// SubmitResult is the generateFromGraph reply — one normalized workflow. +// +// ✅ VERIFIED against a live submit (one SDXL-default txt2img, quantity 1: +// estimated 8 Buzz, charged exactly 8). The field names below were originally +// derived by reading the server's `NormalizedWorkflow` interface +// (civitai/civitai -> src/server/services/orchestrator/ +// orchestration-new.service.ts) and carried an UNVERIFIED warning, because +// exercising the mutation spends real money; that warning is now discharged. +// +// Only the fields a caller needs to poll and report are modelled; the raw +// payload is returned alongside so nothing is lost. Note this is the NORMALIZED +// shape — `orchestrator.getWorkflow` returns the RAW orchestrator workflow, a +// different shape again (see status.go). Do not share a struct between them. +type SubmitResult struct { + // ID is the workflow id — the handle for polling and for re-attaching after + // an interrupt. + ID string `json:"id"` + Status string `json:"status"` + Cost *WorkflowCost `json:"cost"` + Tags []string `json:"tags,omitempty"` +} + +// SubmitOptions carries the ENVELOPE siblings of the graph — the fields that +// live beside `input`, not inside it. +// +// 🔴 This struct is a WHITELIST and must stay one. The envelope also accepts +// `civitaiTip` / `creatorTip`, which are real money and are deliberately NOT +// modelled: if a caller ever splats a user-supplied graph file into the +// envelope's top level, a committed `graph.json` carrying `civitaiTip: 5000` +// would charge a tip that a cost pre-flight structurally cannot see. +type SubmitOptions struct { + // ExternalID overrides the minted idempotency key. Empty means "mint one", + // which is the normal path — see GenerateFromGraph. + ExternalID string + // Tags are orchestrator workflow tags. + Tags []string +} + +// whatIfEnvelope is the tRPC input wrapper for the QUERY: the graph sits FLAT +// under "json". +type whatIfEnvelope struct { + JSON Graph `json:"json"` +} + +// generateEnvelope is the tRPC input wrapper for the MUTATION: the graph is +// NESTED under "json"."input", beside the envelope-only siblings. +type generateEnvelope struct { + JSON generateInput `json:"json"` +} + +type generateInput struct { + Input Graph `json:"input"` + // ExternalID is the orchestrator idempotency key. It has no `omitempty` on + // purpose: it is unconditional, and a silently-absent key is the exact + // failure this field exists to prevent. + ExternalID string `json:"externalId"` + Tags []string `json:"tags,omitempty"` +} + +// NewExternalID mints a RFC 4122 version-4 UUID for use as the orchestrator +// idempotency key. +// +// 🔴 One MUST be sent on every submit. The platform's submit wrapper retries +// 3x on a 5xx AND on a network error / no response, reusing the same body, and +// adds NO idempotency key of its own; there is no server-side minting fallback. +// The orchestrator dedupes on (userId, externalId), so without one a single +// user action can be charged up to three times. The web client is safe only +// because it always mints one. +// +// It uses crypto/rand + manual v4 formatting rather than a uuid dependency — +// this is a small, focused project and a new module needs maintainer approval. +func NewExternalID() (string, error) { + var b [16]byte + if _, err := rand.Read(b[:]); err != nil { + return "", fmt.Errorf("mint externalId: %w", err) + } + b[6] = (b[6] & 0x0f) | 0x40 // version 4 + b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil +} + +// WhatIfFromGraph estimates the cost of g WITHOUT submitting it. It spends +// nothing (verified live: the Buzz balance was byte-identical before and after +// every probe). +// +// 🔴 It never sends an externalId. A whatIf carrying a matching key would +// return the pre-existing workflow, burning the key the subsequent submit needs +// — which is why the server's own whatIf body omits it. +// +// It returns the decoded result AND the raw unwrapped payload, so a `--json` +// surface can pass through server fields this struct does not model. +func (c *Client) WhatIfFromGraph(ctx context.Context, g Graph) (*WhatIfResult, json.RawMessage, error) { + inputJSON, err := json.Marshal(whatIfEnvelope{JSON: whatIfGraph(g)}) + if err != nil { + return nil, nil, err + } + q := url.Values{} + q.Set("input", string(inputJSON)) + reqURL := c.BaseURL + WhatIfPath + "?" + q.Encode() + + build := func() (*http.Request, error) { + return http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + } + status, raw, err := c.authedDo(ctx, build) + if err != nil { + return nil, nil, err + } + if status != http.StatusOK { + return nil, nil, generateError("whatIfFromGraph", status, raw) + } + payload, err := unwrapTRPC("orchestrator.whatIfFromGraph", raw) + if err != nil { + return nil, nil, err + } + var out WhatIfResult + if err := json.Unmarshal(payload, &out); err != nil { + return nil, nil, fmt.Errorf("unexpected orchestrator.whatIfFromGraph payload: %s", string(payload)) + } + return &out, payload, nil +} + +// GenerateFromGraph SUBMITS g. 🔴 THIS SPENDS BUZZ. +// +// An externalId is minted unconditionally when opts.ExternalID is empty, and is +// always present in the body (see NewExternalID for why). The caller gets it +// back so it can be recorded before/around the call and used to re-attach: a +// duplicate externalId returns HTTP 200 with the PRE-EXISTING workflow rather +// than a 409, so re-attachment has to be inferred locally. +// +// It returns the decoded result AND the raw unwrapped payload. +func (c *Client) GenerateFromGraph(ctx context.Context, g Graph, opts SubmitOptions) (*SubmitResult, string, json.RawMessage, error) { + externalID := opts.ExternalID + if externalID == "" { + var err error + if externalID, err = NewExternalID(); err != nil { + return nil, "", nil, err + } + } + body, err := json.Marshal(generateEnvelope{JSON: generateInput{ + Input: g, + ExternalID: externalID, + Tags: opts.Tags, + }}) + if err != nil { + return nil, externalID, nil, err + } + build := func() (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+GeneratePath, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + return req, nil + } + status, raw, err := c.authedDoWith(ctx, c.submitClient(), build) + if err != nil { + return nil, externalID, nil, err + } + if status != http.StatusOK { + return nil, externalID, nil, generateError("generateFromGraph", status, raw) + } + payload, err := unwrapTRPC("orchestrator.generateFromGraph", raw) + if err != nil { + return nil, externalID, nil, err + } + var out SubmitResult + if err := json.Unmarshal(payload, &out); err != nil { + return nil, externalID, nil, fmt.Errorf("unexpected orchestrator.generateFromGraph payload: %s", string(payload)) + } + return &out, externalID, payload, nil +} + +// unwrapTRPC extracts the payload from a tRPC success envelope +// {"result":{"data":{"json":{...}}}}. +// +// A literal `null` payload unmarshals CLEANLY into a zero struct, which for a +// cost estimate would render as "total 0" — a fabricated free quote. Reject it +// as malformed alongside a missing/undecodable envelope, exactly as the App +// Blocks analytics reader does. +func unwrapTRPC(proc string, raw []byte) (json.RawMessage, error) { + var env struct { + Result struct { + Data struct { + JSON json.RawMessage `json:"json"` + } `json:"data"` + } `json:"result"` + } + if err := json.Unmarshal(raw, &env); err != nil || + len(env.Result.Data.JSON) == 0 || + string(bytes.TrimSpace(env.Result.Data.JSON)) == "null" { + return nil, fmt.Errorf("unexpected %s response: %s", proc, string(raw)) + } + return env.Result.Data.JSON, nil +} diff --git a/internal/genapi/generate_test.go b/internal/genapi/generate_test.go new file mode 100644 index 00000000..0f525240 --- /dev/null +++ b/internal/genapi/generate_test.go @@ -0,0 +1,697 @@ +package genapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "regexp" + "strings" + "testing" + + "github.com/civitai/cli/pkg/civitai" +) + +// --------------------------------------------------------------------------- +// Envelope shape — the core guard of this package. +// +// whatIf takes the graph FLAT; generate takes it NESTED under .input. A +// mismatch returns HTTP 200 with a bogus default cost, so a test that only +// asserts "it returned 200" is worthless here. Every assertion below decodes +// the ACTUAL outgoing bytes into map[string]any and inspects key positions. +// --------------------------------------------------------------------------- + +// flatOnlyPricer reproduces the MEASURED civitai.com behaviour: whatIfFromGraph +// parses the graph only when it arrives FLAT under "json". A nested payload is +// never parsed at all and prices the default job at 8, byte-identically to {}. +// +// A client wired to the wrong nesting therefore still gets a clean 200 here — +// which is exactly the silent failure this handler exists to expose. +func flatOnlyPricer(w http.ResponseWriter, r *http.Request) { + var env struct { + JSON map[string]any `json:"json"` + } + if err := json.Unmarshal([]byte(r.URL.Query().Get("input")), &env); err != nil { + http.Error(w, "bad input param", http.StatusBadRequest) + return + } + total := 8.0 // the default-job price: what a wrongly-nested payload gets + if _, nested := env.JSON["input"]; !nested { + if _, ok := env.JSON["workflow"]; ok { + qty := 1.0 + if q, ok := env.JSON["quantity"].(float64); ok { + qty = q + } + total = 60 * qty + } + } + writeTRPC(w, map[string]any{ + "ready": true, + "cost": map[string]any{"base": 60, "total": total, "factors": map[string]any{"quantity": 1}}, + }) +} + +func writeTRPC(w http.ResponseWriter, payload any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "result": map[string]any{"data": map[string]any{"json": payload}}, + }) +} + +func testClient(t *testing.T, h http.Handler) *Client { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + return New(srv.URL, "test-key") +} + +// TestWhatIf_GraphIsFlatInTheEnvelope pins the QUERY envelope: the graph's own +// keys sit at the top level of "json", with no "input" wrapper. +func TestWhatIf_GraphIsFlatInTheEnvelope(t *testing.T) { + var got map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var env struct { + JSON map[string]any `json:"json"` + } + if err := json.Unmarshal([]byte(r.URL.Query().Get("input")), &env); err != nil { + t.Errorf("input param is not JSON: %v", err) + } + got = env.JSON + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}}) + })) + + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{ + Workflow: "txt2img", Ecosystem: "SDXL", Prompt: "a cat", Quantity: Ptr(2), + }); err != nil { + t.Fatalf("WhatIfFromGraph: %v", err) + } + + if _, nested := got["input"]; nested { + t.Errorf("whatIf envelope nests the graph under .input; it must be FLAT: %v", got) + } + for _, k := range []string{"workflow", "ecosystem", "quantity"} { + if _, ok := got[k]; !ok { + t.Errorf("whatIf envelope: key %q missing from the TOP level: %v", k, got) + } + } + if got["workflow"] != "txt2img" { + t.Errorf("whatIf workflow = %v, want txt2img", got["workflow"]) + } +} + +// TestWhatIf_PricesTheGraphNotTheDefaultJob is the POSITIVE CONTROL for the +// envelope: against a handler that only prices a FLAT graph, the client must +// see the graph's real price AND that price must MOVE with quantity. A client +// in the wrong-nesting regime would read a constant 8 here. +func TestWhatIf_PricesTheGraphNotTheDefaultJob(t *testing.T) { + c := testClient(t, http.HandlerFunc(flatOnlyPricer)) + + one, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img", Quantity: Ptr(1)}) + if err != nil { + t.Fatalf("WhatIfFromGraph(quantity=1): %v", err) + } + four, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img", Quantity: Ptr(4)}) + if err != nil { + t.Fatalf("WhatIfFromGraph(quantity=4): %v", err) + } + if one.Cost.Total == 8 || four.Cost.Total == 8 { + t.Fatalf("got the default-job price (8) — the graph was not parsed, i.e. the envelope is wrong: %v / %v", + one.Cost.Total, four.Cost.Total) + } + if one.Cost.Total != 60 || four.Cost.Total != 240 { + t.Fatalf("totals = %v / %v, want 60 / 240", one.Cost.Total, four.Cost.Total) + } + if four.Cost.Total <= one.Cost.Total { + t.Errorf("total did not move with quantity (%v -> %v): a constant total is indistinguishable "+ + "from a harness wired to nothing", one.Cost.Total, four.Cost.Total) + } +} + +// TestFlatOnlyPricer_NegativeControl validates the HARNESS above: fed a NESTED +// payload directly (bypassing the client), it must report the bogus default +// price of 8. Without this, the green result in the previous test could come +// from a handler that always answers 60. +func TestFlatOnlyPricer_NegativeControl(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(flatOnlyPricer)) + defer srv.Close() + + get := func(input string) float64 { + t.Helper() + q := url.Values{} + q.Set("input", input) + resp, err := http.Get(srv.URL + "?" + q.Encode()) + if err != nil { + t.Fatalf("GET: %v", err) + } + defer resp.Body.Close() + raw, _ := io.ReadAll(resp.Body) + payload, err := unwrapTRPC("test", raw) + if err != nil { + t.Fatalf("unwrap: %v", err) + } + var out WhatIfResult + if err := json.Unmarshal(payload, &out); err != nil { + t.Fatalf("decode: %v", err) + } + return out.Cost.Total + } + + if got := get(`{"json":{"input":{"workflow":"txt2img","quantity":4}}}`); got != 8 { + t.Errorf("nested payload priced %v, want the bogus default 8 — the harness cannot detect a wrong envelope", got) + } + if got := get(`{"json":{}}`); got != 8 { + t.Errorf("empty payload priced %v, want 8", got) + } + if got := get(`{"json":{"workflow":"txt2img","quantity":4}}`); got != 240 { + t.Errorf("flat payload priced %v, want 240 — the harness cannot observe a correct envelope", got) + } +} + +// checkNestedEnvelope asserts the SUBMIT envelope shape on a decoded body: the +// graph must sit under .json.input, and its keys must NOT be at .json's top +// level beside externalId. +func checkNestedEnvelope(body map[string]any) error { + j, ok := body["json"].(map[string]any) + if !ok { + return fmt.Errorf("body has no object at .json: %v", body) + } + inner, ok := j["input"].(map[string]any) + if !ok { + return fmt.Errorf("submit envelope has no object at .json.input — the graph must be NESTED: %v", j) + } + if _, ok := inner["workflow"]; !ok { + return fmt.Errorf(".json.input carries no graph keys: %v", inner) + } + if _, leaked := j["workflow"]; leaked { + return fmt.Errorf("graph keys leaked to .json's top level (that is the whatIf shape): %v", j) + } + return nil +} + +// TestGenerate_GraphIsNestedUnderInput pins the MUTATION envelope. +func TestGenerate_GraphIsNestedUnderInput(t *testing.T) { + var body map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + raw, _ := io.ReadAll(r.Body) + if err := json.Unmarshal(raw, &body); err != nil { + t.Errorf("submit body is not JSON: %v", err) + } + writeTRPC(w, map[string]any{"id": "wf_123", "status": "processing"}) + })) + + res, _, _, err := c.GenerateFromGraph(context.Background(), + Graph{Workflow: "txt2img", Prompt: "a cat"}, SubmitOptions{Tags: []string{"cli"}}) + if err != nil { + t.Fatalf("GenerateFromGraph: %v", err) + } + if err := checkNestedEnvelope(body); err != nil { + t.Fatalf("submit envelope: %v", err) + } + if res.ID != "wf_123" { + t.Errorf("workflow id = %q, want wf_123", res.ID) + } +} + +// TestCheckNestedEnvelope_NegativeControl validates the assertion above: fed +// the whatIf (flat) shape and a graph-keys-leaked shape, it must FAIL. A +// checker that cannot go red says nothing about the real envelope. +func TestCheckNestedEnvelope_NegativeControl(t *testing.T) { + cases := map[string]string{ + "flat (the whatIf shape)": `{"json":{"workflow":"txt2img","externalId":"x"}}`, + "no json wrapper": `{"input":{"workflow":"txt2img"}}`, + "input present but empty": `{"json":{"input":{}}}`, + "graph keys duplicated": `{"json":{"input":{"workflow":"txt2img"},"workflow":"txt2img"}}`, + } + for name, raw := range cases { + var m map[string]any + if err := json.Unmarshal([]byte(raw), &m); err != nil { + t.Fatalf("%s: fixture is not JSON: %v", name, err) + } + if err := checkNestedEnvelope(m); err == nil { + t.Errorf("%s: checkNestedEnvelope accepted a bad shape", name) + } + } + // Positive control: the correct shape must pass. + var good map[string]any + if err := json.Unmarshal([]byte(`{"json":{"input":{"workflow":"txt2img"},"externalId":"x"}}`), &good); err != nil { + t.Fatal(err) + } + if err := checkNestedEnvelope(good); err != nil { + t.Errorf("checkNestedEnvelope rejected the correct shape: %v", err) + } +} + +// --------------------------------------------------------------------------- +// Unset fields must be ABSENT from the wire, never Go zero values. +// --------------------------------------------------------------------------- + +func marshalToMap(t *testing.T, v any) map[string]any { + t.Helper() + raw, err := json.Marshal(v) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var m map[string]any + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatalf("unmarshal to map: %v", err) + } + return m +} + +// TestGraph_UnsetFieldsAreAbsent is the key-absence guard. `steps: 0` is +// ACCEPTED by the server and silently prices a degenerate half-price job, so a +// Go zero value leaking onto the wire is a money bug, not a cosmetic one. +// +// It checks KEY PRESENCE on map[string]any, never strings.Contains: "cfg" +// substring-matches "cfgScale", so a text search cannot tell the two apart. +func TestGraph_UnsetFieldsAreAbsent(t *testing.T) { + m := marshalToMap(t, Graph{Workflow: "txt2img", Prompt: "a cat"}) + + for _, k := range []string{"steps", "cfgScale", "quantity", "seed", "sampler", "ecosystem", + "aspectRatio", "negativePrompt", "model", "resources"} { + if _, ok := m[k]; ok { + t.Errorf("unset field %q is PRESENT on the wire as %#v — it must be absent", k, m[k]) + } + } + for _, k := range []string{"workflow", "prompt"} { + if _, ok := m[k]; !ok { + t.Errorf("set field %q is missing from the wire: %v", k, m) + } + } +} + +// TestGraph_ZeroValueMarshalsToEmptyObject is the same guard in its widest +// form: it covers every field, including ones added later, so a new value-typed +// field without omitempty fails here without anyone remembering to list it. +func TestGraph_ZeroValueMarshalsToEmptyObject(t *testing.T) { + m := marshalToMap(t, Graph{}) + if len(m) != 0 { + t.Errorf("zero Graph marshalled to %d keys (%v); every optional field must be absent when unset", len(m), m) + } +} + +// TestGraph_ExplicitZeroIsSent is the other half of the pointer rationale: a +// caller that DELIBERATELY sets 0 must be able to, and that is exactly what a +// value-typed field with omitempty could not express. +func TestGraph_ExplicitZeroIsSent(t *testing.T) { + m := marshalToMap(t, Graph{Steps: Ptr(0), CfgScale: Ptr(0.0)}) + for _, k := range []string{"steps", "cfgScale"} { + v, ok := m[k] + if !ok { + t.Fatalf("explicitly-zero %q was dropped; unset and explicit-zero must stay distinguishable", k) + } + if v != 0.0 { + t.Errorf("%q = %v, want 0", k, v) + } + } +} + +// TestWhatIf_StripsPrompts pins that a cost estimate does not ship the user's +// prompt. The server substitutes its own placeholder for whatIf, so this cannot +// change the quote. +func TestWhatIf_StripsPrompts(t *testing.T) { + var got map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var env struct { + JSON map[string]any `json:"json"` + } + _ = json.Unmarshal([]byte(r.URL.Query().Get("input")), &env) + got = env.JSON + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}}) + })) + + g := Graph{Workflow: "txt2img", Prompt: "a secret prompt", NegativePrompt: "blurry"} + if _, _, err := c.WhatIfFromGraph(context.Background(), g); err != nil { + t.Fatalf("WhatIfFromGraph: %v", err) + } + for _, k := range []string{"prompt", "negativePrompt"} { + if _, ok := got[k]; ok { + t.Errorf("whatIf sent %q (%v); prompts must be stripped from a cost estimate", k, got[k]) + } + } + // The caller's graph must be untouched — the same value is submitted next. + if g.Prompt != "a secret prompt" || g.NegativePrompt != "blurry" { + t.Errorf("WhatIfFromGraph mutated the caller's graph: %+v", g) + } +} + +// --------------------------------------------------------------------------- +// externalId — unconditional on submit, never on whatIf. +// --------------------------------------------------------------------------- + +var uuidV4Re = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + +// TestGenerate_MintsExternalIDUnconditionally: the platform retries a submit 3x +// with the same body and adds no idempotency key of its own, so a missing +// externalId risks charging one user action up to three times. +func TestGenerate_MintsExternalIDUnconditionally(t *testing.T) { + var bodies []map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var m map[string]any + raw, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(raw, &m) + bodies = append(bodies, m) + writeTRPC(w, map[string]any{"id": "wf_1", "status": "processing"}) + })) + + seen := map[string]bool{} + for i := 0; i < 2; i++ { + _, returned, _, err := c.GenerateFromGraph(context.Background(), Graph{Workflow: "txt2img"}, SubmitOptions{}) + if err != nil { + t.Fatalf("GenerateFromGraph: %v", err) + } + j := bodies[i]["json"].(map[string]any) + id, ok := j["externalId"].(string) + if !ok || id == "" { + t.Fatalf("submit body has no externalId: %v", j) + } + if id != returned { + t.Errorf("returned externalId %q != the one sent %q", returned, id) + } + if !uuidV4Re.MatchString(id) { + t.Errorf("externalId %q is not a v4 UUID", id) + } + if seen[id] { + t.Errorf("externalId %q reused across submits — each submit needs its own key", id) + } + seen[id] = true + } +} + +// TestGenerate_ExternalIDOverride: an explicit id is passed through verbatim +// (this is how a re-attach after an interrupt reuses the original key). +func TestGenerate_ExternalIDOverride(t *testing.T) { + var body map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(raw, &body) + writeTRPC(w, map[string]any{"id": "wf_1"}) + })) + _, returned, _, err := c.GenerateFromGraph(context.Background(), + Graph{Workflow: "txt2img"}, SubmitOptions{ExternalID: "fixed-key-1"}) + if err != nil { + t.Fatalf("GenerateFromGraph: %v", err) + } + if returned != "fixed-key-1" { + t.Errorf("returned externalId = %q, want fixed-key-1", returned) + } + if got := body["json"].(map[string]any)["externalId"]; got != "fixed-key-1" { + t.Errorf("sent externalId = %v, want fixed-key-1", got) + } +} + +// TestWhatIf_NeverSendsExternalID: a whatIf carrying a matching key would +// return the pre-existing workflow and burn the key the submit needs. +func TestWhatIf_NeverSendsExternalID(t *testing.T) { + var rawQuery string + var input map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rawQuery = r.URL.RawQuery + var env map[string]any + _ = json.Unmarshal([]byte(r.URL.Query().Get("input")), &env) + input, _ = env["json"].(map[string]any) + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}}) + })) + + g := Graph{Workflow: "txt2img", Prompt: "a cat"} + if _, _, err := c.WhatIfFromGraph(context.Background(), g); err != nil { + t.Fatalf("WhatIfFromGraph: %v", err) + } + if _, ok := input["externalId"]; ok { + t.Errorf("whatIf graph carries externalId: %v", input) + } + // Widest form: the key must not appear ANYWHERE in the request line — + // neither as its own param nor inside the encoded input blob. + decoded, err := url.QueryUnescape(rawQuery) + if err != nil { + t.Fatalf("query unescape: %v", err) + } + if strings.Contains(strings.ToLower(decoded), "externalid") { + t.Errorf("whatIf request mentions externalId: %s", decoded) + } + // Positive control for that scan: it must be able to SEE the token when one + // is present, otherwise the clean result above proves nothing. + if !strings.Contains(strings.ToLower(decoded+"externalId"), "externalid") { + t.Fatal("the externalId scan cannot detect the token at all") + } +} + +// --------------------------------------------------------------------------- +// Error classification — pinned by errors.Is, never by message text. +// --------------------------------------------------------------------------- + +func TestGenerateErrors_Classification(t *testing.T) { + cases := []struct { + name string + status int + body string + want error + }{ + {"401", http.StatusUnauthorized, `{"error":{"json":{"message":"UNAUTHORIZED"}}}`, civitai.ErrUnauthorized}, + {"403", http.StatusForbidden, `{"error":{"json":{"message":"Insufficient funds"}}}`, civitai.ErrUnauthorized}, + {"400", http.StatusBadRequest, `{"error":{"json":{"message":"request is invalid"}}}`, civitai.ErrBadRequest}, + {"404", http.StatusNotFound, `{"message":"not found"}`, civitai.ErrNotFound}, + {"429", http.StatusTooManyRequests, `{"message":"slow down"}`, civitai.ErrRateLimited}, + {"503", http.StatusServiceUnavailable, `{"message":"down"}`, civitai.ErrNetwork}, + } + for _, tc := range cases { + t.Run("whatIf/"+tc.name, func(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}) + if err == nil { + t.Fatalf("status %d returned no error", tc.status) + } + if !errors.Is(err, tc.want) { + t.Errorf("errors.Is(err, %v) = false for status %d; err = %v", tc.want, tc.status, err) + } + }) + t.Run("generate/"+tc.name, func(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + _, _, _, err := c.GenerateFromGraph(context.Background(), Graph{Workflow: "txt2img"}, SubmitOptions{}) + if err == nil { + t.Fatalf("status %d returned no error", tc.status) + } + if !errors.Is(err, tc.want) { + t.Errorf("errors.Is(err, %v) = false for status %d; err = %v", tc.want, tc.status, err) + } + }) + } +} + +// TestGenerateErrors_500IsNotMisclassified: an unknown ecosystem arrives as a +// bare 500. It must NOT be tagged as an auth failure (which would tell a user +// to re-run `civitai login` for a typo). Design §7 wants it re-mapped to usage +// at the command surface; this layer must at least not lie about it. +func TestGenerateErrors_500IsNotMisclassified(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = io.WriteString(w, `{"error":{"json":{"message":"Unknown ecosystem: SDXLL"}}}`) + })) + _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img", Ecosystem: "SDXLL"}) + if err == nil { + t.Fatal("500 returned no error") + } + for _, kind := range []error{civitai.ErrUnauthorized, civitai.ErrBadRequest, civitai.ErrNotFound, + civitai.ErrRateLimited, civitai.ErrNetwork} { + if errors.Is(err, kind) { + t.Errorf("500 was classified as %v; it carries no kind today", kind) + } + } + if !strings.Contains(err.Error(), "Unknown ecosystem") { + t.Errorf("500 error dropped the server message: %v", err) + } +} + +// TestGenerateErrors_NoToken refuses before any request is made. +func TestGenerateErrors_NoToken(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("a request was sent without a token") + })) + c.Tokens = civitai.StaticToken("") + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{}); !errors.Is(err, civitai.ErrUnauthorized) { + t.Errorf("empty token: err = %v, want ErrUnauthorized", err) + } + if _, _, _, err := c.GenerateFromGraph(context.Background(), Graph{}, SubmitOptions{}); !errors.Is(err, civitai.ErrUnauthorized) { + t.Errorf("empty token: err = %v, want ErrUnauthorized", err) + } +} + +// TestMalformedEnvelope covers the shapes that unmarshal CLEANLY into a zero +// struct: a `null` payload would render as a free (total 0) quote. +func TestMalformedEnvelope(t *testing.T) { + cases := map[string]string{ + "null payload": `{"result":{"data":{"json":null}}}`, + "empty object": `{}`, + "no json key": `{"result":{"data":{}}}`, + "not json": `502 bad gateway`, + "bare array": `[]`, + "result is nul": `{"result":null}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, body) + })) + res, raw, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}) + if err == nil { + t.Fatalf("malformed envelope %q accepted: result=%+v raw=%s", body, res, raw) + } + if res != nil { + t.Errorf("malformed envelope returned a non-nil result: %+v", res) + } + sub, _, _, err := c.GenerateFromGraph(context.Background(), Graph{Workflow: "txt2img"}, SubmitOptions{}) + if err == nil { + t.Fatalf("malformed submit envelope %q accepted: %+v", body, sub) + } + }) + } +} + +// TestUnwrapTRPC_PositiveControl proves unwrapTRPC can actually observe a good +// payload — otherwise the rejections above could come from a function that +// rejects everything. +func TestUnwrapTRPC_PositiveControl(t *testing.T) { + payload, err := unwrapTRPC("test", []byte(`{"result":{"data":{"json":{"ready":true,"cost":{"total":60}}}}}`)) + if err != nil { + t.Fatalf("unwrapTRPC rejected a well-formed envelope: %v", err) + } + var out WhatIfResult + if err := json.Unmarshal(payload, &out); err != nil { + t.Fatalf("decode: %v", err) + } + if !out.Ready || out.Cost.Total != 60 { + t.Errorf("decoded = %+v, want ready + total 60", out) + } +} + +// --------------------------------------------------------------------------- +// Transport +// --------------------------------------------------------------------------- + +// refreshOnceSource returns a stale token until Refresh is called. +type refreshOnceSource struct { + refreshed bool + calls int +} + +func (s *refreshOnceSource) Token(context.Context) (string, error) { + if s.refreshed { + return "good", nil + } + return "stale", nil +} + +func (s *refreshOnceSource) Refresh(context.Context) (string, error) { + s.calls++ + s.refreshed = true + return "good", nil +} + +// TestAuthedDo_RefreshesOn401 pins the transparent-refresh replay for both the +// GET and the POST path. +func TestAuthedDo_RefreshesOn401(t *testing.T) { + var tokens []string + h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tok := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + tokens = append(tokens, tok) + if tok != "good" { + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":{"json":{"message":"expired"}}}`) + return + } + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}, "id": "wf_1"}) + }) + srv := httptest.NewServer(h) + defer srv.Close() + + src := &refreshOnceSource{} + c := NewWithSource(srv.URL, src) + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}); err != nil { + t.Fatalf("WhatIfFromGraph after refresh: %v", err) + } + if len(tokens) != 2 || tokens[0] != "stale" || tokens[1] != "good" { + t.Fatalf("tokens = %v, want [stale good]", tokens) + } + + // The POST body must survive the replay. + var replayed []map[string]any + src2 := &refreshOnceSource{} + srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var m map[string]any + raw, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(raw, &m) + replayed = append(replayed, m) + if strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") != "good" { + w.WriteHeader(http.StatusUnauthorized) + return + } + writeTRPC(w, map[string]any{"id": "wf_1"}) + })) + defer srv2.Close() + c2 := NewWithSource(srv2.URL, src2) + _, id, _, err := c2.GenerateFromGraph(context.Background(), Graph{Workflow: "txt2img"}, SubmitOptions{}) + if err != nil { + t.Fatalf("GenerateFromGraph after refresh: %v", err) + } + if len(replayed) != 2 { + t.Fatalf("submit attempts = %d, want 2", len(replayed)) + } + // 🔴 The replayed body must carry the SAME externalId, or the refresh retry + // would be a second charge. + first := replayed[0]["json"].(map[string]any)["externalId"] + second := replayed[1]["json"].(map[string]any)["externalId"] + if first != second || first != id { + t.Errorf("replayed submit changed externalId (%v -> %v, returned %v); the retry must dedupe", first, second, id) + } +} + +// TestNewExternalID_Format/uniqueness — the key itself. +func TestNewExternalID(t *testing.T) { + seen := map[string]bool{} + for i := 0; i < 64; i++ { + id, err := NewExternalID() + if err != nil { + t.Fatalf("NewExternalID: %v", err) + } + if !uuidV4Re.MatchString(id) { + t.Fatalf("NewExternalID = %q, not an RFC 4122 v4 UUID", id) + } + if seen[id] { + t.Fatalf("NewExternalID repeated %q", id) + } + seen[id] = true + } +} + +// TestResponseBodyCap: an over-cap body is an error, not silently truncated +// JSON. +func TestResponseBodyCap(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, `{"result":{"data":{"json":{"ready":true,"cost":{"total":60,"pad":"`+ + strings.Repeat("x", 4096)+`"}}}}}`) + })) + c.MaxResponseBody = 128 + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}); err == nil { + t.Fatal("over-cap body was accepted") + } else if !strings.Contains(err.Error(), "limit") { + t.Errorf("over-cap error = %v, want a limit error", err) + } + // Positive control: under the cap the same client succeeds. + c.MaxResponseBody = 1 << 20 + if _, _, err := c.WhatIfFromGraph(context.Background(), Graph{Workflow: "txt2img"}); err != nil { + t.Errorf("under-cap body rejected: %v", err) + } +} diff --git a/internal/genapi/graph.go b/internal/genapi/graph.go new file mode 100644 index 00000000..4bb62eb9 --- /dev/null +++ b/internal/genapi/graph.go @@ -0,0 +1,206 @@ +package genapi + +import ( + "bytes" + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// Graph is the generation-graph payload — the ONE payload struct both +// orchestrator procedures carry. The two procedures wrap it in DIFFERENT +// envelopes (see generate.go); the graph itself is identical. +// +// 🔴 EVERY optional field is a pointer or `omitempty`, so an unset field is +// ABSENT from the marshalled JSON rather than a Go zero value. This is not +// style — the server is permissive, not a validator: +// +// - `steps: 0` is ACCEPTED and prices a degenerate, cheaper, wrong job +// (measured: the steps cost factor drops to 0.333 from 1). +// - `quantity: 0` / out-of-range values are CLAMPED silently, with no error. +// - `cfgScale: 0` is accepted the same way. +// +// A value-typed field would therefore turn "the user did not pass --steps" +// into "the user asked for a broken job", HTTP 200, billed. Pointers also keep +// "unset" distinguishable from "explicitly zero", which a later `--input` +// round-trip needs. +// +// Field names track the server's declared graph nodes EXACTLY +// (civitai/civitai -> src/shared/data-graph/generation/). An UNDECLARED key is +// silently DROPPED server-side (`_validate` copies only declared node keys), so +// a typo here is a no-op that reports success — never add a key without +// checking it against the graph definitions. +type Graph struct { + // Workflow is the generation mode, e.g. "txt2img". + Workflow string `json:"workflow,omitempty"` + // Ecosystem selects the model family, e.g. "SDXL". It is OMITTABLE, but its + // default is NOT a stable fact: the server resolves it against the caller's + // usable (non-disabled, non-memberOnly) ecosystems, so a free-tier account + // and a member account can resolve to different models at different prices. + // Callers must report which ecosystem the server actually used. + Ecosystem string `json:"ecosystem,omitempty"` + // Prompt is the positive prompt. It is STRIPPED from whatIf calls (see + // whatIfGraph) — it does not affect cost, and the server defaults it. + Prompt string `json:"prompt,omitempty"` + // NegativePrompt is stripped from whatIf calls for the same reason. + NegativePrompt string `json:"negativePrompt,omitempty"` + // Quantity is the number of outputs. The server CLAMPS out-of-range values + // (measured: 10000 -> 10, -5 -> 1) without an error, so the effective value + // must be read back from the response rather than assumed. + Quantity *int `json:"quantity,omitempty"` + // AspectRatio is a bucket string, e.g. "1:1"; width/height derive from it. + AspectRatio string `json:"aspectRatio,omitempty"` + // Model is the checkpoint. Unlike Resources, this node coerces a bare id, + // so {id} alone is accepted. A NONEXISTENT id is still accepted with HTTP + // 200 and the ecosystem default silently substituted — resolve it first + // (see ResolveModelVersion). + Model *Resource `json:"model,omitempty"` + // Resources are the additional networks (LoRAs). 🔴 Each entry REQUIRES + // `model:{type}`: a bare id, and `{id}` alone, are both rejected with + // 400 "expected object, received undefined". The type comes from + // ResolveModelVersion. + Resources []Resource `json:"resources,omitempty"` + // Steps, CfgScale, Sampler and Seed are the silently-degrading parameters + // (see the type comment). They are carried here so the transport is + // complete and the absence rule is pinned; no flag sets them yet. + Steps *int `json:"steps,omitempty"` + CfgScale *float64 `json:"cfgScale,omitempty"` + Sampler string `json:"sampler,omitempty"` + Seed *int `json:"seed,omitempty"` + + // Raw, when non-nil, IS the graph: MarshalJSON emits it VERBATIM and every + // typed field above is ignored. It is the `--input` passthrough. + // + // 🔴 It exists so a caller-supplied graph reaches the server UNCHANGED. The + // whole point of a raw-graph surface is that the CLI carries no per-engine + // code for the platform's ~51 ecosystem graphs; round-tripping such a file + // through the typed struct above would silently DELETE every key this struct + // does not model, which is worse than the server's own silent-drop behaviour + // because it happens before the request is even sent. + // + // It is `json:"-"` so the typed path can never emit it as a field, and it is + // deliberately NOT settable from a decoded server payload — nothing in this + // package unmarshals into a Graph. + Raw json.RawMessage `json:"-"` +} + +// MarshalJSON emits Raw verbatim when it is set, and the typed fields otherwise. +// +// Raw is passed through json.Compact rather than returned as-is: Compact both +// VALIDATES it (encoding/json does not check what a MarshalJSON implementation +// returns beyond re-scanning it, and a malformed byte slice would corrupt the +// whole envelope) and normalises the whitespace of a hand-edited file. +// +// The `graphAlias` indirection is what stops this from recursing: a named type +// with the same fields has no methods, so json.Marshal falls back to the +// reflect-based encoder for it. +func (g Graph) MarshalJSON() ([]byte, error) { + if g.Raw != nil { + var buf bytes.Buffer + if err := json.Compact(&buf, g.Raw); err != nil { + return nil, fmt.Errorf("raw graph is not valid JSON: %w", err) + } + return buf.Bytes(), nil + } + type graphAlias Graph + return json.Marshal(graphAlias(g)) +} + +// Resource is one graph resource reference (a checkpoint or an additional +// network). +type Resource struct { + ID int `json:"id"` + // Model carries the resource's model TYPE. It is REQUIRED inside + // Graph.Resources and optional on Graph.Model. A WRONG type is silently + // accepted (a LoRA sent as {type:"Checkpoint"} returns 200), so it must come + // from a live lookup, never a guess. + Model *ResourceModel `json:"model,omitempty"` + // Strength is the additional-network weight; unset means the server default. + Strength *float64 `json:"strength,omitempty"` +} + +// ResourceModel is the `model` sub-object of a graph resource. +type ResourceModel struct { + Type string `json:"type"` +} + +// whatIfGraph returns a COPY of g suitable for a cost estimate: the prompt +// fields are removed. +// +// The web deliberately strips them ("they don't affect cost and shouldn't be +// sent to the server until actual submission"), and the server's whatIf path +// substitutes its own defaults for exactly this case — `whatIfFromGraph` +// spreads the caller's input over its own defaults (prompt "cost-estimation", +// negativePrompt empty) before +// validating (civitai/civitai -> +// src/server/services/orchestrator/orchestration-new.service.ts). So dropping +// them cannot change the quote, and it stops shipping the user's prompt on +// every estimate. +// +// It returns a copy: the caller's Graph must be unchanged, because the SAME +// Graph is submitted afterwards and it needs its prompt. +// +// A RAW graph (--input) is stripped the same way, by deleting the two keys from +// the decoded object rather than by re-marshalling a typed struct — every other +// key, including ones this package does not model, must survive untouched. A raw +// graph that does not decode as a JSON object is passed through unchanged: it is +// the server's business to reject it, and inventing a local parse error here +// would be a validation rule this CLI has no authority to enforce. +func whatIfGraph(g Graph) Graph { + out := g + if g.Raw != nil { + out.Raw = stripPromptKeys(g.Raw) + return out + } + out.Prompt = "" + out.NegativePrompt = "" + return out +} + +// stripPromptKeys removes `prompt`/`negativePrompt` from a raw graph object, +// leaving every other key byte-identical. It returns the input unchanged when it +// is not a JSON object. +func stripPromptKeys(raw json.RawMessage) json.RawMessage { + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil { + return raw + } + delete(obj, "prompt") + delete(obj, "negativePrompt") + out, err := json.Marshal(obj) + if err != nil { + return raw + } + return out +} + +// KnownGraphKeys returns the set of top-level JSON keys this CLI's Graph models. +// +// 🔴 It is derived by REFLECTION over the struct tags, never hand-listed. A +// second hand-maintained list would drift from the struct the moment a field is +// added, and the only consumer is a warning about keys the CLI does not +// recognise — a warning built from a stale list warns about the wrong things. +// +// This is emphatically NOT a mirror of the server's node registry, and must +// never become one: it answers "does the CLI model this key?", not "does the +// server accept it?". The server owns ~51 ecosystem graphs whose node sets this +// package deliberately does not vendor. +func KnownGraphKeys() map[string]bool { + out := make(map[string]bool) + t := reflect.TypeOf(Graph{}) + for i := 0; i < t.NumField(); i++ { + tag := t.Field(i).Tag.Get("json") + name, _, _ := strings.Cut(tag, ",") + if name == "" || name == "-" { + continue + } + out[name] = true + } + return out +} + +// Ptr returns a pointer to v. Every optional Graph field is a pointer so that +// "unset" is absent from the wire (see the Graph doc comment); this is how a +// caller sets one from a literal. +func Ptr[T any](v T) *T { return &v } diff --git a/internal/genapi/status.go b/internal/genapi/status.go new file mode 100644 index 00000000..130772ad --- /dev/null +++ b/internal/genapi/status.go @@ -0,0 +1,330 @@ +package genapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strings" +) + +// GetWorkflowPath is the read-back query for one workflow. +// +// 🔴 It is deliberately `getWorkflow` and NOT `statusUpdate`, even though +// statusUpdate returns a smaller projection that looks better suited to a poll. +// Two reasons, both measured against the platform source +// (civitai/civitai -> src/server/routers/orchestrator.router.ts): +// +// - `statusUpdate` is an `orchestratorGuardedProcedure` (:593) while +// `getWorkflow` is a plain `orchestratorProcedure` (:203). The guard rejects a +// MUTED user — so polling through statusUpdate would leave a restricted user +// unable to read a workflow they had ALREADY PAID FOR. Reading is not +// spending; it must not be gated behind the spend guard. +// - `statusUpdate` is `getWorkflow(...)` plus a projection that DROPS the +// workflow `metadata` (:2854-2861), which is where per-output user state +// (the `hidden` flag) lives. +// +// Neither procedure is cached: the "3s server-side feed cache" that an earlier +// design revision cited is `QUERIED_WORKFLOWS_CACHE_TTL`, which belongs to +// `queryGeneratedImages`, not to this route. `getWorkflow` proxies straight +// through to the orchestrator. See PollConfig for what follows from that. +const GetWorkflowPath = "/api/trpc/orchestrator.getWorkflow" + +// The orchestrator's workflow statuses, verbatim from the generated client's +// WorkflowStatus enum (@civitai/client -> types.gen.d.ts). There is no "pending" +// — a workflow that has not started yet is `unassigned`, `preparing` or +// `scheduled`. +const ( + StatusUnassigned = "unassigned" + StatusPreparing = "preparing" + StatusScheduled = "scheduled" + StatusProcessing = "processing" + StatusSucceeded = "succeeded" + StatusFailed = "failed" + StatusExpired = "expired" + StatusCanceled = "canceled" +) + +// terminalStatuses are the four statuses a workflow never leaves. +var terminalStatuses = map[string]bool{ + StatusSucceeded: true, + StatusFailed: true, + StatusExpired: true, + StatusCanceled: true, +} + +// IsTerminalStatus reports whether s is a status a workflow never leaves. +// +// It fails toward KEEPING WAITING: an unrecognised status is reported +// non-terminal, so a status the platform adds after this build makes the poll +// run to its --timeout and print the re-attach command, rather than declaring a +// result the CLI cannot actually interpret. A wrong "done" is much worse than a +// slow "still waiting" — the first reports a fabricated outcome for a job the +// user paid for. +func IsTerminalStatus(s string) bool { + return terminalStatuses[strings.ToLower(strings.TrimSpace(s))] +} + +// Blob is one orchestrator output blob as it appears on the RAW workflow. +// +// 🔴 The field set here is the RAW `Blob`/`ImageBlob` from the orchestrator +// client, NOT the site's `NormalizedWorkflowStepOutput`. `orchestrator.getWorkflow` +// returns the orchestrator's own workflow untouched (router :203-207 hands the +// client result straight back), while the normalized shape is only produced by +// `formatGenerationResponse2` on OTHER routes. Two consequences that are easy to +// get wrong, and that a normalized-shape reader would silently get zero values +// for: +// +// - `hidden` is NOT a blob field. It lives in the STEP's metadata, keyed by +// blob id (`metadata.output[].hidden`, legacy `metadata.images[]`). +// See stepMetadata. +// - `seed` is NOT a blob field either. It is `metadata.params.seed` plus the +// blob's index within the step. +type Blob struct { + ID string `json:"id"` + Type string `json:"type"` + // Available reports that the blob has landed and its URL is fetchable. + Available bool `json:"available"` + // URL is presigned and EXPIRES (see URLExpiresAt). It needs no bearer token + // — and must not be sent one; see the download seam in internal/cmd. + URL *string `json:"url"` + URLExpiresAt *string `json:"urlExpiresAt"` + NSFWLevel *string `json:"nsfwLevel"` + // BlockedReason is set only when moderation blocked the blob. + BlockedReason *string `json:"blockedReason"` + Width *int `json:"width"` + Height *int `json:"height"` +} + +// stepOutput covers the output containers an image-producing step can use. The +// orchestrator's step output is a discriminated union keyed on the step's +// `$type`; rather than vendor the 51-engine table (this repo's anti-mirror +// rule), all three image-shaped containers are read and whichever is populated +// wins. `textToImage`/`imageGen` fill `images`, `comfy` fills `blobs`, and the +// upscaler/preprocess steps fill the single `blob`. +type stepOutput struct { + Images []Blob `json:"images"` + Blobs []Blob `json:"blobs"` + Blob *Blob `json:"blob"` +} + +// stepMetadata is the per-step user metadata. It carries the two fields the raw +// blob does not: the per-output `hidden` flag and the job's seed. +type stepMetadata struct { + // Output is the current per-blob metadata map, keyed by blob id. + Output map[string]outputMeta `json:"output"` + // Images is the LEGACY name for the same map (pre-rename workflows). The + // site merges both with the new key winning per field; a workflow submitted + // before the rename only has this one, so ignoring it would read `hidden` + // as false for every output of an older workflow. + Images map[string]outputMeta `json:"images"` + Params struct { + Seed *int64 `json:"seed"` + } `json:"params"` +} + +type outputMeta struct { + Hidden bool `json:"hidden"` +} + +// hiddenFor reports the effective `hidden` flag for a blob id, with the current +// key winning over the legacy one. +func (m stepMetadata) hiddenFor(id string) bool { + if v, ok := m.Output[id]; ok { + return v.Hidden + } + if v, ok := m.Images[id]; ok { + return v.Hidden + } + return false +} + +// Step is one workflow step. +type Step struct { + Type string `json:"$type"` + Name string `json:"name"` + Status string `json:"status"` + Metadata stepMetadata `json:"metadata"` + Output stepOutput `json:"output"` +} + +// blobs returns the step's outputs from whichever container the step populated. +func (s Step) blobs() []Blob { + switch { + case len(s.Output.Images) > 0: + return s.Output.Images + case len(s.Output.Blobs) > 0: + return s.Output.Blobs + case s.Output.Blob != nil: + return []Blob{*s.Output.Blob} + } + return nil +} + +// Workflow is the orchestrator workflow as `orchestrator.getWorkflow` returns +// it. Only the fields the CLI reports on are modelled; the raw payload travels +// alongside for `--json`. +type Workflow struct { + ID string `json:"id"` + Status string `json:"status"` + CreatedAt string `json:"createdAt"` + StartedAt *string `json:"startedAt"` + CompletedAt *string `json:"completedAt"` + Tags []string + Steps []Step `json:"steps"` + // Transactions is the orchestrator's own money record, passed through + // untyped: its shape is orchestrator-owned and the CLI must not relabel it. + Transactions json.RawMessage `json:"transactions,omitempty"` +} + +// Output is one workflow output with the two step-derived fields folded in. +type Output struct { + Blob + // StepName / StepStatus identify the producing step. + StepName string + StepStatus string + // Index is the blob's position within its step, which is what makes Seed + // per-output rather than per-step. + Index int + // Hidden is the user's per-output "deleted" flag, read from the step + // metadata (it is not on the blob). + Hidden bool + // Seed is the step's seed offset by Index, or nil when the step recorded + // none. + Seed *int64 +} + +// Outputs flattens every step's outputs, folding in the step-derived `hidden` +// and `seed` fields. It applies NO filtering — see Deliverable. +func (w *Workflow) Outputs() []Output { + var out []Output + for _, st := range w.Steps { + blobs := st.blobs() + for i, b := range blobs { + o := Output{ + Blob: b, + StepName: st.Name, + StepStatus: st.Status, + Index: i, + Hidden: st.Metadata.hiddenFor(b.ID), + } + if s := st.Metadata.Params.Seed; s != nil { + v := *s + int64(i) + o.Seed = &v + } + out = append(out, o) + } + } + return out +} + +// Deliverable reports whether an output is a real, fetchable result. +// +// 🔴 This is the site's own predicate, verbatim: +// +// output.filter((x) => x.available && !x.blockedReason && !x.hidden) +// +// (civitai/civitai -> src/shared/orchestrator/workflow-data.ts:222, +// `succeededOutput`.) A `succeeded` workflow can legitimately contain outputs +// that are none of those things: moderation-blocked, not-yet-landed (the worker +// finished but the blob upload did not), or user-hidden. A caller that skips +// this reports success and silently writes fewer files than --quantity asked +// for, with no signal — which is why the CLI reports the excluded ones by REASON +// rather than just downloading what is left. +func Deliverable(o Output) bool { + return o.Available && !hasBlockedReason(o) && !o.Hidden +} + +func hasBlockedReason(o Output) bool { + return o.BlockedReason != nil && strings.TrimSpace(*o.BlockedReason) != "" +} + +// ExclusionReason returns why an output is NOT deliverable, or "" when it is. +// The reasons are checked in the same order the predicate ANDs them, so an +// output failing several reports the first — the one closest to the cause. +func ExclusionReason(o Output) string { + switch { + case !o.Available: + return "not available (the job finished without producing a usable file)" + case hasBlockedReason(o): + return "blocked by moderation: " + strings.TrimSpace(*o.BlockedReason) + case o.Hidden: + return "hidden (you deleted this result on the website)" + } + return "" +} + +// PartitionOutputs splits a workflow's outputs into the deliverable ones and the +// excluded ones, so a caller can report BOTH rather than quietly shipping the +// remainder. +func PartitionOutputs(w *Workflow) (kept, excluded []Output) { + for _, o := range w.Outputs() { + if Deliverable(o) { + kept = append(kept, o) + } else { + excluded = append(excluded, o) + } + } + return kept, excluded +} + +// GetWorkflow reads one workflow by id. It is a READ — it spends nothing. +// +// It returns the decoded workflow AND the raw unwrapped payload, so a `--json` +// surface can pass through server fields this struct does not model. +func (c *Client) GetWorkflow(ctx context.Context, workflowID string) (*Workflow, json.RawMessage, error) { + id := strings.TrimSpace(workflowID) + if id == "" { + return nil, nil, fmt.Errorf("a workflow id is required") + } + inputJSON, err := json.Marshal(struct { + JSON struct { + WorkflowID string `json:"workflowId"` + } `json:"json"` + }{JSON: struct { + WorkflowID string `json:"workflowId"` + }{WorkflowID: id}}) + if err != nil { + return nil, nil, err + } + q := url.Values{} + q.Set("input", string(inputJSON)) + reqURL := c.BaseURL + GetWorkflowPath + "?" + q.Encode() + + build := func() (*http.Request, error) { + return http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + } + status, raw, err := c.authedDo(ctx, build) + if err != nil { + return nil, nil, err + } + if status != http.StatusOK { + return nil, nil, generateError("getWorkflow", status, raw) + } + payload, err := unwrapTRPC("orchestrator.getWorkflow", raw) + if err != nil { + return nil, nil, err + } + var out Workflow + if err := json.Unmarshal(payload, &out); err != nil { + return nil, nil, fmt.Errorf("unexpected orchestrator.getWorkflow payload: %s", string(payload)) + } + if out.ID == "" { + // The orchestrator's id field is nullable; fall back to what was asked + // for so downstream output never renders an empty handle. + out.ID = id + } + return &out, payload, nil +} + +// StatusOf returns an APIError's HTTP status, or 0 when err is not one. It backs +// the poll loop's 429/5xx retry decision without re-parsing message text. +func StatusOf(err error) int { + var apiErr *APIError + if errors.As(err, &apiErr) { + return apiErr.Status + } + return 0 +} diff --git a/internal/genapi/status_test.go b/internal/genapi/status_test.go new file mode 100644 index 00000000..9bc5196c --- /dev/null +++ b/internal/genapi/status_test.go @@ -0,0 +1,258 @@ +package genapi + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/civitai/cli/pkg/civitai" +) + +// trpcOK wraps a payload in the tRPC success envelope. +func trpcOK(payload string) string { + return `{"result":{"data":{"json":` + payload + `}}}` +} + +// statusServer serves one scripted getWorkflow reply and records the requests. +func statusServer(t *testing.T, handler http.HandlerFunc) (*Client, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + c := New(srv.URL, "tok") + return c, srv +} + +func TestGetWorkflow_SendsTheWorkflowIdInTheTRPCInput(t *testing.T) { + var gotInput string + var gotPath string + c, _ := statusServer(t, func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotInput = r.URL.Query().Get("input") + _, _ = w.Write([]byte(trpcOK(`{"id":"wf_1","status":"processing","steps":[]}`))) + }) + + wf, raw, err := c.GetWorkflow(context.Background(), "wf_1") + if err != nil { + t.Fatalf("GetWorkflow: %v", err) + } + if gotPath != GetWorkflowPath { + t.Errorf("path = %q, want %q", gotPath, GetWorkflowPath) + } + // Pin the ENVELOPE by decoding it, not by substring-matching: a wrongly + // nested input would still contain the id as a substring. + var env struct { + JSON map[string]any `json:"json"` + } + if err := json.Unmarshal([]byte(gotInput), &env); err != nil { + t.Fatalf("input is not JSON: %q", gotInput) + } + if env.JSON["workflowId"] != "wf_1" { + t.Errorf("input.json.workflowId = %v, want wf_1 (input was %q)", env.JSON["workflowId"], gotInput) + } + if wf.Status != "processing" { + t.Errorf("status = %q", wf.Status) + } + if len(raw) == 0 { + t.Error("raw payload must be returned for --json passthrough") + } +} + +func TestGetWorkflow_ErrorsAreClassifiedByStatus(t *testing.T) { + cases := []struct { + name string + status int + want error + }{ + {"unauthorized", http.StatusUnauthorized, civitai.ErrUnauthorized}, + {"forbidden", http.StatusForbidden, civitai.ErrUnauthorized}, + {"not found", http.StatusNotFound, civitai.ErrNotFound}, + {"rate limited", http.StatusTooManyRequests, civitai.ErrRateLimited}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c, _ := statusServer(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(`{"error":{"json":{"message":"nope"}}}`)) + }) + _, _, err := c.GetWorkflow(context.Background(), "wf_1") + if !errors.Is(err, tc.want) { + t.Errorf("status %d: errors.Is(err, %v) = false; err = %v", tc.status, tc.want, err) + } + // The poll loop branches on this, not on message text. + if got := StatusOf(err); got != tc.status { + t.Errorf("StatusOf = %d, want %d", got, tc.status) + } + }) + } +} + +func TestGetWorkflow_RejectsAnEmptyId(t *testing.T) { + c := New("https://example.invalid", "tok") + if _, _, err := c.GetWorkflow(context.Background(), " "); err == nil { + t.Fatal("empty workflow id: want an error, got nil") + } +} + +// A null tRPC payload must be rejected, not decoded into a zero Workflow that +// would render as "status (empty), 0 outputs" for a job the user paid for. +func TestGetWorkflow_RejectsANullPayload(t *testing.T) { + c, _ := statusServer(t, func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(trpcOK(`null`))) + }) + if _, _, err := c.GetWorkflow(context.Background(), "wf_1"); err == nil { + t.Fatal("null payload: want an error, got nil") + } +} + +func TestIsTerminalStatus(t *testing.T) { + terminal := []string{StatusSucceeded, StatusFailed, StatusExpired, StatusCanceled, "SUCCEEDED", " failed "} + for _, s := range terminal { + if !IsTerminalStatus(s) { + t.Errorf("IsTerminalStatus(%q) = false, want true", s) + } + } + // Everything else keeps waiting — including a status this build has never + // heard of. Reporting an unknown status as terminal would fabricate an + // outcome; reporting it as non-terminal costs a --timeout at worst. + nonTerminal := []string{StatusUnassigned, StatusPreparing, StatusScheduled, StatusProcessing, "", "quantum-superposition"} + for _, s := range nonTerminal { + if IsTerminalStatus(s) { + t.Errorf("IsTerminalStatus(%q) = true, want false", s) + } + } +} + +// The output filter is the guard that stops `generate` from reporting success +// while writing fewer files than the user paid for. Every exclusion reason is +// driven independently, and the kept set is checked by ID so a filter that +// dropped everything (or nothing) cannot pass. +func TestPartitionOutputs_FiltersBlockedUnavailableAndHidden(t *testing.T) { + payload := `{ + "id":"wf_1","status":"succeeded", + "steps":[{ + "$type":"textToImage","name":"step-1","status":"succeeded", + "metadata":{"params":{"seed":100},"output":{"c":{"hidden":true}}}, + "output":{"images":[ + {"id":"a","type":"image","available":true,"url":"https://x/a.jpeg","width":512,"height":512}, + {"id":"b","type":"image","available":true,"url":"https://x/b.jpeg","blockedReason":"minor"}, + {"id":"c","type":"image","available":true,"url":"https://x/c.jpeg"}, + {"id":"d","type":"image","available":false,"url":null}, + {"id":"e","type":"image","available":true,"url":"https://x/e.jpeg"} + ]} + }] + }` + var wf Workflow + if err := json.Unmarshal([]byte(payload), &wf); err != nil { + t.Fatalf("decode: %v", err) + } + + kept, excluded := PartitionOutputs(&wf) + var keptIDs, exclIDs []string + for _, o := range kept { + keptIDs = append(keptIDs, o.ID) + } + for _, o := range excluded { + exclIDs = append(exclIDs, o.ID) + } + if strings.Join(keptIDs, ",") != "a,e" { + t.Errorf("kept = %v, want [a e]", keptIDs) + } + if strings.Join(exclIDs, ",") != "b,c,d" { + t.Errorf("excluded = %v, want [b c d] (blocked, hidden, unavailable)", exclIDs) + } + + // Each exclusion must report ITS OWN reason — a single generic string would + // pass a "some reason was printed" assertion while telling the user nothing. + reasons := map[string]string{} + for _, o := range excluded { + reasons[o.ID] = ExclusionReason(o) + } + if !strings.Contains(reasons["b"], "moderation") || !strings.Contains(reasons["b"], "minor") { + t.Errorf("blocked reason = %q, want the moderation reason echoed", reasons["b"]) + } + if !strings.Contains(reasons["c"], "hidden") { + t.Errorf("hidden reason = %q", reasons["c"]) + } + if !strings.Contains(reasons["d"], "not available") { + t.Errorf("unavailable reason = %q", reasons["d"]) + } + if r := ExclusionReason(kept[0]); r != "" { + t.Errorf("a deliverable output must have no exclusion reason, got %q", r) + } + + // Seed is per-OUTPUT (step seed + index), not per-step. + seedOf := func(o Output) string { + if o.Seed == nil { + return "" + } + return fmt.Sprint(*o.Seed) + } + if kept[0].Seed == nil || *kept[0].Seed != 100 { + t.Errorf("output %s seed = %s, want 100", kept[0].ID, seedOf(kept[0])) + } + if kept[1].Seed == nil || *kept[1].Seed != 104 { + t.Errorf("output %s seed = %s, want 104 (index 4)", kept[1].ID, seedOf(kept[1])) + } + if kept[0].Width == nil || *kept[0].Width != 512 { + t.Errorf("width not decoded: %v", kept[0].Width) + } +} + +// `hidden` lives in the step metadata under the CURRENT key `output` and the +// LEGACY key `images`. A reader that only knows the current key reports every +// output of a pre-rename workflow as visible — and then downloads results the +// user deleted. +func TestPartitionOutputs_HonoursTheLegacyHiddenMetadataKey(t *testing.T) { + payload := `{ + "id":"wf_1","status":"succeeded", + "steps":[{ + "$type":"textToImage","name":"s","status":"succeeded", + "metadata":{"images":{"a":{"hidden":true}}}, + "output":{"images":[{"id":"a","type":"image","available":true,"url":"https://x/a.jpeg"}]} + }] + }` + var wf Workflow + if err := json.Unmarshal([]byte(payload), &wf); err != nil { + t.Fatalf("decode: %v", err) + } + kept, excluded := PartitionOutputs(&wf) + if len(kept) != 0 || len(excluded) != 1 { + t.Fatalf("legacy hidden key ignored: kept=%d excluded=%d", len(kept), len(excluded)) + } + if !strings.Contains(ExclusionReason(excluded[0]), "hidden") { + t.Errorf("reason = %q", ExclusionReason(excluded[0])) + } +} + +// The three output containers a raw orchestrator step can use. `images` is the +// image path, `blobs` the comfy path, `blob` the upscaler path — reading only +// one of them silently yields zero outputs for the others. +func TestWorkflowOutputs_ReadsEveryStepOutputContainer(t *testing.T) { + cases := []struct { + name string + output string + wantIDs int + }{ + {"images", `{"images":[{"id":"a","available":true},{"id":"b","available":true}]}`, 2}, + {"blobs", `{"blobs":[{"id":"a","available":true}]}`, 1}, + {"blob", `{"blob":{"id":"a","available":true}}`, 1}, + {"empty", `{}`, 0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var wf Workflow + payload := `{"id":"w","status":"succeeded","steps":[{"$type":"x","name":"s","status":"succeeded","output":` + tc.output + `}]}` + if err := json.Unmarshal([]byte(payload), &wf); err != nil { + t.Fatalf("decode: %v", err) + } + if got := len(wf.Outputs()); got != tc.wantIDs { + t.Errorf("outputs = %d, want %d", got, tc.wantIDs) + } + }) + } +} diff --git a/internal/genapi/versions.go b/internal/genapi/versions.go new file mode 100644 index 00000000..51d3410b --- /dev/null +++ b/internal/genapi/versions.go @@ -0,0 +1,99 @@ +package genapi + +import ( + "context" + "fmt" + "strconv" + + "github.com/civitai/cli/pkg/civitai" +) + +// ResolvedVersion is what a model-version id resolves to: the model TYPE the +// graph requires, plus the names a confirmation prompt should show. +type ResolvedVersion struct { + // VersionID is the id that was resolved. + VersionID int + // VersionName is the version's own name, e.g. "v8". + VersionName string + // ModelName is the parent model's name, e.g. "DreamShaper". + ModelName string + // ModelType is the graph-required type, e.g. "Checkpoint", "LORA". + ModelType string + // BaseModel is the version's base model, e.g. "SDXL 1.0". Informational. + BaseModel string +} + +// DisplayName renders the resolved version for a human confirmation, so the +// user approves a NAME rather than an integer. +func (r *ResolvedVersion) DisplayName() string { + switch { + case r.ModelName != "" && r.VersionName != "": + return r.ModelName + " — " + r.VersionName + case r.ModelName != "": + return r.ModelName + case r.VersionName != "": + return r.VersionName + default: + return strconv.Itoa(r.VersionID) + } +} + +// Resource builds the graph resource reference for this version. The model +// type is carried because Graph.Resources entries REQUIRE `model:{type}` — a +// bare id, or `{id}` alone, is rejected with a 400. +func (r *ResolvedVersion) Resource(strength *float64) Resource { + return Resource{ + ID: r.VersionID, + Model: &ResourceModel{Type: r.ModelType}, + Strength: strength, + } +} + +// ResolveModelVersion resolves a model-version id via the existing PUBLIC read +// route GET /api/v1/model-versions/{id}. +// +// It exists for two reasons, both of which are about money: +// +// 1. Graph.Resources entries REQUIRE the model type, which is not derivable +// from a version id, and a WRONG type is silently accepted (a LoRA sent as +// {type:"Checkpoint"} returns 200 with the cost unchanged). So the type has +// to come from a live lookup, never a guess. +// 2. It converts a nonexistent checkpoint id from a SILENT SUBSTITUTED CHARGE +// into a hard local 404. Measured: on one ecosystem the correct model id +// priced at 160, while a nonexistent id, a foreign-ecosystem id, and no +// model at all ALL priced at 60 — the server substitutes the ecosystem +// default, and that correction is surfaced on-site but is invisible through +// a non-browser path. +// +// This is a live round-trip, NOT a vendored table, so it carries no drift cost +// against the platform — the distinction that makes it the right fix under this +// repo's anti-mirror rule. +// +// Errors carry the read SDK's classification (a missing version is tagged +// civitai.ErrNotFound), so exit codes stay pinned by errors.Is. +func (c *Client) ResolveModelVersion(ctx context.Context, id int) (*ResolvedVersion, error) { + if id <= 0 { + return nil, civitai.Tag(civitai.ErrBadRequest, + fmt.Errorf("invalid model-version id %d — pass the numeric id from a model's version URL (…/models/?modelVersionId=)", id)) + } + getter := c.Versions + if getter == nil { + getter = civitai.NewWithSource(c.BaseURL, c.Tokens) + } + v, _, err := getter.GetModelVersion(ctx, strconv.Itoa(id)) + if err != nil { + return nil, err + } + if v == nil || v.Model == nil || v.Model.Type == "" { + // Without a type the resource cannot be built at all, and guessing one + // would be silently accepted by the server. Fail loudly instead. + return nil, fmt.Errorf("model version %d has no model type in the API response — cannot build a generation resource for it", id) + } + return &ResolvedVersion{ + VersionID: id, + VersionName: v.Name, + ModelName: v.Model.Name, + ModelType: v.Model.Type, + BaseModel: v.BaseModel, + }, nil +} diff --git a/internal/genapi/versions_test.go b/internal/genapi/versions_test.go new file mode 100644 index 00000000..35433fe8 --- /dev/null +++ b/internal/genapi/versions_test.go @@ -0,0 +1,216 @@ +package genapi + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/civitai/cli/pkg/civitai" +) + +const versionBody = `{ + "id": 250712, + "modelId": 4384, + "name": "v8", + "baseModel": "SD 1.5", + "model": {"name": "DreamShaper", "type": "LORA", "nsfw": false}, + "files": [] +}` + +func versionClient(t *testing.T, h http.Handler) *Client { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + return New(srv.URL, "test-key") +} + +// TestResolveModelVersion_Found: the resolver returns the model TYPE (which +// Graph.Resources entries require and which is not derivable from the id) plus +// a display name, so a confirmation prompt shows a name rather than an integer. +func TestResolveModelVersion_Found(t *testing.T) { + var path string + c := versionClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path = r.URL.Path + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, versionBody) + })) + + v, err := c.ResolveModelVersion(context.Background(), 250712) + if err != nil { + t.Fatalf("ResolveModelVersion: %v", err) + } + if path != "/api/v1/model-versions/250712" { + t.Errorf("path = %q, want the existing public model-versions route", path) + } + if v.ModelType != "LORA" { + t.Errorf("ModelType = %q, want LORA", v.ModelType) + } + if v.ModelName != "DreamShaper" || v.VersionName != "v8" || v.BaseModel != "SD 1.5" { + t.Errorf("resolved = %+v", v) + } + if got := v.DisplayName(); got != "DreamShaper — v8" { + t.Errorf("DisplayName = %q", got) + } + + // The resource it builds must carry model:{type} — a bare id, and {id} + // alone, are both rejected by the server with a 400. + r := v.Resource(Ptr(0.8)) + if r.Model == nil || r.Model.Type != "LORA" { + t.Fatalf("Resource() dropped the model type: %+v", r) + } + m := marshalToMap(t, r) + inner, ok := m["model"].(map[string]any) + if !ok || inner["type"] != "LORA" { + t.Fatalf("marshalled resource has no model.type: %v", m) + } + if m["id"] != float64(250712) { + t.Errorf("resource id = %v, want 250712", m["id"]) + } + if m["strength"] != 0.8 { + t.Errorf("resource strength = %v, want 0.8", m["strength"]) + } + + // An unset strength must be ABSENT, not 0 — the same zero-value rule the + // graph fields follow. + if _, ok := marshalToMap(t, v.Resource(nil))["strength"]; ok { + t.Error("unset strength is present on the wire") + } +} + +// TestResolveModelVersion_NotFound is the whole point of resolving at all: it +// converts a nonexistent id from a silent substituted charge (HTTP 200, the +// ecosystem default billed instead) into a hard local 404. +func TestResolveModelVersion_NotFound(t *testing.T) { + c := versionClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"error":"Model version not found"}`) + })) + v, err := c.ResolveModelVersion(context.Background(), 999999999) + if err == nil { + t.Fatalf("a nonexistent version resolved cleanly: %+v", v) + } + if !errors.Is(err, civitai.ErrNotFound) { + t.Errorf("errors.Is(err, ErrNotFound) = false; err = %v", err) + } + if v != nil { + t.Errorf("returned a version alongside the error: %+v", v) + } +} + +// TestResolveModelVersion_Malformed: a body with no model type cannot build a +// resource, and guessing one would be SILENTLY ACCEPTED by the server (a LoRA +// sent as {type:"Checkpoint"} returns 200), so it must fail loudly. +func TestResolveModelVersion_Malformed(t *testing.T) { + cases := map[string]string{ + "no model object": `{"id":1,"name":"v1"}`, + "empty type": `{"id":1,"name":"v1","model":{"name":"x","type":""}}`, + "model is null": `{"id":1,"name":"v1","model":null}`, + "not json": `oops`, + "wrong type": `{"id":1,"model":{"type":123}}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + c := versionClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, body) + })) + v, err := c.ResolveModelVersion(context.Background(), 1) + if err == nil { + t.Fatalf("malformed body %q resolved to %+v", body, v) + } + if v != nil { + t.Errorf("returned a version alongside the error: %+v", v) + } + }) + } +} + +// TestResolveModelVersion_RejectsNonPositiveID refuses locally rather than +// building a /model-versions/0 request. +func TestResolveModelVersion_RejectsNonPositiveID(t *testing.T) { + c := versionClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("a request was sent for a non-positive id: %s", r.URL.Path) + })) + for _, id := range []int{0, -1} { + _, err := c.ResolveModelVersion(context.Background(), id) + if !errors.Is(err, civitai.ErrBadRequest) { + t.Errorf("id %d: err = %v, want ErrBadRequest", id, err) + } + } +} + +// TestResolveModelVersion_UsesTheInjectedGetter pins the seam: a caller (or a +// test) can substitute the version lookup without a live server. +func TestResolveModelVersion_UsesTheInjectedGetter(t *testing.T) { + c := &Client{BaseURL: "http://never.invalid", Tokens: civitai.StaticToken("k"), Versions: fakeGetter{}} + v, err := c.ResolveModelVersion(context.Background(), 7) + if err != nil { + t.Fatalf("ResolveModelVersion: %v", err) + } + if v.ModelType != "Checkpoint" || v.DisplayName() != "Fake — vX" { + t.Errorf("resolved = %+v", v) + } +} + +type fakeGetter struct{} + +func (fakeGetter) GetModelVersion(_ context.Context, id string) (*civitai.ModelVersionDetail, []byte, error) { + if id != "7" { + return nil, nil, errors.New("unexpected id " + id) + } + return &civitai.ModelVersionDetail{ + ID: 7, Name: "vX", + Model: &civitai.ModelVersionModel{Name: "Fake", Type: "Checkpoint"}, + }, nil, nil +} + +// TestDisplayName_Fallbacks: never render an empty label. +func TestDisplayName_Fallbacks(t *testing.T) { + cases := []struct { + v ResolvedVersion + want string + }{ + {ResolvedVersion{VersionID: 5}, "5"}, + {ResolvedVersion{VersionID: 5, ModelName: "M"}, "M"}, + {ResolvedVersion{VersionID: 5, VersionName: "v1"}, "v1"}, + {ResolvedVersion{VersionID: 5, ModelName: "M", VersionName: "v1"}, "M — v1"}, + } + for _, tc := range cases { + if got := tc.v.DisplayName(); got != tc.want { + t.Errorf("DisplayName(%+v) = %q, want %q", tc.v, got, tc.want) + } + } +} + +// TestServerMessage covers the three body shapes the CLI sees from this +// surface: a tRPC error envelope, a plain REST error, and raw bytes. +func TestServerMessage(t *testing.T) { + cases := []struct{ raw, want string }{ + {`{"error":{"json":{"message":"Insufficient funds"}}}`, "Insufficient funds"}, + {`{"message":"nope"}`, "nope"}, + {`{"error":"Model version not found"}`, "Model version not found"}, + {` plain text `, "plain text"}, + } + for _, tc := range cases { + if got := serverMessage([]byte(tc.raw)); got != tc.want { + t.Errorf("serverMessage(%q) = %q, want %q", tc.raw, got, tc.want) + } + } +} + +// TestGenerateError_KeepsTheServerMessage: the message text is what tells a +// user WHICH 403 they hit, so it must survive classification unaltered. +func TestGenerateError_KeepsTheServerMessage(t *testing.T) { + err := generateError("generateFromGraph", http.StatusForbidden, + []byte(`{"error":{"json":{"message":"Insufficient funds"}}}`)) + if !strings.Contains(err.Error(), "Insufficient funds") { + t.Errorf("error dropped the server message: %v", err) + } + if !errors.Is(err, civitai.ErrUnauthorized) { + t.Errorf("403 lost its classification: %v", err) + } +} diff --git a/internal/genapi/workflows.go b/internal/genapi/workflows.go new file mode 100644 index 00000000..0e11252a --- /dev/null +++ b/internal/genapi/workflows.go @@ -0,0 +1,217 @@ +package genapi + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" +) + +// The two orchestrator workflow-collection procedures. +// +// queryGeneratedImages GET ?input={"json":{take,cursor,tags}} READ, spends nothing +// cancelWorkflow POST {"json":{"workflowId":"…"}} MUTATION +// +// 🔴 cancelWorkflow is a MUTATION and must never be pointed at a live server +// from a test. It does not refund anything — see CancelWorkflow. +const ( + // QueryWorkflowsPath is the paged list of the caller's own workflows. + QueryWorkflowsPath = "/api/trpc/orchestrator.queryGeneratedImages" + // CancelWorkflowPath cancels one workflow. It is a mutation. + CancelWorkflowPath = "/api/trpc/orchestrator.cancelWorkflow" +) + +// ListedWorkflow is one entry of the workflow feed. +// +// 🔴 It is the server's NORMALIZED workflow shape, which is NOT the raw +// orchestrator shape `GetWorkflow` returns. `queryGeneratedImages` runs its +// items through `formatGenerationResponse2` (civitai/civitai -> +// src/server/services/orchestrator/orchestration-new.service.ts) while +// `orchestrator.getWorkflow` hands the orchestrator's own workflow straight +// back. The two overlap on id/status/createdAt/cost but differ underneath, so +// this deliberately does not reuse the Workflow struct — a shared struct would +// read zero values for whichever fields the other shape names differently, and +// a fabricated zero is exactly the class of bug this package exists to avoid. +type ListedWorkflow struct { + ID string `json:"id"` + Status string `json:"status"` + // CreatedAt is a Date server-side; superjson serialises it to an ISO string + // inside the `json` payload, so it decodes as a string here. + CreatedAt string `json:"createdAt"` + Cost *WorkflowCost `json:"cost"` + Tags []string `json:"tags,omitempty"` + Steps []ListedStep `json:"steps"` +} + +// ListedStep is one step of a normalized (listed) workflow. +type ListedStep struct { + Type string `json:"$type"` + Name string `json:"name"` + Status string `json:"status"` + // Metadata carries the per-output `hidden` flag, which is NOT a field of the + // output itself in either shape. + Metadata stepMetadata `json:"metadata"` + // Output is the normalized output array. + Output []Blob `json:"output"` + // Images is the server's TEMPORARY legacy alias of Output, emitted during + // the rename rollout and documented as always identical to it. It is read as + // a fallback so a server that has finished the rollout and one that has not + // both count correctly. + Images []Blob `json:"images"` +} + +// blobs returns the step's outputs from whichever array the server populated. +func (s ListedStep) blobs() []Blob { + if len(s.Output) > 0 { + return s.Output + } + return s.Images +} + +// OutputCounts returns the total number of outputs and how many of them are +// DELIVERABLE, using the same predicate `workflows get` and the download path +// use (available && !blockedReason && !hidden). +// +// Reporting both is the point: a listing that showed only the total would +// present a workflow whose outputs were all moderation-blocked as a normal +// four-image result, and one that showed only the deliverable count would hide +// that anything had been produced and paid for at all. +func (w ListedWorkflow) OutputCounts() (total, deliverable int) { + for _, st := range w.Steps { + for i, b := range st.blobs() { + total++ + o := Output{Blob: b, StepName: st.Name, StepStatus: st.Status, Index: i, + Hidden: st.Metadata.hiddenFor(b.ID)} + if Deliverable(o) { + deliverable++ + } + } + } + return total, deliverable +} + +// WorkflowPage is one page of the workflow feed. +type WorkflowPage struct { + Items []ListedWorkflow `json:"items"` + // NextCursor is absent on the last page. It is a POINTER so "no more pages" + // stays distinguishable from "an empty cursor string". + NextCursor *string `json:"nextCursor"` +} + +// ListOptions are the query parameters for QueryWorkflows. +type ListOptions struct { + // Take is the page size. Zero omits the key and lets the server apply its + // own default (20) rather than asking for zero workflows. + Take int + // Cursor is the opaque page cursor from a previous page's NextCursor. + Cursor string + // Tags filters the feed. Empty omits the key: the server's schema declares + // `tags` with a default of [], and sending an explicit null would fail + // validation rather than mean "no filter". + Tags []string +} + +// listInput is the tRPC input object. Every field is omitempty so an unset +// option is ABSENT from the wire and the server's own default applies — the +// same absence rule the generation graph follows, for the same reason. +type listInput struct { + Take int `json:"take,omitempty"` + Cursor string `json:"cursor,omitempty"` + Tags []string `json:"tags,omitempty"` +} + +// QueryWorkflows reads one page of the caller's own workflows. It is a READ and +// spends nothing. +// +// It returns the decoded page AND the raw unwrapped payload, so a `--json` +// surface can pass through server fields this struct does not model. +func (c *Client) QueryWorkflows(ctx context.Context, opts ListOptions) (*WorkflowPage, json.RawMessage, error) { + inputJSON, err := json.Marshal(struct { + JSON listInput `json:"json"` + }{JSON: listInput{ + Take: opts.Take, + Cursor: strings.TrimSpace(opts.Cursor), + Tags: opts.Tags, + }}) + if err != nil { + return nil, nil, err + } + q := url.Values{} + q.Set("input", string(inputJSON)) + reqURL := c.BaseURL + QueryWorkflowsPath + "?" + q.Encode() + + build := func() (*http.Request, error) { + return http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil) + } + status, raw, err := c.authedDo(ctx, build) + if err != nil { + return nil, nil, err + } + if status != http.StatusOK { + return nil, nil, generateError("queryGeneratedImages", status, raw) + } + payload, err := unwrapTRPC("orchestrator.queryGeneratedImages", raw) + if err != nil { + return nil, nil, err + } + var out WorkflowPage + if err := json.Unmarshal(payload, &out); err != nil { + return nil, nil, fmt.Errorf("unexpected orchestrator.queryGeneratedImages payload: %s", string(payload)) + } + return &out, payload, nil +} + +// CancelWorkflow cancels one workflow. 🔴 IT IS A MUTATION, AND IT DOES NOT +// REFUND ANYTHING. +// +// The server-side handler resolves to `updateWorkflow({status:'canceled'})` and +// a mid-run cancel BILLS THE ACCRUED COST orchestrator-side, non-refundably. +// Cancelling is how you stop a job you no longer want the *output* of; it is +// never a way to get Buzz back, and no caller of this may present it as one. +// +// 🔴 It deliberately does NOT go through unwrapTRPC. The server procedure +// returns `undefined` (its service function awaits the orchestrator call and +// returns nothing), so a SUCCESSFUL reply carries no `result.data.json` at all — +// unwrapTRPC would reject the success case as a malformed response. HTTP 200 is +// therefore the success signal, and the raw body is returned for `--json`. +// +// It sends NO externalId, and must not: the orchestrator dedupes generation +// submits on (userId, externalId) and this is not a submit — but note that means +// the client-side retry safety the submit path relies on does not apply here. +// authedDo replays only on a 401, and a replayed cancel is idempotent by nature +// (the workflow is already canceled), so that is safe. +func (c *Client) CancelWorkflow(ctx context.Context, workflowID string) (json.RawMessage, error) { + id := strings.TrimSpace(workflowID) + if id == "" { + return nil, fmt.Errorf("a workflow id is required") + } + body, err := json.Marshal(struct { + JSON struct { + WorkflowID string `json:"workflowId"` + } `json:"json"` + }{JSON: struct { + WorkflowID string `json:"workflowId"` + }{WorkflowID: id}}) + if err != nil { + return nil, err + } + build := func() (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+CancelWorkflowPath, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + return req, nil + } + status, raw, err := c.authedDo(ctx, build) + if err != nil { + return nil, err + } + if status != http.StatusOK { + return nil, generateError("cancelWorkflow", status, raw) + } + return raw, nil +} diff --git a/internal/genapi/workflows_test.go b/internal/genapi/workflows_test.go new file mode 100644 index 00000000..ab8c7337 --- /dev/null +++ b/internal/genapi/workflows_test.go @@ -0,0 +1,380 @@ +package genapi + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + "github.com/civitai/cli/pkg/civitai" +) + +// --- queryGeneratedImages (list) -------------------------------------------- + +// The list envelope is a tRPC QUERY, so the input rides FLAT under "json" in the +// query string — the same shape whatIf uses, and NOT the nested shape the submit +// mutation uses. A wrong nesting here would 200 with the server's defaults +// (measured on whatIf: every nested body prices the default job), so the page +// size and cursor would be silently ignored and page 2 would repeat page 1. +func TestQueryWorkflows_EnvelopeIsFlatQueryInput(t *testing.T) { + var got map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + t.Errorf("queryGeneratedImages must be a GET query, got %s", r.Method) + } + if r.URL.Path != QueryWorkflowsPath { + t.Errorf("path = %s, want %s", r.URL.Path, QueryWorkflowsPath) + } + var env struct { + JSON map[string]any `json:"json"` + } + if err := json.Unmarshal([]byte(r.URL.Query().Get("input")), &env); err != nil { + t.Errorf("input param is not JSON: %v", err) + } + got = env.JSON + writeTRPC(w, map[string]any{"items": []any{}, "nextCursor": nil}) + })) + + if _, _, err := c.QueryWorkflows(context.Background(), ListOptions{Take: 5, Cursor: "cur_1", Tags: []string{"x"}}); err != nil { + t.Fatalf("QueryWorkflows: %v", err) + } + if _, nested := got["input"]; nested { + t.Fatalf("the query input must be FLAT under \"json\", not nested under \"input\": %v", got) + } + if got["take"] != float64(5) { + t.Errorf("take = %v, want 5", got["take"]) + } + if got["cursor"] != "cur_1" { + t.Errorf("cursor = %v, want cur_1", got["cursor"]) + } +} + +// Unset options must be ABSENT so the server applies its own defaults. `take: 0` +// would ask for zero workflows and `tags: null` fails the server's zod schema +// (it declares a default of []), so a Go zero value leaking onto the wire is a +// broken request, not a harmless one. +func TestQueryWorkflows_UnsetOptionsAreAbsent(t *testing.T) { + var got map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var env struct { + JSON map[string]any `json:"json"` + } + _ = json.Unmarshal([]byte(r.URL.Query().Get("input")), &env) + got = env.JSON + writeTRPC(w, map[string]any{"items": []any{}}) + })) + if _, _, err := c.QueryWorkflows(context.Background(), ListOptions{}); err != nil { + t.Fatalf("QueryWorkflows: %v", err) + } + for _, k := range []string{"take", "cursor", "tags"} { + if _, ok := got[k]; ok { + t.Errorf("unset option %q is PRESENT on the wire as %#v — it must be absent", k, got[k]) + } + } +} + +const listPayload = `{ + "items":[ + {"id":"wf_1","status":"succeeded","createdAt":"2026-08-05T12:00:00Z","cost":{"base":8,"total":12}, + "steps":[{"$type":"textToImage","name":"s","status":"succeeded", + "metadata":{"output":{"c":{"hidden":true}}}, + "output":[ + {"id":"a","available":true,"url":"https://blobs.example/a.jpeg"}, + {"id":"b","available":true,"url":"https://blobs.example/b.jpeg","blockedReason":"minor"}, + {"id":"c","available":true,"url":"https://blobs.example/c.jpeg"}, + {"id":"d","available":false,"url":"https://blobs.example/d.jpeg"} + ]}]}, + {"id":"wf_2","status":"processing","createdAt":"2026-08-05T12:05:00Z","steps":[]} + ], + "nextCursor":"cur_2", + "serverOnlyField":"kept"}` + +func TestQueryWorkflows_DecodesPageAndCounts(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"result":{"data":{"json":` + listPayload + `}}}`)) + })) + page, raw, err := c.QueryWorkflows(context.Background(), ListOptions{}) + if err != nil { + t.Fatalf("QueryWorkflows: %v", err) + } + if len(page.Items) != 2 { + t.Fatalf("items = %d, want 2", len(page.Items)) + } + if page.NextCursor == nil || *page.NextCursor != "cur_2" { + t.Errorf("nextCursor = %v, want cur_2", page.NextCursor) + } + // 4 outputs; one blocked, one hidden (via step metadata), one unavailable. + total, deliverable := page.Items[0].OutputCounts() + if total != 4 || deliverable != 1 { + t.Errorf("OutputCounts = %d/%d, want 1/4 deliverable/total", deliverable, total) + } + if page.Items[0].Cost == nil || page.Items[0].Cost.Total != 12 { + t.Errorf("cost = %v, want total 12", page.Items[0].Cost) + } + // The raw payload must survive for --json. + var decoded map[string]any + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatalf("raw payload is not JSON: %v", err) + } + if decoded["serverOnlyField"] != "kept" { + t.Error("a field the CLI does not model was dropped from the raw passthrough") + } +} + +// The legacy `images` alias must be counted when `output` is absent — a server +// mid-rollout emits both, one before the rename emits only `images`, and reading +// only `output` would report every older workflow as having produced nothing. +func TestQueryWorkflows_LegacyImagesAliasIsCounted(t *testing.T) { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"result":{"data":{"json":{"items":[{"id":"wf_old","status":"succeeded", + "steps":[{"name":"s","images":[{"id":"a","available":true},{"id":"b","available":true}]}]}]}}}}`)) + })) + page, _, err := c.QueryWorkflows(context.Background(), ListOptions{}) + if err != nil { + t.Fatalf("QueryWorkflows: %v", err) + } + total, deliverable := page.Items[0].OutputCounts() + if total != 2 || deliverable != 2 { + t.Errorf("legacy `images` outputs = %d/%d, want 2/2", deliverable, total) + } +} + +func TestQueryWorkflows_ErrorStatusIsClassified(t *testing.T) { + srv := trpcErrJSON(t, http.StatusForbidden, "Your API key does not have the required scope", "FORBIDDEN") + _, _, err := New(srv, "tok").QueryWorkflows(context.Background(), ListOptions{}) + if err == nil { + t.Fatal("a 403 must return an error") + } + if !errors.Is(err, civitai.ErrUnauthorized) { + t.Errorf("want civitai.ErrUnauthorized, got %v", err) + } +} + +// --- cancelWorkflow --------------------------------------------------------- + +// 🔴 cancelWorkflow is a MUTATION. Every assertion here runs against httptest; +// nothing in this file may reach a real server. +func TestCancelWorkflow_PostsWorkflowIdEnvelope(t *testing.T) { + var method, path string + var body map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + method, path = r.Method, r.URL.Path + _ = json.NewDecoder(r.Body).Decode(&body) + w.Header().Set("Content-Type", "application/json") + // The real procedure returns undefined, so superjson emits an envelope + // with NO `json` key at all. + _, _ = w.Write([]byte(`{"result":{"data":{}}}`)) + })) + raw, err := c.CancelWorkflow(context.Background(), " wf_1 ") + if err != nil { + t.Fatalf("CancelWorkflow: %v", err) + } + if method != http.MethodPost { + t.Errorf("cancel must be a POST mutation, got %s", method) + } + if path != CancelWorkflowPath { + t.Errorf("path = %s, want %s", path, CancelWorkflowPath) + } + inner, _ := body["json"].(map[string]any) + if inner == nil || inner["workflowId"] != "wf_1" { + t.Fatalf("body = %v, want {\"json\":{\"workflowId\":\"wf_1\"}} with the id trimmed", body) + } + if len(raw) == 0 { + t.Error("the raw reply must be returned for --json") + } +} + +// 🔴 The regression this pins: unwrapTRPC REJECTS an envelope with no +// `result.data.json`, and cancelWorkflow's success reply is exactly that (the +// server procedure returns undefined). Routing cancel through unwrapTRPC would +// turn every successful cancel into "unexpected response". +func TestCancelWorkflow_EmptyPayloadIsSuccessNotAnError(t *testing.T) { + for _, reply := range []string{ + `{"result":{"data":{}}}`, + `{"result":{"data":{"json":null}}}`, + `{}`, + } { + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(reply)) + })) + if _, err := c.CancelWorkflow(context.Background(), "wf_1"); err != nil { + t.Errorf("a 200 with reply %s must be a successful cancel, got %v", reply, err) + } + } + // Negative control: the same code path DOES surface a non-200. + srv := trpcErrJSON(t, http.StatusNotFound, "No workflow with that id", "NOT_FOUND") + if _, err := New(srv, "tok").CancelWorkflow(context.Background(), "wf_gone"); err == nil { + t.Error("a 404 must still be an error — otherwise the success check above proves nothing") + } +} + +func TestCancelWorkflow_NotFoundIsClassified(t *testing.T) { + srv := trpcErrJSON(t, http.StatusNotFound, "No workflow with that id", "NOT_FOUND") + _, err := New(srv, "tok").CancelWorkflow(context.Background(), "wf_gone") + if !errors.Is(err, civitai.ErrNotFound) { + t.Errorf("want civitai.ErrNotFound (exit 4), got %v", err) + } +} + +func TestCancelWorkflow_EmptyIDIsRejectedLocally(t *testing.T) { + calls := 0 + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + writeTRPC(w, map[string]any{}) + })) + if _, err := c.CancelWorkflow(context.Background(), " "); err == nil { + t.Fatal("an empty workflow id must be refused") + } + if calls != 0 { + t.Errorf("a mutation was sent for an empty id (%d calls)", calls) + } + // Positive control: the same seam DOES issue a request for a real id. + if _, err := c.CancelWorkflow(context.Background(), "wf_1"); err != nil { + t.Fatalf("control cancel: %v", err) + } + if calls != 1 { + t.Errorf("control: request count = %d, want 1 — a zero above would otherwise prove nothing", calls) + } +} + +// trpcErrJSON serves the platform's tRPC error envelope at a given status and +// returns the server URL. +func trpcErrJSON(t *testing.T, status int, message, code string) string { + t.Helper() + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + body, _ := json.Marshal(map[string]any{ + "error": map[string]any{"json": map[string]any{"message": message, "code": code}}, + }) + _, _ = w.Write(body) + })) + return c.BaseURL +} + +// --- raw-graph passthrough --------------------------------------------------- + +// A raw graph must reach the wire BYTE-FOR-BYTE (modulo whitespace), including +// keys this package does not model. Round-tripping it through the typed Graph +// would delete them silently, which is the failure `--input` exists to avoid. +func TestGraph_RawPassthroughKeepsUnmodelledKeys(t *testing.T) { + raw := json.RawMessage(`{"workflow":"txt2img","prompt":"a cat","someFutureNode":{"shift":3},"foobar":123}`) + m := marshalToMap(t, Graph{Raw: raw}) + for _, k := range []string{"workflow", "prompt", "someFutureNode", "foobar"} { + if _, ok := m[k]; !ok { + t.Errorf("raw key %q was dropped: %v", k, m) + } + } + // The typed fields must NOT leak in beside the raw payload. + if len(m) != 4 { + t.Errorf("raw graph marshalled to %d keys, want exactly the 4 supplied: %v", len(m), m) + } +} + +// The typed fields are IGNORED when Raw is set — a half-merged graph would be a +// payload neither the caller nor the file author wrote. +func TestGraph_RawWinsOverTypedFields(t *testing.T) { + m := marshalToMap(t, Graph{ + Raw: json.RawMessage(`{"workflow":"txt2img","prompt":"from the file"}`), + Prompt: "from a flag", + Quantity: Ptr(9), + }) + if m["prompt"] != "from the file" { + t.Errorf("prompt = %v, want the raw graph's value", m["prompt"]) + } + if _, ok := m["quantity"]; ok { + t.Errorf("a typed field leaked into a raw graph: %v", m) + } +} + +func TestGraph_RawInvalidJSONFailsMarshal(t *testing.T) { + if _, err := json.Marshal(Graph{Raw: json.RawMessage(`{"workflow":`)}); err == nil { + t.Fatal("a malformed raw graph must fail to marshal rather than corrupt the envelope") + } +} + +// whatIf strips the prompts from a RAW graph too — and leaves everything else +// untouched. Stripping by re-marshalling a typed struct would have deleted the +// unmodelled keys, so this is also a guard on HOW the strip is done. +func TestWhatIf_StripsPromptsFromRawGraphOnly(t *testing.T) { + var got map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var env struct { + JSON map[string]any `json:"json"` + } + _ = json.Unmarshal([]byte(r.URL.Query().Get("input")), &env) + got = env.JSON + writeTRPC(w, map[string]any{"ready": true, "cost": map[string]any{"total": 60}}) + })) + g := Graph{Raw: json.RawMessage(`{"workflow":"txt2img","prompt":"a secret prompt","negativePrompt":"blurry","someFutureNode":{"shift":3}}`)} + if _, _, err := c.WhatIfFromGraph(context.Background(), g); err != nil { + t.Fatalf("WhatIfFromGraph: %v", err) + } + for _, k := range []string{"prompt", "negativePrompt"} { + if _, ok := got[k]; ok { + t.Errorf("%q was shipped on a cost estimate: %v", k, got) + } + } + if _, ok := got["someFutureNode"]; !ok { + t.Errorf("stripping the prompts deleted an unmodelled key: %v", got) + } + // The caller's Graph must be unchanged — the SAME graph is submitted next. + if !strings.Contains(string(g.Raw), `"prompt":"a secret prompt"`) { + t.Errorf("whatIf mutated the caller's graph: %s", g.Raw) + } +} + +// The SUBMIT envelope keeps the raw graph nested under "input", beside the +// CLI-owned externalId — the asymmetry phase 0 pinned, now exercised with a raw +// payload. +func TestGenerate_RawGraphKeepsNestedEnvelope(t *testing.T) { + var body map[string]any + c := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewDecoder(r.Body).Decode(&body) + writeTRPC(w, map[string]any{"id": "wf_1", "status": "queued"}) + })) + raw := json.RawMessage(`{"workflow":"txt2img","prompt":"a cat","someFutureNode":{"shift":3}}`) + if _, _, _, err := c.GenerateFromGraph(context.Background(), Graph{Raw: raw}, SubmitOptions{}); err != nil { + t.Fatalf("GenerateFromGraph: %v", err) + } + inner, _ := body["json"].(map[string]any) + if inner == nil { + t.Fatalf("body has no \"json\" wrapper: %v", body) + } + graph, _ := inner["input"].(map[string]any) + if graph == nil { + t.Fatalf("the raw graph must sit NESTED under \"input\": %v", inner) + } + if _, ok := graph["someFutureNode"]; !ok { + t.Errorf("an unmodelled key was dropped from the submit body: %v", graph) + } + if inner["externalId"] == nil || inner["externalId"] == "" { + t.Error("a raw-graph submit must still carry the minted externalId") + } +} + +// KnownGraphKeys must be derived from the struct, not hand-listed: a hand-list +// is what goes stale and makes the unknown-key warning warn about the wrong +// things. +func TestKnownGraphKeys_TracksTheStruct(t *testing.T) { + keys := KnownGraphKeys() + for _, k := range []string{"workflow", "ecosystem", "prompt", "negativePrompt", "quantity", + "aspectRatio", "model", "resources", "steps", "cfgScale", "sampler", "seed"} { + if !keys[k] { + t.Errorf("KnownGraphKeys is missing %q, which Graph models", k) + } + } + // `Raw` is json:"-" and must never appear as a graph key. + if keys["-"] || keys["Raw"] || keys["raw"] { + t.Errorf("KnownGraphKeys leaked the Raw carrier field: %v", keys) + } + // Negative control: it must not claim to know a key the struct does not have. + if keys["foobar"] { + t.Error("KnownGraphKeys reports an unmodelled key as known") + } +} diff --git a/pkg/civitai/download.go b/pkg/civitai/download.go index 0262cf5d..24060233 100644 --- a/pkg/civitai/download.go +++ b/pkg/civitai/download.go @@ -24,6 +24,26 @@ type Downloader interface { DownloadFile(ctx context.Context, fileURL string) (*http.Response, error) } +// PresignedDownloader streams a file from a URL that is ALREADY AUTHORIZED by +// its own signature, with NO credential attached. +// +// 🔴 It exists because reuse of DownloadFile would have leaked a credential. +// isTrustedDownloadHost (below) attaches the bearer token to civitai.com and to +// ANY *.civitai.com subdomain — which is correct for the model-download route it +// was written for, and wrong for an orchestrator blob: those are served from a +// *.civitai.com host and are presigned, so DownloadFile would send a full-scope +// personal API key (25 scopes, including ModelsDelete and VaultWrite) to a +// request that needs no token at all. Weakening isTrustedDownloadHost was not an +// option — `civitai download` depends on it attaching the token — so the fix is +// a SEAM that never has a credential to attach, not a hole in the predicate. +// +// Everything else is shared with DownloadFile: the same SSRF dial guard, the +// same https-per-redirect-hop policy and 10-hop cap, the same +// ResponseHeaderTimeout. The CALLER owns resp.Body and MUST close it. +type PresignedDownloader interface { + DownloadPresigned(ctx context.Context, fileURL string) (*http.Response, error) +} + // downloadResponseHeaderTimeout bounds how long the download client waits for a // server to send response HEADERS after the connection is accepted. There is // deliberately NO overall client Timeout (a large file legitimately streams for @@ -207,6 +227,19 @@ func (c *Client) DownloadFile(ctx context.Context, fileURL string) (*http.Respon return resp, nil } +// DownloadPresigned implements PresignedDownloader. See the interface doc for +// why this is a separate entry point rather than a flag on DownloadFile. +// +// It passes an EMPTY token to doDownload, so no Authorization header is ever +// built — the check there is `token != "" && isTrustedDownloadHost(...)`, and +// the empty token short-circuits it before the host predicate is even consulted. +// It also does NOT do the 401-refresh replay DownloadFile does: there is no +// credential to refresh, and a 401 from a presigned URL means the signature is +// wrong or expired, which a token would not fix. +func (c *Client) DownloadPresigned(ctx context.Context, fileURL string) (*http.Response, error) { + return c.doDownload(ctx, c.downloadHTTPClient(), fileURL, "") +} + // doDownload builds + issues a single GET. The bearer token is attached ONLY // when non-empty AND the destination is a trusted host+scheme (see // isTrustedDownloadHost): f.DownloadURL is SERVER-SUPPLIED, so a hostile value diff --git a/pkg/civitai/download_presigned_test.go b/pkg/civitai/download_presigned_test.go new file mode 100644 index 00000000..d92a2979 --- /dev/null +++ b/pkg/civitai/download_presigned_test.go @@ -0,0 +1,110 @@ +package civitai + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// TestDownloadPresignedSendsNoAuthorizationHeader is the credential-leak guard, +// WITH its positive control in the same test. +// +// The claim under test is an ABSENCE — "no Authorization header reaches the blob +// host" — and an absence measured by a probe that is wired to nothing looks +// exactly the same as an absence produced by correct code. So case (B) drives +// the SAME recorder, through the SAME server, over the SAME URL, and requires it +// to observe a header. Report the pair, never the zero alone. +// +// The setup is the hazardous one on purpose: baseURL EQUALS the blob host, so +// isTrustedDownloadHost returns true and DownloadFile genuinely does attach the +// token. That is what makes (A) a real result rather than a URL the predicate +// would have rejected anyway. +func TestDownloadPresignedSendsNoAuthorizationHeader(t *testing.T) { + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + seen = append(seen, r.Header.Get("Authorization")) + _, _ = io.WriteString(w, "blob-bytes") + })) + defer srv.Close() + + c := New(srv.URL, "secret-api-key") + c.AllowPrivateDownloadHosts = true // httptest binds plain-http loopback + blobURL := srv.URL + "/blob/1.jpeg" + + // (A) The guard: the presigned path must send NO credential. + resp, err := c.DownloadPresigned(context.Background(), blobURL) + if err != nil { + t.Fatalf("DownloadPresigned: %v", err) + } + _, _ = io.Copy(io.Discard, resp.Body) + _ = resp.Body.Close() + if len(seen) != 1 { + t.Fatalf("expected exactly 1 request, got %d", len(seen)) + } + if seen[0] != "" { + t.Errorf("DownloadPresigned leaked a credential to the blob host: Authorization = %q", seen[0]) + } + + // (B) POSITIVE CONTROL: the same recorder, the same host, the same URL — + // through DownloadFile, which SHOULD authenticate. If this is also empty the + // probe observes nothing and (A) proves nothing. + resp2, err := c.DownloadFile(context.Background(), blobURL) + if err != nil { + t.Fatalf("DownloadFile: %v", err) + } + _, _ = io.Copy(io.Discard, resp2.Body) + _ = resp2.Body.Close() + if len(seen) != 2 { + t.Fatalf("expected exactly 2 requests, got %d", len(seen)) + } + if !strings.HasPrefix(seen[1], "Bearer ") { + t.Fatalf("POSITIVE CONTROL FAILED: DownloadFile sent Authorization = %q, want a Bearer token — "+ + "the recorder cannot observe the header, so the empty value in case (A) means nothing", seen[1]) + } + if !strings.Contains(seen[1], "secret-api-key") { + t.Errorf("positive control: want the configured token in the header, got %q", seen[1]) + } +} + +// TestDownloadPresignedKeepsTheTransportGuards proves the credential-free path +// did not become a second, unguarded downloader: it must still refuse a non-https +// URL when private hosts are not allowed (the guard `civitai download` relies on). +func TestDownloadPresignedKeepsTheTransportGuards(t *testing.T) { + c := New("https://civitai.com", "tok") + // AllowPrivateDownloadHosts stays FALSE — the production configuration. + _, err := c.DownloadPresigned(context.Background(), "http://orchestration.civitai.com/blob/1.jpeg") + if err == nil { + t.Fatal("plain-http blob URL: want a refusal, got nil") + } + if !strings.Contains(err.Error(), "https") { + t.Errorf("refusal should name the https requirement, got %v", err) + } +} + +// TestIsTrustedDownloadHostStillTrustsCivitaiSubdomains pins WHY the seam had to +// exist: the trusted-host predicate does match the orchestrator blob host, so +// reusing DownloadFile really would have attached the token. If this ever goes +// false, the predicate was weakened — which is exactly what +// PresignedDownloader's doc forbids, because `civitai download` depends on it. +func TestIsTrustedDownloadHostStillTrustsCivitaiSubdomains(t *testing.T) { + for _, u := range []string{ + "https://orchestration.civitai.com/blob/abc", + "https://civitai.com/api/download/models/1", + } { + if !isTrustedDownloadHost(u, "https://civitai.com") { + t.Errorf("isTrustedDownloadHost(%q) = false, want true — the token-attaching predicate must not be weakened", u) + } + } + // And it must still reject the look-alikes. + for _, u := range []string{ + "https://evilcivitai.com/blob", + "https://civitai.com.evil.com/blob", + } { + if isTrustedDownloadHost(u, "https://civitai.com") { + t.Errorf("isTrustedDownloadHost(%q) = true, want false", u) + } + } +}