Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -677,11 +677,19 @@ neither one's.
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.
was written for — and orchestrator output blobs are served from a
`*.civitai.com` host (observed: `orchestration-new.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.
🔴 **The specific subdomain is incidental to the argument, and must not be
written as if it were the load-bearing fact.** An earlier revision of this
item named `orchestration.civitai.com`; the host actually observed in a real
upload reply is `orchestration-new.civitai.com`. BOTH match the `*.civitai.com`
wildcard, so the credential-free seam is required either way — which is
exactly why the reasoning is stated over the wildcard rather than over a
hostname a server-side rename can invalidate. Do not "fix" this seam because
the subdomain you see does not match the one written here.
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`,
Expand Down Expand Up @@ -901,9 +909,12 @@ neither one's.
item 17's download does not.** `UploadPresigned` (`pkg/civitai/upload.go`) is
a near-duplicate of `DownloadPresigned` and will attract the same "fold it
back in behind a bool". The upload URL is **server-supplied** and lives on a
`*.civitai.com` host, which `isTrustedDownloadHost` **matches**, so a
token-carrying path would hand a 25-scope personal API key to a request its
own signature already authorizes. The interface has no token parameter and
`*.civitai.com` host (observed: `orchestration-new.civitai.com`), which
`isTrustedDownloadHost` **matches**, so a token-carrying path would hand a
25-scope personal API key to a request its own signature already authorizes.
As in item 17, the WILDCARD is the load-bearing fact and the subdomain is
incidental — the seam is required for any `*.civitai.com` host, so a rename
server-side changes nothing here. The interface has no token parameter and
consults no `TokenSource`, so the safety is structural rather than
conditional. `genapi.UploadImageBlob`'s two hops differ on purpose — hop 1
(presign) is authed, hop 2 (upload) is not — and the test asserts BOTH, since
Expand Down
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ README. For the end-to-end walkthrough, see
| `civitai generate "<prompt>" [--negative-prompt <p>] [--quantity <n>] [--aspect-ratio <r>] [--checkpoint <version-id>] [--lora <version-id>[:strength]] [--image <path-or-url>] [--ecosystem <key>] [--input <file>] [--print-input] [--dry-run] [--json] [--max-cost <buzz>] [--yes] [--no-wait] [--timeout <dur>] [--out-dir <dir>] [--no-download] [--force] [--external-id <key>]` | **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 `<workflow-id>-<n>.<ext>`. `--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) — note that with `--image` it still **uploads** local files first, because the printed graph has to reference real blob URLs for `--input` to be able to submit it; uploading spends nothing; `--input <file>` (or `-` for stdin) sends a raw graph as-is — txt2img only, and mutually exclusive with the content flags. `--image <path-or-url>` (repeatable) attaches a reference image for **image-to-image** — a local png/jpeg is uploaded, an https URL is passed through — and **requires `--ecosystem`**, because without one the server ignores the images, generates from the prompt alone and charges anyway. 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 <n>] [--cursor <c>] [--tag <t>] [--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 <workflow-id> [--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 <workflow-id> [--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 workflows cancel <workflow-id> [--yes] [--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. Asks for confirmation (default **no**); `--yes` skips the prompt and a non-TTY without it refuses. See [Generate](#listing-and-cancelling-workflows). |
| `civitai version` | Print version / commit / build date. |
| `civitai completion [shell]` | Generate a shell-completion script. |

Expand Down Expand Up @@ -1213,7 +1213,8 @@ civitai workflows list # newest first
civitai workflows list --limit 5
civitai workflows list --limit 50 --cursor <next-cursor>
civitai workflows list --json # raw server payload, incl. nextCursor
civitai workflows cancel <workflow-id>
civitai workflows cancel <workflow-id> # asks for confirmation
civitai workflows cancel <workflow-id> -y # skip the prompt (scripts/CI)
```

`list` is **cursor-paged**, not page-numbered: when more results exist it prints
Expand All @@ -1234,6 +1235,20 @@ the per-output reason.
> 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.)

`cancel` **asks for confirmation**, matching `civitai generate` and
`civitai app submit`. It is the one irreversible action here, and it destroys a
job you have already paid for, so it is gated the same way every other
destructive path in this feature is:

- `--yes` / `-y` proceeds without prompting;
- an interactive terminal prints what is lost and prompts — the default is
**no**, so a bare Enter aborts;
- a **non-interactive** shell without `--yes` **refuses** rather than cancelling
silently. Scripts must pass `--yes` explicitly.

Nothing is cancelled when the confirmation is refused — the gate runs before the
request goes out.

### Exit codes specific to `generate`

`generate` follows the [global exit-code table](#exit-codes), with one
Expand Down
7 changes: 4 additions & 3 deletions internal/cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -689,9 +689,10 @@ func buildGenerateGraph(ctx context.Context, deps generateDeps, o generateOpts)
}
out.graph.Images = imgs
// Label each image with the SOURCE the user typed, not just the blob URL it
// became: after upload every entry is an opaque orchestration.civitai.com
// blob, so a confirmation listing only those cannot be matched back to the
// files on disk — which is the whole point of showing them before a spend.
// became: after upload every entry is an opaque blob URL on a *.civitai.com
// host (observed: orchestration-new.civitai.com), so a confirmation listing
// only those cannot be matched back to the files on disk — which is the whole
// point of showing them before a spend.
// resolveImages preserves order, so imgs[i] is o.images[i].
for i, img := range imgs {
src := ""
Expand Down
217 changes: 217 additions & 0 deletions internal/cmd/generate_confirm_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
package cmd

import (
"context"
"errors"
"strings"
"testing"
)

// 🔴 Nothing in this file may reach a real server: every case drives the stubbed
// genSeams submit counter, which is what makes "0 submits" a MEASURED zero.

// --- the prompt defaults to NO ------------------------------------------------

// 🔴 THE default-deny guard for the spend prompt.
//
// The existing tests feed only "y" and "n", and that pair CANNOT see the
// mutation this test exists to kill — rewriting confirmGenerate's
//
// case "y", "yes": proceed; default: cancel
//
// as
//
// case "n", "no": cancel; default: proceed
//
// keeps both of those cases green while silently turning `[y/N]` into `[Y/n]`.
// The difference is only observable on an answer that is NEITHER accepting NOR
// explicitly refusing: a bare Enter, a typo, a stray "1". Under the mutation
// every one of those SPENDS REAL BUZZ.
//
// "n" and "no" are deliberately absent from the deny table below: they abort
// under the mutation too, so they discriminate nothing.
func TestGenerate_PromptDefaultsToNoAndNeverSubmits(t *testing.T) {
withStdinTTY(t, true)

deny := []struct {
name string
stdin string
}{
{"bare Enter", "\n"},
{"empty stdin (EOF)", ""},
{"whitespace only", " \n"},
{"maybe", "maybe\n"},
{"yy", "yy\n"},
{"Ye (prefix of yes, not yes)", "Ye\n"},
{"1", "1\n"},
{"ok", "ok\n"},
{"sure", "sure\n"},
{"yeah", "yeah\n"},
{"y-with-trailing-junk", "y!\n"},
}
for _, tc := range deny {
t.Run("deny/"+tc.name, func(t *testing.T) {
var s genSeams
c, out, errb := genCmd(tc.stdin)
err := runGenerate(c, s.deps(t), baseOpts())
if err == nil {
t.Fatalf("answer %q: want a cancellation, got nil", tc.stdin)
}
// 🔴 The load-bearing assertion: no money moved. Under the inverted
// switch this is 1.
if s.submitCalls != 0 {
t.Errorf("🔴 answer %q SPENT BUZZ: submit called %d time(s), want 0", tc.stdin, s.submitCalls)
}
// The case must actually have reached the switch. Without this, a
// refusal from some earlier guard would look like a default-deny.
if !strings.Contains(errb.String(), "[y/N]") {
t.Errorf("answer %q: no prompt printed, so this case never reached the switch:\n%s", tc.stdin, errb.String())
}
if strings.Contains(out.String(), "wf_123") {
t.Errorf("answer %q: a workflow id was printed for a cancelled run: %q", tc.stdin, out.String())
}
})
}

// 🔴 POSITIVE CONTROLS, in the same test. Every zero above is only meaningful
// because these drive the SAME counter, through the SAME deps constructor, to
// 1 — a submit seam wired to nothing would report 0 for the whole table.
for _, tc := range []struct {
name string
stdin string
}{
{"y", "y\n"},
{"yes", "yes\n"},
{"Y uppercase", "Y\n"},
{"YES uppercase", "YES\n"},
{"y with surrounding spaces", " y \n"},
} {
t.Run("accept/"+tc.name, func(t *testing.T) {
var s genSeams
c, out, _ := genCmd(tc.stdin)
if err := runGenerate(c, s.deps(t), baseOpts()); err != nil {
t.Fatalf("answer %q: want the generation to proceed, got %v", tc.stdin, err)
}
if s.submitCalls != 1 {
t.Fatalf("POSITIVE CONTROL FAILED: answer %q submitted %d times, want 1 — the zeros in the deny table prove nothing",
tc.stdin, s.submitCalls)
}
if !strings.Contains(out.String(), "wf_123") {
t.Errorf("answer %q: accepted run printed no workflow id: %q", tc.stdin, out.String())
}
})
}
}

// 🔴 The non-TTY refusal must hold REGARDLESS of what is on stdin.
//
// TestGenerate_NonTTYWithoutYesRefusesAndNeverSubmits pipes EMPTY stdin, so if
// the `!stdinIsTTY()` refusal were removed the run would fall through to the
// prompt, read EOF, and cancel anyway — the submit counter stays at 0 and only
// the message assertions notice. The counter never discriminates, so the guard
// is pinned by its wording rather than by its behaviour.
//
// Piping "y" is the real shape of the hazard: a CI job that answers the prompt
// on stdin instead of passing --yes. With the non-TTY branch gone, that SPENDS
// REAL BUZZ with no --yes anywhere in the command line. The claim is "a terminal
// is attached", not "somebody typed something".
func TestGenerate_NonTTYIgnoresPipedYes(t *testing.T) {
withStdinTTY(t, false)

for _, piped := range []string{"y\n", "yes\n", "Y\n", "YES\n"} {
var s genSeams
c, _, errb := genCmd(piped)
err := runGenerate(c, s.deps(t), baseOpts())
if err == nil {
t.Errorf("non-TTY with %q piped to stdin: want a refusal, got nil", piped)
}
if s.submitCalls != 0 {
t.Errorf("🔴 non-TTY with %q piped to stdin SPENT BUZZ (%d submit(s)) — piped input is not a confirmation",
piped, s.submitCalls)
}
if strings.Contains(errb.String(), "[y/N]") {
t.Errorf("non-TTY with %q piped: a prompt was printed to a shell that cannot answer it", piped)
}
}

// POSITIVE CONTROL: the same seam, same non-TTY, with --yes — submits.
var ok genSeams
o := baseOpts()
o.assumeYes = true
c, _, _ := genCmd("")
if err := runGenerate(c, ok.deps(t), o); err != nil {
t.Fatalf("positive control (--yes on a non-TTY): %v", err)
}
if ok.submitCalls != 1 {
t.Fatalf("POSITIVE CONTROL FAILED: submit called %d times, want 1", ok.submitCalls)
}
}

// --- the cost-vs-balance boundary --------------------------------------------

// 🔴 The `cost > balance` comparison at its BOUNDARY.
//
// Surviving mutation: `>` → `>=`. Every existing case sits far from the edge
// (balance 3 vs cost 12, or balance 1,000,000), so none of them can tell the two
// operators apart. Spending your last Buzz on a job you can exactly afford is a
// legitimate, and not especially rare, thing to do — under `>=` it is refused
// with "exceeds your balance of 12", which is simply false.
//
// The three points are measured together so the claim carries its own scope:
// just below the balance, exactly at it, and just above it.
func TestGenerate_CostEqualToBalanceIsAffordable(t *testing.T) {
withStdinTTY(t, false)

const cost = 12 // genSeams' default quote (okQuote(12))

cases := []struct {
name string
balance int64
wantSubmits int
wantErr bool
}{
// Below the cost: refused. This is the POSITIVE CONTROL for the guard —
// it proves the balance check is wired up and CAN fire, so the zeros in
// the "want a refusal" direction are real.
{"balance one below the cost", cost - 1, 0, true},
// 🔴 AT the boundary: affordable. This is the case `>=` gets wrong.
{"balance exactly equal to the cost", cost, 1, false},
// Above: affordable (guards against `<` style inversions too).
{"balance one above the cost", cost + 1, 1, false},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var s genSeams
bal := tc.balance
s.balance = func(context.Context) (int64, error) { return bal, nil }
o := baseOpts()
o.assumeYes = true
c, _, _ := genCmd("")
err := runGenerate(c, s.deps(t), o)

if tc.wantErr {
if err == nil {
t.Fatalf("balance %d vs cost %d: want a refusal, got nil", tc.balance, cost)
}
// Pinned by errors.Is, never by message text.
if !errors.Is(err, ErrInsufficientBuzz) {
t.Errorf("balance %d: want ErrInsufficientBuzz, got %v", tc.balance, err)
}
} else if err != nil {
t.Fatalf("balance %d vs cost %d: this job IS affordable and must not be refused: %v",
tc.balance, cost, err)
}

if s.submitCalls != tc.wantSubmits {
t.Errorf("balance %d vs cost %d: submit called %d time(s), want %d",
tc.balance, cost, s.submitCalls, tc.wantSubmits)
}
// The balance seam must have been consulted, or the comparison under
// test never ran and the whole case is vacuous.
if s.balanceCalls != 1 {
t.Errorf("balance seam called %d time(s), want 1 — the comparison under test did not run", s.balanceCalls)
}
})
}
}
16 changes: 16 additions & 0 deletions internal/cmd/generate_image.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,22 @@ func decodeImageHeader(r io.Reader, what string) (int, int, string, error) {
"%s could not be read as an image (%w) — the file may be truncated or corrupt; supported formats: %s",
what, err, supportedImageFormatList())
}
// 🔴 DEFENSIVE ONLY — this branch is UNREACHABLE as the package is currently
// built, and no test can kill a mutation inside it. image.DecodeConfig can
// only name a format whose decoder is registered, this file registers exactly
// png and jpeg (the blank imports above), and both are keys of
// supportedImageFormats — so every input either yields one of those two names
// or fails earlier with image.ErrFormat. Neutering this `if` therefore leaves
// the whole suite green, and that is a fact about reachability, not a missing
// test: forcing it reachable would mean registering a third decoder, which is
// exactly what gifBytes() in generate_image_test.go documents as the thing
// that would silently destroy the real unsupported-format test.
//
// It is kept because the invariant it depends on is one line away from being
// broken: adding a blank import WITHOUT adding the map entry makes this the
// live guard that stops an unlabelled format reaching the upload. That
// lockstep is what TestSupportedImageFormats_DecoderRegistrationIsInLockstep
// pins — the reachable half of this rule.
if _, ok := supportedImageFormats[format]; !ok {
return 0, 0, "", fmt.Errorf(
"%s is a %s image, which this CLI cannot attach — supported formats: %s",
Expand Down
Loading
Loading