From 4bf61ca1f2de443861ecdf1b7214c092538de71d Mon Sep 17 00:00:00 2001 From: Google Team Member Date: Fri, 4 Dec 2026 04:13:36 -0800 Subject: [PATCH] feat(cli): validate --processing and --resolution against generated enums and API version - Validate --processing and --resolution values against generated per-modality enums and surface valid schema values in usage error hints. - Scope media fields by modality and API version (document and audio fields are v1beta-only; v1 skips them in mixed calls and hints --api-version v1beta when no input accepts the flag on v1). - Preview a video block on --dry-run for untyped files/ handles when a video-only processing mode is requested. - Add contract tests in media_options_test.go covering validation, case insensitivity, per-modality scoping, v1/v1beta behavior, and dry-run previews. PiperOrigin-RevId: 1036209720 --- internal/cli/custom/analyze.go | 110 ++++- internal/cli/custom/files_upload.go | 74 ++-- internal/cli/custom/hardening_test.go | 52 +-- internal/cli/custom/media.go | 523 +++++++++++++++++++++++- internal/cli/custom/porcelain.go | 3 +- internal/cli/custom/transcribe.go | 19 +- tests/contract/media_options_test.go | 306 ++++++++++++++ tests/contract/porcelain_inputs_test.go | 369 +++++++++++++++++ 8 files changed, 1365 insertions(+), 91 deletions(-) create mode 100644 tests/contract/media_options_test.go diff --git a/internal/cli/custom/analyze.go b/internal/cli/custom/analyze.go index 9f90f249..64833498 100644 --- a/internal/cli/custom/analyze.go +++ b/internal/cli/custom/analyze.go @@ -15,8 +15,10 @@ package custom import ( + "encoding/json" "errors" "fmt" + "slices" "strings" "github.com/google-gemini/gemini-api-cli/internal/flagutil" @@ -35,7 +37,7 @@ const defaultAnalyzeQuestion = "Describe this file in detail." func attachAnalyze(cmd *cobra.Command) { cmd.Use = "analyze [question]" cmd.Short = "Ask questions about images, audio, video, documents, text files, or YouTube URLs (" + defaultTextModel + ")" - cmd.Long = "Ask a question about one or more images, audio files, videos, PDFs, CSV or text\nfiles, or YouTube URLs.\n\nPass each media source separately with --input. files/ references use the\nFiles API, and YouTube URLs are passed by URI. The optional question applies to\nall inputs; its default is \"" + defaultAnalyzeQuestion + "\"\nBy default, stdout prints only the model's answer. The request is not stored\nserver-side.\n\n" + inlineLimitNote + cmd.Long = "Ask a question about one or more images, audio files, videos, PDFs, CSV or text\nfiles, or YouTube URLs. Pass each source with --input: files/ uses the Files\nAPI and YouTube URLs go by URI. The question applies to every input; its default\nis \"" + defaultAnalyzeQuestion + "\" By default, stdout prints only the answer;\nnothing is stored. Video with a non-static --processing streams internally.\n\n" + inlineLimitNote cmd.Example = " gemini-api analyze -i report.pdf \"Summarize the key findings\"\n" + " gemini-api analyze -i photo.jpg\n" + " gemini-api analyze -i files/abc123 \"List every speaker with timestamps\"\n" + @@ -47,6 +49,9 @@ func attachAnalyze(cmd *cobra.Command) { cmd.Args = cobra.ArbitraryArgs cmd.Flags().StringArrayP("input", "i", nil, "Local path, files/, or YouTube URL to analyze (repeatable)") cmd.Flags().String("mime-type", "", "Override the detected MIME type (one input only)") + cmd.Flags().Bool("upload", false, uploadFlagHelp) + cmd.Flags().String("processing", "", processingFlagHelp) + cmd.Flags().String("resolution", "", resolutionFlagHelp) cmd.Flags().String("system", "", "System instruction to steer the analysis") cmd.Flags().Bool("stdin", false, "Read text to analyze from stdin to EOF (sent after the --input media, before the question)") modelFlag(cmd, defaultTextModel, "text") @@ -117,6 +122,10 @@ func runAnalyze(cmd *cobra.Command, args []string) error { if sys, _ := flagutil.GetStringFlag(cmd, "system"); strings.TrimSpace(sys) != "" { body.SystemInstruction = stringPtr(strings.TrimSpace(sys)) } + stream := streamsAnalysis(sources) + if stream { + body.Stream = boolPtr(true) + } req := operations.CreateInteractionRequest{ Body: operations.CreateCreateInteractionRequestBodyCreateModelInteraction(body), } @@ -138,7 +147,13 @@ func runAnalyze(cmd *cobra.Command, args []string) error { if err != nil { return output.Error(cmd, err) } - text, err := interactionText(res.Interaction) + interaction := res.Interaction + if stream { + if interaction, err = collectStreamedInteraction(cmd, res); err != nil { + return err + } + } + text, err := interactionText(interaction) if err != nil { return err } @@ -149,8 +164,97 @@ func runAnalyze(cmd *cobra.Command, args []string) error { if len(mimeTypes) > 0 { envelope["mime_types"] = mimeTypes } - if u := usageEnvelope(res.Interaction.Usage); u != nil { + if u := usageEnvelope(interaction.Usage); u != nil { envelope["usage"] = u } return emitResult(cmd, text, envelope) } + +// streamsAnalysis reports whether the request is sent as an SSE stream: a +// video input processed in a mode other than static runs long enough that a +// single unary response risks the connection and auth window. The stream is +// consumed internally; the command still prints one answer. +func streamsAnalysis(sources []*mediaSource) bool { + for _, src := range sources { + if src.class() == contentVideo && src.opts.agentic() { + return true + } + } + return false +} + +// collectStreamedInteraction drains the event stream of a streaming create +// and returns the interaction its completed event carries, rebuilt as the +// full resource shape the text and usage readers expect. When the completed +// event omits model-output text steps, streamed text deltas are assembled +// into a model output step so interactionText still succeeds. +func collectStreamedInteraction(cmd *cobra.Command, res *operations.CreateInteractionResponse) (*interactions.Interaction, error) { + es := res.InteractionSSEStreamEvent + if es == nil { + return nil, runtimeError("the API did not return an event stream") + } + defer es.Close() + var completed *interactions.InteractionCompletedEvent + var deltaText strings.Builder + for es.Next() { + ev := es.Value() + if ev == nil { + continue + } + if e := ev.GetDataError(); e != nil { + if raw, err := json.Marshal(e); err == nil { + return nil, output.Error(cmd, &output.StreamEventError{Body: string(raw)}) + } + msg := "the API reported an error while streaming" + if e.Error != nil && e.Error.Message != nil && strings.TrimSpace(*e.Error.Message) != "" { + msg = *e.Error.Message + } + return nil, runtimeError(msg) + } + if sd := ev.GetDataStepDelta(); sd != nil { + if td := sd.GetDeltaText(); td != nil { + deltaText.WriteString(td.Text) + } + } + if c := ev.GetDataInteractionCompleted(); c != nil { + completed = c + } + } + if err := es.Err(); err != nil { + return nil, output.Error(cmd, err) + } + if completed == nil { + return nil, runtimeError("the stream ended without an interaction.completed event") + } + it := completed.Interaction + steps := it.Steps + if !stepsHaveText(steps) && deltaText.Len() > 0 { + steps = append(slices.Clone(steps), interactions.CreateStepModelOutput(interactions.ModelOutputStep{ + Content: []interactions.Content{textContentBlock(deltaText.String())}, + })) + } + full := &interactions.Interaction{ + ID: stringPtr(it.ID), + Status: interactions.InteractionStatus(it.Status), + Steps: steps, + Usage: it.Usage, + } + if it.Model != nil { + full.Model = modelPtr(*it.Model) + } + return full, nil +} + +func stepsHaveText(steps []interactions.Step) bool { + for _, step := range steps { + if step.ModelOutputStep == nil { + continue + } + for _, block := range step.ModelOutputStep.Content { + if block.TextContent != nil && strings.TrimSpace(block.TextContent.Text) != "" { + return true + } + } + } + return false +} diff --git a/internal/cli/custom/files_upload.go b/internal/cli/custom/files_upload.go index 1adffd81..13dd71d1 100644 --- a/internal/cli/custom/files_upload.go +++ b/internal/cli/custom/files_upload.go @@ -108,10 +108,40 @@ func runFilesUpload(cmd *cobra.Command, args []string) error { displayName = filepath.Base(path) } - t, err := newRawTransport(cmd) + file, err := uploadSource(cmd, source, path, info.Size(), mimeType, displayName) if err != nil { return err } + if isDryRun(cmd) { + if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait { + progress(cmd, "[DRY-RUN] --wait polling is response-dependent and was not simulated.") + } + return nil + } + name := *file.Name + + if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait { + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + waited, err := waitActive(cmd, name, timeout) + if err != nil { + return err + } + if waited != nil { + file = waited + } + } + return emitResult(cmd, name, fileEnvelope(file)) +} + +// uploadSource opens a resumable session for an already-open local file, +// streams its bytes, and returns the named File the finalize response carries. +// Under --dry-run the start request and every chunk are previewed and the +// returned File is nil. +func uploadSource(cmd *cobra.Command, source *os.File, path string, size int64, mimeType, displayName string) (*genai.File, error) { + t, err := newRawTransport(cmd) + if err != nil { + return nil, err + } // Step 1: start the resumable session. meta := map[string]any{"file": map[string]any{"display_name": displayName}} @@ -119,46 +149,32 @@ func runFilesUpload(cmd *cobra.Command, args []string) error { startURL := t.apiURL("upload/" + t.apiVersion + "/files") startReq, err := t.newRequest(cmd.Context(), http.MethodPost, startURL, bytes.NewReader(metaBytes)) if err != nil { - return err + return nil, err } startReq.Header.Set("Content-Type", "application/json") - setUploadStartHeaders(startReq, info.Size(), mimeType) + setUploadStartHeaders(startReq, size, mimeType) if !isDryRun(cmd) { - progress(cmd, "Starting upload of %s (%d bytes, %s)...", path, info.Size(), mimeType) + progress(cmd, "Starting upload of %s (%d bytes, %s)...", path, size, mimeType) } // Step 2: send the start request, then stream the bytes in chunks; only // the last chunk finalizes. - finalBody, err := t.resumableUpload(cmd, startReq, source, path, info.Size()) + finalBody, err := t.resumableUpload(cmd, startReq, source, path, size) if err != nil { - return err + return nil, err } if isDryRun(cmd) { - if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait { - progress(cmd, "[DRY-RUN] --wait polling is response-dependent and was not simulated.") - } - return nil + return nil, nil } file, err := decodeUploadedFile(finalBody) if err != nil { - return runtimeError(err.Error()) + return nil, runtimeError(err.Error()) } if file.Name == nil || *file.Name == "" { - return runtimeError("upload finished but the response had no file name") - } - name := *file.Name - progress(cmd, "Uploaded %s as %s.", path, name) - - if wait, _ := flagutil.GetBoolFlag(cmd, "wait"); wait { - waited, err := t.waitActive(cmd, name) - if err != nil { - return err - } - if waited != nil { - file = *waited - } + return nil, runtimeError("upload finished but the response had no file name") } - return emitResult(cmd, name, fileEnvelope(&file)) + progress(cmd, "Uploaded %s as %s.", path, *file.Name) + return &file, nil } // setUploadStartHeaders declares the resumable session a start request opens. @@ -345,10 +361,9 @@ func (t *rawTransport) streamUpload(ctx context.Context, uploadURL string, sourc } } -// waitActive polls files.get until the file is ACTIVE, fails, or the -// --wait-timeout deadline passes; every poll and sleep is bounded by that -// deadline. -func (t *rawTransport) waitActive(cmd *cobra.Command, name string) (*genai.File, error) { +// waitActive polls files.get until the file is ACTIVE, fails, or timeout +// passes; every poll and sleep is bounded by that deadline. +func waitActive(cmd *cobra.Command, name string, timeout time.Duration) (*genai.File, error) { s, err := client.NewClient(cmd) if err != nil { return nil, err @@ -357,7 +372,6 @@ func (t *rawTransport) waitActive(cmd *cobra.Command, name string) (*genai.File, if err != nil { return nil, err } - timeout, _ := cmd.Flags().GetDuration("wait-timeout") waitTimedOut := func() error { return runtimeError(fmt.Sprintf("%s did not become ACTIVE within %s", name, timeout), fmt.Sprintf("Check its state later: gemini-api files get %s", name)) diff --git a/internal/cli/custom/hardening_test.go b/internal/cli/custom/hardening_test.go index a3164bc5..3f83e7d9 100644 --- a/internal/cli/custom/hardening_test.go +++ b/internal/cli/custom/hardening_test.go @@ -83,12 +83,15 @@ func TestCheckLocalFileInlineBoundary(t *testing.T) { for name, tc := range map[string]struct { file string size int64 + upload bool wantOK bool }{ - "media at the cap": {"a.mp4", largest, true}, - "media over the cap": {"b.mp4", largest + 3, false}, - "text at the cap": {"a.txt", maxInlineBytes, true}, - "text over the cap": {"b.txt", maxInlineBytes + 1, false}, + "media at the cap": {"a.mp4", largest, false, true}, + "media over the cap": {"b.mp4", largest + 3, false, false}, + "media over the cap with upload": {"c.mp4", largest + 3, true, true}, + "text at the cap": {"a.txt", maxInlineBytes, false, true}, + "text over the cap": {"b.txt", maxInlineBytes + 1, false, false}, + "text over the cap with upload": {"c.txt", maxInlineBytes + 1, true, false}, } { path := filepath.Join(t.TempDir(), tc.file) f, err := os.Create(path) @@ -100,10 +103,13 @@ func TestCheckLocalFileInlineBoundary(t *testing.T) { t.Fatal(err) } f.Close() - _, _, err = checkLocalFile(path, "", "--input[1]", analyzePolicy) + cost, _, err := checkLocalFile(path, "", "--input[1]", analyzePolicy, tc.upload) if (err == nil) != tc.wantOK { t.Errorf("%s: checkLocalFile error = %v, want ok=%v", name, err, tc.wantOK) } + if tc.upload && tc.wantOK && cost != 0 { + t.Errorf("%s: upload cost = %d, want 0", name, cost) + } } } @@ -124,6 +130,7 @@ func TestCanonicalRemoteMIME(t *testing.T) { func TestInteractionOutcome(t *testing.T) { rejected := []interactions.InteractionStatus{ interactions.InteractionStatusIncomplete, interactions.InteractionStatusBudgetExceeded, + interactions.InteractionStatusRequiresContinuation, interactions.InteractionStatusFailed, interactions.InteractionStatusCancelled, interactions.InteractionStatusRequiresAction, interactions.InteractionStatusInProgress, interactions.InteractionStatusQueued, @@ -255,11 +262,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) { _ = cmd.Flags().Set("wait-timeout", "5s") cmd.SetContext(ctx) - tr, err := newRawTransport(cmd) - if err != nil { - t.Fatalf("newRawTransport: %v", err) - } - _, err = tr.waitActive(cmd, "files/xyz789") + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + _, err := waitActive(cmd, "files/xyz789", timeout) if err == nil { t.Fatal("expected error on caller cancellation") } @@ -291,11 +295,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) { _ = cmd.Flags().Set("wait-timeout", "5s") cmd.SetContext(ctx) - tr, err := newRawTransport(cmd) - if err != nil { - t.Fatalf("newRawTransport: %v", err) - } - _, err = tr.waitActive(cmd, "files/xyz789") + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + _, err := waitActive(cmd, "files/xyz789", timeout) if !errors.Is(err, context.Canceled) { t.Errorf("error = %v, want context.Canceled", err) } @@ -317,11 +318,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) { _ = cmd.Flags().Set("wait-timeout", "0s") cmd.SetContext(t.Context()) - tr, err := newRawTransport(cmd) - if err != nil { - t.Fatalf("newRawTransport: %v", err) - } - _, err = tr.waitActive(cmd, "files/xyz789") + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + _, err := waitActive(cmd, "files/xyz789", timeout) if err == nil || !strings.Contains(err.Error(), "files/xyz789 did not become ACTIVE within 0s") { t.Errorf("error = %v, want wait-timeout message", err) } @@ -340,11 +338,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) { _ = cmd.Flags().Set("wait-timeout", "50ms") cmd.SetContext(t.Context()) - tr, err := newRawTransport(cmd) - if err != nil { - t.Fatalf("newRawTransport: %v", err) - } - _, err = tr.waitActive(cmd, "files/xyz789") + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + _, err := waitActive(cmd, "files/xyz789", timeout) if err == nil || !strings.Contains(err.Error(), "files/xyz789 did not become ACTIVE within 50ms") { t.Errorf("error = %v, want wait-timeout message", err) } @@ -367,11 +362,8 @@ func TestWaitActiveCancellationAndDeadline(t *testing.T) { _ = cmd.Flags().Set("wait-timeout", "5s") cmd.SetContext(t.Context()) - tr, err := newRawTransport(cmd) - if err != nil { - t.Fatalf("newRawTransport: %v", err) - } - file, err := tr.waitActive(cmd, "files/xyz789") + timeout, _ := cmd.Flags().GetDuration("wait-timeout") + file, err := waitActive(cmd, "files/xyz789", timeout) if err != nil { t.Fatalf("waitActive: %v", err) } diff --git a/internal/cli/custom/media.go b/internal/cli/custom/media.go index c699edd7..3bd7a0b1 100644 --- a/internal/cli/custom/media.go +++ b/internal/cli/custom/media.go @@ -30,6 +30,8 @@ import ( "regexp" "slices" "strings" + "sync" + "time" "unicode/utf8" "github.com/google-gemini/gemini-api-cli/internal/client" @@ -67,8 +69,329 @@ func inlineCost(size int64, class contentClass) int64 { } // inlineLimitNote is the help sentence analyze and transcribe share. -var inlineLimitNote = fmt.Sprintf("Local files are sent inline; this CLI keeps each request under %d MB, base64\nincluded (about %d MB of media). Upload larger files with \"gemini-api files upload\"\nand pass the returned files/.", - maxInlineRequestBytes>>20, (maxInlineBytes/4*3)>>20) +var inlineLimitNote = fmt.Sprintf("Local files are sent inline; this CLI keeps each request under %d MB, base64\nincluded. Pass --upload (or run \"gemini-api files upload\") for larger media.", + maxInlineRequestBytes>>20) + +// uploadReadyTimeout bounds how long --upload waits for a fresh upload to +// become ACTIVE before the interaction is sent. +const uploadReadyTimeout = 5 * time.Minute + +// uploadFlagHelp is the --upload description every media command shares. +const uploadFlagHelp = "Send local media through the Files API instead of inline (waits until ready)" + +// uploadRequested reports whether the command carries --upload. +func uploadRequested(cmd *cobra.Command) bool { + if cmd.Flags().Lookup("upload") == nil { + return false + } + upload, _ := flagutil.GetBoolFlag(cmd, "upload") + return upload +} + +// uploadHint names the two ways past the inline cap for one input. +func uploadHint(path string) string { + return fmt.Sprintf("Pass --upload to send it through the Files API, or run \"gemini-api files upload %s --wait\" and pass the returned files/", path) +} + +const ( + processingFlagHelp = "How video, audio, and document inputs are processed (for example static or agentic)" + resolutionFlagHelp = "Media resolution for image, video, and document inputs (for example low or high)" +) + +// mediaOptions are the request-level media parameters --processing and +// --resolution, applied to every input block whose content type carries the +// field for the active API version. Values are checked against the generated +// per-modality enums, so a value the schema gains on regeneration (such as a +// future "auto" processing mode) is accepted without a change here. +type mediaOptions struct { + processing string + resolution string + // apiVersion is the request's API version; document and audio media + // fields exist only on v1beta. + apiVersion string +} + +func (o mediaOptions) empty() bool { return o.processing == "" && o.resolution == "" } + +// agentic reports whether --processing names a mode other than static. +func (o mediaOptions) agentic() bool { + return o.processing != "" && o.processing != "static" +} + +// betaOnlyFields reports whether the request targets an API version that +// carries the document and audio media fields. +func (o mediaOptions) betaOnlyFields() bool { + return !strings.EqualFold(strings.TrimSpace(o.apiVersion), "v1") +} + +func mediaOptionsFromFlags(cmd *cobra.Command) mediaOptions { + o := mediaOptions{apiVersion: resolveAPIVersion(cmd)} + if cmd.Flags().Lookup("processing") != nil { + v, _ := flagutil.GetStringFlag(cmd, "processing") + o.processing = strings.ToLower(strings.TrimSpace(v)) + } + if cmd.Flags().Lookup("resolution") != nil { + v, _ := flagutil.GetStringFlag(cmd, "resolution") + o.resolution = strings.ToLower(strings.TrimSpace(v)) + } + return o +} + +// schemaMediaValues reads the processing and resolution values out of the +// embedded request schema, in the order the schema lists them. They only name +// the valid values in a rejection hint; the generated enums decide what is +// valid. Both come from the same spec, so a value added there (such as +// "auto") shows up in both on regeneration. +var schemaMediaValues = sync.OnceValue(func() (v struct{ processing, resolution []string }) { + var raw bytes.Buffer + if err := usage.EmitBodySchema(&raw, "CreateInteraction"); err != nil { + return v + } + type enumSchema struct { + Enum []string `json:"enum"` + OneOf []enumSchema `json:"oneOf"` + } + var schema struct { + Defs map[string]struct { + enumSchema + Properties map[string]enumSchema `json:"properties"` + } `json:"$defs"` + } + if err := json.Unmarshal(raw.Bytes(), &schema); err != nil { + return v + } + add := func(dst *[]string, values []string) { + for _, value := range values { + if !slices.Contains(*dst, value) { + *dst = append(*dst, value) + } + } + } + for _, def := range []string{"VideoContent", "DocumentContent", "AudioContent"} { + processing := schema.Defs[def].Properties["processing"] + add(&v.processing, processing.Enum) + for _, variant := range processing.OneOf { + add(&v.processing, variant.Enum) + } + } + add(&v.resolution, schema.Defs["MediaResolution"].Enum) + return v +}) + +// validValuesHint names the schema's values for a rejected flag, or is empty +// when the embedded schema lists none. +func validValuesHint(values []string) []string { + if len(values) == 0 { + return nil + } + return []string{"Valid values: " + strings.Join(values, ", ")} +} + +// processingInSchema reports whether the class's generated processing enum +// defines the value, on any API version. +func processingInSchema(class contentClass, value string) bool { + switch class { + case contentVideo: + e := interactions.ProcessingEnum(value) + return e.IsExact() + case contentDocument: + e := interactions.DocumentProcessingEnum(value) + return e.IsExact() + case contentAudio: + e := interactions.AudioProcessingEnum(value) + return e.IsExact() + } + return false +} + +// resolutionInSchema reports whether the class carries a resolution field and +// the generated enum defines the value, on any API version. +func resolutionInSchema(class contentClass, value string) bool { + switch class { + case contentVideo, contentImage, contentDocument: + e := interactions.MediaResolution(value) + return e.IsExact() + } + return false +} + +// betaOnly reports whether the class's media fields exist only on v1beta. +// Video and image fields are on both versions; document fields and audio +// processing are v1beta-only. +func betaOnly(class contentClass) bool { + return class == contentDocument || class == contentAudio +} + +// acceptsProcessing reports whether a block of the class takes the +// --processing value on the request's API version. +func (o mediaOptions) acceptsProcessing(class contentClass) bool { + if o.processing == "" || !processingInSchema(class, o.processing) { + return false + } + return o.betaOnlyFields() || !betaOnly(class) +} + +// acceptsResolution reports whether a block of the class takes the +// --resolution value on the request's API version. +func (o mediaOptions) acceptsResolution(class contentClass) bool { + if o.resolution == "" || !resolutionInSchema(class, o.resolution) { + return false + } + return o.betaOnlyFields() || !betaOnly(class) +} + +// inAnySchema reports whether some media class defines the value. +func inAnySchema(value string, inSchema func(contentClass, string) bool) bool { + for _, class := range []contentClass{contentVideo, contentImage, contentDocument, contentAudio} { + if inSchema(class, value) { + return true + } + } + return false +} + +// previewsAsVideo reports whether the dry-run placeholder for a files handle of +// unknown type should be a video block: the flags are set, a document block +// would not take them on the request's API version, and a video block would. +// That covers a mode only video defines (agentic today) and, on v1, every +// value, since the document fields exist only on v1beta. +func (o mediaOptions) previewsAsVideo() bool { + takes := func(class contentClass) bool { + return (o.processing == "" || o.acceptsProcessing(class)) && + (o.resolution == "" || o.acceptsResolution(class)) + } + return !o.empty() && !takes(contentDocument) && takes(contentVideo) +} + +// validate rejects a --processing or --resolution value no media class +// defines, naming the values the schema does define. +func (o mediaOptions) validate() error { + if o.processing != "" { + if !inAnySchema(o.processing, processingInSchema) { + return usageError(fmt.Sprintf("--processing %q is not a processing mode", o.processing), + validValuesHint(schemaMediaValues().processing)...) + } + } + if o.resolution != "" { + if !inAnySchema(o.resolution, resolutionInSchema) { + return usageError(fmt.Sprintf("--resolution %q is not a media resolution", o.resolution), + validValuesHint(schemaMediaValues().resolution)...) + } + } + return nil +} + +// blockClass is the content class of a ready block. +func blockClass(blk interactions.Content) (contentClass, bool) { + switch { + case blk.VideoContent != nil: + return contentVideo, true + case blk.DocumentContent != nil: + return contentDocument, true + case blk.ImageContent != nil: + return contentImage, true + case blk.AudioContent != nil: + return contentAudio, true + } + return contentText, false +} + +// applyMediaOptions sets processing and resolution on the block when its +// content type takes the value on the request's API version, and leaves every +// other block unchanged. +func applyMediaOptions(blk interactions.Content, o mediaOptions) interactions.Content { + if o.empty() { + return blk + } + class, ok := blockClass(blk) + if !ok { + return blk + } + var resolution *interactions.MediaResolution + if o.acceptsResolution(class) { + r := interactions.MediaResolution(o.resolution) + resolution = &r + } + processing := o.acceptsProcessing(class) + switch class { + case contentVideo: + if processing { + p := interactions.CreateProcessingProcessingEnum(interactions.ProcessingEnum(o.processing)) + blk.VideoContent.Processing = &p + } + if resolution != nil { + blk.VideoContent.Resolution = resolution + } + case contentDocument: + if processing { + p := interactions.CreateDocumentProcessingDocumentProcessingEnum(interactions.DocumentProcessingEnum(o.processing)) + blk.DocumentContent.Processing = &p + } + if resolution != nil { + blk.DocumentContent.Resolution = resolution + } + case contentImage: + if resolution != nil { + blk.ImageContent.Resolution = resolution + } + case contentAudio: + if processing { + p := interactions.CreateAudioProcessingAudioProcessingEnum(interactions.AudioProcessingEnum(o.processing)) + blk.AudioContent.Processing = &p + } + } + return blk +} + +// checkMediaOptionsApply rejects --processing or --resolution when no input +// carries the field, so a flag is never silently dropped. +func checkMediaOptionsApply(sources []*mediaSource, o mediaOptions) error { + classes := make([]contentClass, 0, len(sources)) + for _, src := range sources { + classes = append(classes, src.class()) + } + return checkMediaClassesApply(classes, o) +} + +// checkMediaClassesApply validates the flag values, then requires at least one +// input to take each flag on the request's API version. When an input would +// take the value on v1beta only, the rejection points there. +func checkMediaClassesApply(classes []contentClass, o mediaOptions) error { + if err := o.validate(); err != nil { + return err + } + if o.processing != "" { + if err := requireAccepted(classes, "--processing", o.processing, o.acceptsProcessing, processingInSchema, + "video, audio, and document"); err != nil { + return err + } + } + if o.resolution != "" { + if err := requireAccepted(classes, "--resolution", o.resolution, o.acceptsResolution, resolutionInSchema, + "image, video, and document"); err != nil { + return err + } + } + return nil +} + +func requireAccepted(classes []contentClass, flag, value string, accepts func(contentClass) bool, + inSchema func(contentClass, string) bool, takers string) error { + onBeta := false + for _, class := range classes { + if accepts(class) { + return nil + } + if inSchema(class, value) { + onBeta = true + } + } + if onBeta { + return usageError(fmt.Sprintf("%s %s is not available for these inputs on this API version", flag, value), + "Pass --api-version v1beta") + } + return usageError(fmt.Sprintf("%s applies to %s inputs; none of the inputs accepts %q", flag, takers, value)) +} // mimeByExtension maps common media/document extensions to the MIME types the // Interactions API accepts. It is consulted before the platform's mime database @@ -176,6 +499,10 @@ type mediaPolicy struct { // hint points at the command that takes the rest. accepts string hint string + // checkAccepted applies an extra command-specific check (for example + // rejecting video inputs when a transcribe-only model was explicitly set) + // after the policy's base class check succeeds. + checkAccepted func(mimeType, ref string) error } var ( @@ -189,14 +516,16 @@ var ( // checkClass rejects a MIME type whose content class the command does not take. func (p mediaPolicy) checkClass(mimeType, ref string) error { - if p.classes == nil { - return nil + if p.classes != nil { + class, _ := contentClassOf(mimeType) + if !slices.Contains(p.classes, class) { + return usageError(fmt.Sprintf("%s: only %s inputs are accepted; got %s", ref, p.accepts, mimeType), p.hint) + } } - class, _ := contentClassOf(mimeType) - if slices.Contains(p.classes, class) { - return nil + if p.checkAccepted != nil { + return p.checkAccepted(mimeType, ref) } - return usageError(fmt.Sprintf("%s: only %s inputs are accepted; got %s", ref, p.accepts, mimeType), p.hint) + return nil } // mediaSource is the resolved input of analyze/transcribe: a request content @@ -211,6 +540,24 @@ type mediaSource struct { mimeType string // inlineBytes is what block found the local file to cost once read. inlineBytes int64 + opts mediaOptions +} + +// class is the content class of the block the source produces; a URI-backed +// source may carry no MIME type, so its ready block decides. +func (m *mediaSource) class() contentClass { + switch { + case m.content.VideoContent != nil: + return contentVideo + case m.content.ImageContent != nil: + return contentImage + case m.content.DocumentContent != nil: + return contentDocument + case m.content.AudioContent != nil: + return contentAudio + } + class, _ := contentClassOf(m.mimeType) + return class } // block returns the interaction content block. A local file is read and @@ -271,7 +618,7 @@ func (m *mediaSource) block(cmd *cobra.Command) (interactions.Content, error) { if class == contentText { return textContentBlock(string(data)), nil } - return mediaContentBlock(m.mimeType, string(data), true), nil + return applyMediaOptions(mediaContentBlock(m.mimeType, string(data), true), m.opts), nil } // mediaContentBlock builds an interactions Content block for a media input, @@ -401,7 +748,7 @@ func classifyMediaInput(cmd *cobra.Command, arg, ref string, allowYouTube bool) // checkLocalFile enforces what an inline input must satisfy — a non-empty // regular file within the inline cap whose MIME type the API and the command // accept — and returns its inline cost and MIME type. -func checkLocalFile(path, mimeOverride, ref string, policy mediaPolicy) (int64, string, error) { +func checkLocalFile(path, mimeOverride, ref string, policy mediaPolicy, upload bool) (int64, string, error) { info, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { @@ -433,10 +780,14 @@ func checkLocalFile(path, mimeOverride, ref string, policy mediaPolicy) (int64, // Text travels inline only; an uploaded copy could not be referenced. return 0, "", usageError(fmt.Sprintf("%s: text file is %d bytes; this CLI sends text inline, up to %d MB per request", ref, info.Size(), maxInlineBytes>>20)) } + if upload && class != contentText { + // The bytes go through the Files API, so the inline cap does not apply. + return 0, mimeType, nil + } if cost > maxInlineBytes { return 0, "", usageError( fmt.Sprintf("%s: file is %d bytes (%d as base64); this CLI keeps inline requests under %d MB", ref, info.Size(), cost, maxInlineRequestBytes>>20), - fmt.Sprintf("Run \"gemini-api files upload %s\" and pass the returned files/ instead", path)) + uploadHint(path)) } return cost, mimeType, nil } @@ -468,6 +819,12 @@ func probeLocalFile(path, mimeType, ref string) error { // or sent. Probing each file also catches permissions and mislabelled text. func prevalidateMediaInputs(cmd *cobra.Command, inputs []string, mimeOverride string, policy mediaPolicy) error { var inlineBytes int64 + upload := uploadRequested(cmd) + if len(inputs) == 0 && upload { + return usageError("--upload requires --input") + } + var classes []contentClass + hasUnknownRemote := false for i, raw := range inputs { arg := strings.TrimSpace(raw) ref := inputRef(i+1, arg) @@ -475,21 +832,46 @@ func prevalidateMediaInputs(cmd *cobra.Command, inputs []string, mimeOverride st if err != nil { return err } - if kind != mediaInputLocal { + switch kind { + case mediaInputYouTube: + classes = append(classes, contentVideo) + continue + case mediaInputRemoteFile: + if mt := strings.ToLower(strings.TrimSpace(mimeOverride)); mt != "" { + if err := checkRemoteMIME(mt, ref, policy); err != nil { + return err + } + class, _ := contentClassOf(mt) + classes = append(classes, class) + } else { + hasUnknownRemote = true + } continue } - cost, mimeType, err := checkLocalFile(arg, mimeOverride, ref, policy) + cost, mimeType, err := checkLocalFile(arg, mimeOverride, ref, policy, upload) if err != nil { return err } if err := probeLocalFile(arg, mimeType, ref); err != nil { return err } + class, _ := contentClassOf(mimeType) + classes = append(classes, class) inlineBytes += cost if policy.enforceCumulative && inlineBytes > maxInlineBytes { return usageError( fmt.Sprintf("%s: cumulative inline inputs (base64 included) exceed this CLI's %d MB request budget", ref, maxInlineRequestBytes>>20), - fmt.Sprintf("Run \"gemini-api files upload %s\" and pass the returned files/ instead", arg)) + uploadHint(arg)) + } + } + if opts := mediaOptionsFromFlags(cmd); !opts.empty() { + if err := opts.validate(); err != nil { + return err + } + if !hasUnknownRemote { + if err := checkMediaClassesApply(classes, opts); err != nil { + return err + } } } return nil @@ -517,6 +899,18 @@ func resolveMediaSources(cmd *cobra.Command, inputs []string, policy mediaPolicy } sources = append(sources, src) } + opts := mediaOptionsFromFlags(cmd) + if !opts.empty() { + if err := checkMediaOptionsApply(sources, opts); err != nil { + return nil, nil, err + } + for _, src := range sources { + src.opts = opts + if src.path == "" { + src.content = applyMediaOptions(src.content, opts) + } + } + } return s, sources, nil } @@ -545,14 +939,57 @@ func resolveMediaSource(cmd *cobra.Command, s *sdk.GeminiAPI, arg, mimeOverride name, id, _ := normalizeFileID(fileArg) return resolveRemoteFile(cmd, s, name, id, mimeOverride, ref, policy) } - _, mimeType, err := checkLocalFile(arg, mimeOverride, ref, policy) + upload := uploadRequested(cmd) + _, mimeType, err := checkLocalFile(arg, mimeOverride, ref, policy, upload) if err != nil { return nil, err } abs, _ := filepath.Abs(arg) + if class, _ := contentClassOf(mimeType); upload && class != contentText { + return uploadLocalMedia(cmd, arg, abs, mimeType, ref) + } return &mediaSource{path: arg, ref: ref, label: abs, mimeType: mimeType}, nil } +// uploadLocalMedia sends a local media file through the Files API and returns +// a URI-backed source, waiting for the upload to become ACTIVE. Under +// --dry-run the upload exchange is previewed and a placeholder URI stands in, +// as for an explicit files/ input. +func uploadLocalMedia(cmd *cobra.Command, path, label, mimeType, ref string) (*mediaSource, error) { + source, err := os.Open(path) + if err != nil { + return nil, usageError(fmt.Sprintf("%s: cannot read file: %v", ref, err)) + } + defer source.Close() + info, err := source.Stat() + if err != nil { + return nil, usageError(fmt.Sprintf("%s: cannot access file: %v", ref, err)) + } + file, err := uploadSource(cmd, source, path, info.Size(), mimeType, filepath.Base(path)) + if err != nil { + return nil, err + } + if isDryRun(cmd) { + progress(cmd, "[DRY-RUN] %s: the file's URI comes from the upload response; the previewed block is a placeholder.", ref) + return &mediaSource{content: mediaContentBlock(mimeType, expandedFilesURI(cmd, "files/"), false), label: label, mimeType: mimeType}, nil + } + name := *file.Name + if file.State == nil || *file.State != genai.FileStateActive { + waited, err := waitActive(cmd, name, uploadReadyTimeout) + if err != nil { + return nil, err + } + if waited != nil { + file = waited + } + } + fileURI := expandedFilesURI(cmd, name) + if file.URI != nil && *file.URI != "" { + fileURI = *file.URI + } + return &mediaSource{content: mediaContentBlock(mimeType, fileURI, false), label: label, mimeType: mimeType}, nil +} + // resolveRemoteFile looks a Files API resource up so the request part carries // its URI and MIME type. Under --dry-run the lookup is previewed and a // placeholder URI is used so the main request can still be previewed. @@ -612,6 +1049,14 @@ func resolveRemoteFile(cmd *cobra.Command, s *sdk.GeminiAPI, name, id, mimeOverr if err := checkRemoteMIME(mimeType, ref, policy); err != nil { return nil, err } + if mimeType == "" && isDryRun(cmd) && mediaOptionsFromFlags(cmd).previewsAsVideo() { + // The dry-run lookup reports no MIME type. When the default document + // placeholder would not take the flags but a video would, the real + // file may still be one that does, so the preview shows a video block + // carrying the fields rather than rejecting an unknown type. + video := interactions.CreateContentVideo(interactions.VideoContent{URI: stringPtr(fileURI)}) + return &mediaSource{content: video, label: name}, nil + } return &mediaSource{content: mediaContentBlock(mimeType, fileURI, false), label: name, mimeType: mimeType}, nil } @@ -672,7 +1117,11 @@ func extractFullFilesURI(cmd *cobra.Command, raw string) (string, bool) { // generated intent command on top of its declared flags. type intentInputs struct { media bool // -i/--input and --mime-type: media content blocks - stdin bool // --stdin: a text content block read from stdin + // upload adds --upload, sending local media through the Files API. + upload bool + // mediaOptions adds --processing and --resolution for media inputs. + mediaOptions bool + stdin bool // --stdin: a text content block read from stdin // file is -f/--file, a text content block read from a file; only for // commands without media inputs, where -i already takes text files. file bool @@ -692,7 +1141,7 @@ func attachInteractionInputs(root *cobra.Command) error { promptDesc string inputs intentInputs }{ - {"generate", "prompt", "Prompt to send to the model", intentInputs{media: true, stdin: true, continuationResume: true}}, + {"generate", "prompt", "Prompt to send to the model", intentInputs{media: true, upload: true, mediaOptions: true, stdin: true, continuationResume: true}}, {"image", "prompt", "Description of the image to generate", intentInputs{media: true, stdin: true}}, {"video", "prompt", "Scene description for the video to generate", intentInputs{media: true, stdin: true}}, {"music", "prompt", "Music prompt", intentInputs{stdin: true, file: true}}, @@ -706,6 +1155,18 @@ func attachInteractionInputs(root *cobra.Command) error { return fmt.Errorf("%s: %w", spec.name, err) } } + // The media flags cost help lines; compact the generated description to stay within the 40-line budget. + generateCmd := findChild(root, "generate") + if generateCmd != nil && generateCmd.Long != "" { + const ( + generatedGenerateLong = "Send a prompt to a Gemini model and stream text deltas to stdout. Uses the\nschema's default model (" + defaultTextModel + ") unless --model or --body names one\n(--stream=false returns one complete interaction; --output-format json shows\nthe raw NDJSON event stream). Full request control: \"gemini-api agent run\".\n\nArguments:\n Prompt to send to the model" + compactGenerateLong = "Send a prompt to a Gemini model and stream text deltas to stdout. Uses the\ndefault model (" + defaultTextModel + ") unless --model or --body names one\n(--stream=false for one interaction; --output-format json for NDJSON).\nArguments: Prompt to send to the model" + ) + if !strings.Contains(generateCmd.Long, generatedGenerateLong) { + return fmt.Errorf("generate: generated Long help text changed; update compactGenerateLong in attachInteractionInputs") + } + generateCmd.Long = strings.Replace(generateCmd.Long, generatedGenerateLong, compactGenerateLong, 1) + } agentGroup := findChild(root, "agent") if agentGroup == nil { @@ -715,19 +1176,20 @@ func attachInteractionInputs(root *cobra.Command) error { // agent run keeps piped stdin as the request body: it is the full-control // surface, so it takes media inputs but no --stdin/--file text. hadGeneratedLong := agentRunCmd != nil && agentRunCmd.Long != "" - if err := attachIntentInputs(agentRunCmd, "input", "Prompt or task to send", intentInputs{media: true, continuationResume: true}); err != nil { + if err := attachIntentInputs(agentRunCmd, "input", "Prompt or task to send", intentInputs{media: true, upload: true, mediaOptions: true, continuationResume: true}); err != nil { return fmt.Errorf("agent run: %w", err) } if hadGeneratedLong { const ( generatedAgentRunLong = "Run one interaction with a Gemini model (--model, the default) or a\nmanaged agent (--agent); the two flag sets are mutually exclusive.\nStreams text as it arrives; --stream=false returns one complete\ninteraction. --body takes the exact request JSON (\"model\"/\"agent\" picks the variant).\n\nArguments:\n Prompt or task to send\n\nRequest variants: Agent (--agent), Model (--model; default).\nVariant-specific flags cannot be combined." - compactAgentRunLong = "Run one interaction with a Gemini model (--model, default) or a managed agent (--agent); streams text as it arrives (--stream=false or --background for one interaction unless --stream is passed; --body takes exact request JSON).\nArguments: Prompt or task to send\nRequest variants: Agent (--agent), Model (--model; default). Variant-specific flags cannot be combined." + compactAgentRunLong = "Run one interaction with a Gemini model (--model, default) or a managed agent (--agent); streams text as it arrives (--stream=false or --background for one interaction unless --stream is passed; --body takes exact request JSON).\nArguments: Prompt or task to send · Request variants: Agent (--agent), Model (--model; default). Variant-specific flags cannot be combined." ) if !strings.Contains(agentRunCmd.Long, generatedAgentRunLong) { return fmt.Errorf("agent run: generated Long help text changed; update compactAgentRunLong in attachInteractionInputs") } agentRunCmd.Long = strings.Replace(agentRunCmd.Long, generatedAgentRunLong, compactAgentRunLong, 1) } + agentRunCmd.Example = strings.Replace(agentRunCmd.Example, "\n gemini-api agent run \"Write a detailed research report on solar batteries\" --background", "", 1) return nil } @@ -760,6 +1222,15 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten } flagutil.MarkRequestInput(cmd, "input", "mime-type") satisfiedBy = append(satisfiedBy, "input") + if in.upload && cmd.Flags().Lookup("upload") == nil { + cmd.Flags().Bool("upload", false, uploadFlagHelp) + flagutil.MarkRequestInput(cmd, "upload") + } + if in.mediaOptions && cmd.Flags().Lookup("processing") == nil { + cmd.Flags().String("processing", "", processingFlagHelp) + cmd.Flags().String("resolution", "", resolutionFlagHelp) + flagutil.MarkRequestInput(cmd, "processing", "resolution") + } } fileFlag := "" if in.file { @@ -825,6 +1296,20 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten if len(inputs) == 0 && strings.TrimSpace(mimeOverride) != "" { return usageError("--mime-type requires --input") } + if len(inputs) == 0 { + if in.upload && uploadRequested(c) { + return usageError("--upload requires --input") + } + if in.mediaOptions { + opts := mediaOptionsFromFlags(c) + if opts.processing != "" { + return usageError("--processing requires --input") + } + if opts.resolution != "" { + return usageError("--resolution requires --input") + } + } + } } text := "" diff --git a/internal/cli/custom/porcelain.go b/internal/cli/custom/porcelain.go index 794b3deb..d30907d1 100644 --- a/internal/cli/custom/porcelain.go +++ b/internal/cli/custom/porcelain.go @@ -354,7 +354,8 @@ func interactionOutcome(it *interactions.Interaction) error { detail = ": " + msg } switch it.Status { - case interactions.InteractionStatusIncomplete, interactions.InteractionStatusBudgetExceeded: + case interactions.InteractionStatusIncomplete, interactions.InteractionStatusBudgetExceeded, + interactions.InteractionStatusRequiresContinuation: return runtimeError(fmt.Sprintf("the API stopped before the output was complete (status: %s)%s", it.Status, detail), "Nothing was written; shorten or split the input, or raise the limit via gemini-api agent run") case interactions.InteractionStatusFailed, interactions.InteractionStatusCancelled, diff --git a/internal/cli/custom/transcribe.go b/internal/cli/custom/transcribe.go index 8b2dc436..d722285c 100644 --- a/internal/cli/custom/transcribe.go +++ b/internal/cli/custom/transcribe.go @@ -60,6 +60,7 @@ func attachTranscribe(cmd *cobra.Command) { cmd.Flags().Bool("no-timestamps", false, "Do not include timestamps (ignored for srt)") cmd.Flags().String("out", "", "Output path (default: ./transcript--.)") cmd.Flags().String("mime-type", "", "Override the detected MIME type (one input only)") + cmd.Flags().Bool("upload", false, uploadFlagHelp) modelFlag(cmd, defaultTranscribeModel, "transcription") annotatePromptFlag(cmd, "input", flagutil.PromptFlagSpec{Required: true, Kind: "string-array", Order: 0}) cmd.RunE = runTranscribe @@ -94,24 +95,26 @@ func runTranscribe(cmd *cobra.Command, args []string) error { return err } modelChanged := flagutil.FlagChanged(cmd, "model") - s, sources, err := resolveMediaSources(cmd, inputs, transcribePolicy) - if err != nil { - return err - } + policy := transcribePolicy if modelChanged && isTranscribeModel(model) { - for i, src := range sources { - if class, _ := contentClassOf(src.mimeType); class == contentVideo { + policy.checkAccepted = func(mimeType, ref string) error { + if class, _ := contentClassOf(mimeType); class == contentVideo { hints := []string{fmt.Sprintf("Omit --model or pass --model %s to transcribe video", defaultTextModel)} - if src.mimeType == "video/webm" { + if mimeType == "video/webm" { hints = append(hints, webmAudioHint) } return usageError( - fmt.Sprintf("%s: model %q only accepts audio inputs (detected %s)", inputRef(i+1, inputs[i]), model, src.mimeType), + fmt.Sprintf("%s: model %q only accepts audio inputs (detected %s)", ref, model, mimeType), hints..., ) } + return nil } } + s, sources, err := resolveMediaSources(cmd, inputs, policy) + if err != nil { + return err + } paths, err := transcribeArtifactPaths(cmd, sources, ext) if err != nil { return err diff --git a/tests/contract/media_options_test.go b/tests/contract/media_options_test.go new file mode 100644 index 00000000..2d8b419b --- /dev/null +++ b/tests/contract/media_options_test.go @@ -0,0 +1,306 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package contract_test + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" +) + +// TestMediaOptionValidation pins how --processing and --resolution are +// validated and scoped: values come from the generated enums, each value is +// attached only to the inputs whose content type takes it on the request's API +// version, and a flag no input can take is a usage error raised before any +// request is sent. +func TestMediaOptionValidation(t *testing.T) { + newServer := func(t *testing.T) (*httptest.Server, *map[string]any, *atomic.Int32) { + t.Helper() + var body map[string]any + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + raw, _ := io.ReadAll(r.Body) + if err := json.Unmarshal(raw, &body); err != nil { + t.Errorf("decode interaction request: %v", err) + } + if body["stream"] == true { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int_1\",\"status\":\"completed\",\"steps\":[{\"type\":\"model_output\",\"content\":[{\"type\":\"text\",\"text\":\"streamed answer\"}]}]}}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, completedInteraction("unary answer", "")) + })) + t.Cleanup(server.Close) + return server, &body, &hits + } + + dir := t.TempDir() + write := func(name string) string { + t.Helper() + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(name+"-bytes"), 0o644); err != nil { + t.Fatal(err) + } + return path + } + video, pdf, audio, image := write("clip.mp4"), write("spec.pdf"), write("talk.mp3"), write("photo.png") + + // partsByType indexes the request's user-input content blocks by type. + partsByType := func(t *testing.T, body map[string]any) map[string]map[string]any { + t.Helper() + byType := map[string]map[string]any{} + for _, part := range assertUserInputStepParts(t, body) { + if typ, _ := part["type"].(string); typ != "" { + byType[typ] = part + } + } + return byType + } + + t.Run("unknown values are usage errors that name the valid ones", func(t *testing.T) { + for _, tc := range []struct { + name string + args []string + want []string + }{ + {"processing", []string{"analyze", "-i", video, "--processing", "turbo"}, + []string{`--processing "turbo" is not a processing mode`, "Valid values: static, agentic"}}, + {"resolution", []string{"analyze", "-i", video, "--resolution", "4k"}, + []string{`--resolution "4k" is not a media resolution`, "Valid values: low, medium, high, ultra_high"}}, + {"generate", []string{"generate", "-i", video, "--resolution", "4k", "Describe it"}, + []string{`--resolution "4k" is not a media resolution`}}, + {"remote files handle", []string{"analyze", "-i", "files/abc123", "--processing", "turbo"}, + []string{`--processing "turbo" is not a processing mode`, "Valid values: static, agentic"}}, + } { + t.Run(tc.name, func(t *testing.T) { + server, _, hits := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), tc.args...)...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + for _, want := range tc.want { + if !strings.Contains(result.stderr, want) { + t.Errorf("stderr = %q, want it to contain %q", result.stderr, want) + } + } + if result.stdout != "" { + t.Errorf("stdout = %q, want empty", result.stdout) + } + if got := hits.Load(); got != 0 { + t.Errorf("requests sent = %d, want 0", got) + } + }) + } + }) + + t.Run("values are matched case-insensitively", func(t *testing.T) { + server, body, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", video, "--processing", "AGENTIC", "--resolution", "High")...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + got := partsByType(t, *body)["video"] + if got["processing"] != "agentic" || got["resolution"] != "high" { + t.Errorf("video block = %#v, want processing agentic and resolution high", got) + } + }) + + t.Run("a value is attached only to the inputs that take it", func(t *testing.T) { + server, body, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", pdf, "-i", video, "-i", audio, "--processing", "agentic")...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + parts := partsByType(t, *body) + if parts["video"]["processing"] != "agentic" { + t.Errorf("video block = %#v, want processing agentic", parts["video"]) + } + for _, typ := range []string{"document", "audio"} { + if _, set := parts[typ]["processing"]; set { + t.Errorf("%s block = %#v, want no processing: agentic is a video mode", typ, parts[typ]) + } + } + }) + + t.Run("static applies to video, audio, and documents on v1beta", func(t *testing.T) { + server, body, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", pdf, "-i", video, "-i", audio, "--processing", "static")...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + parts := partsByType(t, *body) + for _, typ := range []string{"video", "document", "audio"} { + if parts[typ]["processing"] != "static" { + t.Errorf("%s block = %#v, want processing static", typ, parts[typ]) + } + } + }) + + t.Run("v1 skips the document and audio fields in a mixed call", func(t *testing.T) { + server, body, _ := newServer(t) + args := append(plainArgs(server.URL), "--api-version", "v1", "analyze", "-i", pdf, "-i", video, "-i", audio, "-i", image, + "--resolution", "high", "--processing", "static") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + parts := partsByType(t, *body) + if parts["video"]["resolution"] != "high" || parts["video"]["processing"] != "static" { + t.Errorf("video block = %#v, want resolution high and processing static", parts["video"]) + } + if parts["image"]["resolution"] != "high" { + t.Errorf("image block = %#v, want resolution high", parts["image"]) + } + for _, typ := range []string{"document", "audio"} { + for _, field := range []string{"resolution", "processing"} { + if _, set := parts[typ][field]; set { + t.Errorf("%s block = %#v, want no %s on v1", typ, parts[typ], field) + } + } + } + }) + + t.Run("v1 with only v1beta-only inputs points at v1beta", func(t *testing.T) { + for _, tc := range []struct { + name string + args []string + want string + }{ + {"document resolution", []string{"analyze", "-i", pdf, "--resolution", "high"}, "--resolution high is not available"}, + {"document processing", []string{"analyze", "-i", pdf, "--processing", "static"}, "--processing static is not available"}, + {"audio processing", []string{"analyze", "-i", audio, "--processing", "static"}, "--processing static is not available"}, + } { + t.Run(tc.name, func(t *testing.T) { + server, _, hits := newServer(t) + args := append(append(plainArgs(server.URL), "--api-version", "v1"), tc.args...) + result := runCLI(t, dir, nil, args...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + for _, want := range []string{tc.want, "--api-version v1beta"} { + if !strings.Contains(result.stderr, want) { + t.Errorf("stderr = %q, want it to contain %q", result.stderr, want) + } + } + if got := hits.Load(); got != 0 { + t.Errorf("requests sent = %d, want 0", got) + } + }) + } + }) + + t.Run("document resolution is sent on v1beta", func(t *testing.T) { + server, body, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", pdf, "--resolution", "high")...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + if got := partsByType(t, *body)["document"]; got["resolution"] != "high" { + t.Errorf("document block = %#v, want resolution high", got) + } + }) + + t.Run("a mode no input takes is rejected", func(t *testing.T) { + server, _, hits := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", pdf, "--processing", "agentic")...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + if !strings.Contains(result.stderr, "--processing applies to video, audio, and document inputs") || + !strings.Contains(result.stderr, `"agentic"`) { + t.Errorf("stderr = %q, want the modality hint naming the value", result.stderr) + } + if got := hits.Load(); got != 0 { + t.Errorf("requests sent = %d, want 0", got) + } + }) + + t.Run("dry-run previews a video block for an untyped files handle and a video-only mode", func(t *testing.T) { + server, _, hits := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", "files/abc123", "--processing", "agentic", "--dry-run")...) + if result.err != nil { + t.Fatalf("dry-run failed: %v\nstderr: %s", result.err, result.stderr) + } + preview := result.stdout + result.stderr + for _, want := range []string{`"type": "video"`, `"processing": "agentic"`, `"stream": true`} { + if !strings.Contains(preview, want) { + t.Errorf("preview missing %s\n%s", want, preview) + } + } + if strings.Contains(preview, `"type": "document"`) { + t.Errorf("preview shows a document block for a video-only mode\n%s", preview) + } + if got := hits.Load(); got != 0 { + t.Errorf("requests sent = %d, want 0", got) + } + }) + + t.Run("dry-run on v1 previews a video block for an untyped files handle", func(t *testing.T) { + for _, tc := range []struct { + name string + args []string + want string + }{ + {"processing", []string{"--processing", "static"}, `"processing": "static"`}, + {"resolution", []string{"--resolution", "high"}, `"resolution": "high"`}, + } { + t.Run(tc.name, func(t *testing.T) { + server, _, hits := newServer(t) + args := append(plainArgs(server.URL), "--api-version", "v1", "analyze", "-i", "files/abc123", "--dry-run") + result := runCLI(t, dir, nil, append(args, tc.args...)...) + if result.err != nil { + t.Fatalf("dry-run failed: %v\nstderr: %s", result.err, result.stderr) + } + preview := result.stdout + result.stderr + for _, want := range []string{`"type": "video"`, tc.want} { + if !strings.Contains(preview, want) { + t.Errorf("preview missing %s\n%s", want, preview) + } + } + if got := hits.Load(); got != 0 { + t.Errorf("requests sent = %d, want 0", got) + } + }) + } + }) + + t.Run("dry-run on v1 still rejects an explicit document type", func(t *testing.T) { + server, _, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "--api-version", "v1", "analyze", "-i", "files/abc123", "--mime-type", "application/pdf", "--processing", "static", "--dry-run")...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + if !strings.Contains(result.stderr, "--api-version v1beta") { + t.Errorf("stderr does not point at v1beta\n%s", result.stderr) + } + }) + + t.Run("dry-run still rejects a video-only mode on an explicit document type", func(t *testing.T) { + server, _, _ := newServer(t) + result := runCLI(t, dir, nil, append(plainArgs(server.URL), "analyze", "-i", "files/abc123", "--mime-type", "application/pdf", "--processing", "agentic", "--dry-run")...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + }) +} diff --git a/tests/contract/porcelain_inputs_test.go b/tests/contract/porcelain_inputs_test.go index d4dba933..62f45c4f 100644 --- a/tests/contract/porcelain_inputs_test.go +++ b/tests/contract/porcelain_inputs_test.go @@ -245,6 +245,135 @@ func TestAnalyzeInputValidation(t *testing.T) { } }) + t.Run("--upload sends an over-cap file through the Files API", func(t *testing.T) { + mock := newUploadMock(t) + var interactionBody []byte + mock.respond = func(w http.ResponseWriter, r uploadRequest) bool { + if r.command != "" { + return false + } + interactionBody = r.body + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, completedInteraction("ok", "")) + return true + } + dir := t.TempDir() + big := filepath.Join(dir, "big.mp4") + if err := os.WriteFile(big, bytes.Repeat([]byte{'x'}, 21<<20), 0o644); err != nil { + t.Fatal(err) + } + args := append(plainArgs(mock.URL), "analyze", "-i", big, "--upload", "What happens?") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze --upload failed: %v\nstderr: %s", result.err, result.stderr) + } + if got := strings.TrimSpace(result.stdout); got != "ok" { + t.Errorf("stdout = %q, want ok", got) + } + chunks := 0 + for _, r := range mock.recorded() { + if strings.HasPrefix(r.command, "upload") { + chunks++ + } + } + if chunks != 3 { + t.Errorf("upload chunks = %d, want 3 for 21 MB in 8 MiB chunks", chunks) + } + for _, want := range []string{`"type":"video"`, `"uri":"https://example/files/xyz789"`, `"mime_type":"video/mp4"`} { + if !strings.Contains(string(interactionBody), want) { + t.Errorf("interaction body missing %s:\n%s", want, interactionBody) + } + } + if strings.Contains(string(interactionBody), `"data"`) { + t.Errorf("interaction body still carries inline data:\n%s", interactionBody) + } + }) + + t.Run("--upload waits for PROCESSING file to become ACTIVE", func(t *testing.T) { + mock := newUploadMock(t) + var polls atomic.Int32 + var interactionBody []byte + mock.respond = func(w http.ResponseWriter, r uploadRequest) bool { + switch { + case r.command == "upload, finalize": + w.Header().Set("X-Goog-Upload-Status", "final") + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"file":{"name":"files/proc123","uri":"https://example/files/proc123","mimeType":"video/mp4","state":"PROCESSING"}}`) + return true + case r.method == http.MethodGet && strings.Contains(r.path, "/files/proc123"): + polls.Add(1) + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"name":"files/proc123","uri":"https://example/files/proc123","mimeType":"video/mp4","state":"ACTIVE"}`) + return true + case r.command == "": + interactionBody = r.body + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, completedInteraction("ready", "")) + return true + } + return false + } + dir := t.TempDir() + clip := filepath.Join(dir, "clip.mp4") + if err := os.WriteFile(clip, []byte("video-bytes"), 0o644); err != nil { + t.Fatal(err) + } + args := append(plainArgs(mock.URL), "analyze", "-i", clip, "--upload", "Describe") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze --upload failed: %v\nstderr: %s", result.err, result.stderr) + } + if got := strings.TrimSpace(result.stdout); got != "ready" { + t.Errorf("stdout = %q, want ready", got) + } + if polls.Load() != 1 { + t.Errorf("files.get polls = %d, want 1", polls.Load()) + } + if !strings.Contains(string(interactionBody), `"uri":"https://example/files/proc123"`) { + t.Errorf("interaction body missing uploaded uri:\n%s", interactionBody) + } + }) + + t.Run("--upload --dry-run previews upload and placeholder without network calls", func(t *testing.T) { + mock := newUploadMock(t) + dir := t.TempDir() + clip := filepath.Join(dir, "clip.mp4") + if err := os.WriteFile(clip, []byte("video-bytes"), 0o644); err != nil { + t.Fatal(err) + } + args := append(plainArgs(mock.URL), "--dry-run", "analyze", "-i", clip, "--upload", "Describe") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze --upload --dry-run failed: %v\nstderr: %s", result.err, result.stderr) + } + if got := len(mock.recorded()); got != 0 { + t.Errorf("recorded requests = %d, want 0 under --dry-run", got) + } + if !strings.Contains(result.stderr, "files/") { + t.Errorf("stderr missing placeholder URI:\n%s", result.stderr) + } + }) + + t.Run("transcribe --upload rejects video on audio-only model before uploading", func(t *testing.T) { + mock := newUploadMock(t) + dir := t.TempDir() + clip := filepath.Join(dir, "clip.mp4") + if err := os.WriteFile(clip, []byte("video-bytes"), 0o644); err != nil { + t.Fatal(err) + } + args := append(plainArgs(mock.URL), "transcribe", "-i", clip, "--upload", "--model", "gemini-3.8-flash-transcribe") + result := runCLI(t, dir, nil, args...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + if got := len(mock.recorded()); got != 0 { + t.Errorf("recorded requests = %d, want 0 (must validate before uploading)", got) + } + if !strings.Contains(result.stderr, "only accepts audio inputs") { + t.Errorf("stderr = %q, want audio-only model error", result.stderr) + } + }) + t.Run("existing path beats the files/ spelling", func(t *testing.T) { // A local ./files/abc is a file, never a Files API lookup. var lookups atomic.Int32 @@ -286,6 +415,246 @@ func TestAnalyzeInputValidation(t *testing.T) { }) } +// TestAnalyzeMediaOptions pins --processing and --resolution: they land on +// every block whose content type carries the field, a video processed in a +// non-static mode is requested as an internal SSE stream that still yields one +// answer, and a flag no input can take is a usage error. +func TestAnalyzeMediaOptions(t *testing.T) { + const streamedCompletion = "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int_1\",\"status\":\"completed\",\"steps\":[{\"type\":\"model_output\",\"content\":[{\"type\":\"text\",\"text\":\"streamed answer\"}]}],\"usage\":{\"total_input_tokens\":9,\"total_output_tokens\":2,\"total_tokens\":11}}}\n\ndata: [DONE]\n\n" + + newServer := func(t *testing.T) (*httptest.Server, *map[string]any) { + t.Helper() + var body map[string]any + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + if err := json.Unmarshal(raw, &body); err != nil { + t.Errorf("decode interaction request: %v", err) + } + if body["stream"] == true { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, streamedCompletion) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, completedInteraction("unary answer", "")) + })) + t.Cleanup(server.Close) + return server, &body + } + + dir := t.TempDir() + video := filepath.Join(dir, "clip.mp4") + if err := os.WriteFile(video, []byte("video-bytes"), 0o644); err != nil { + t.Fatal(err) + } + image := filepath.Join(dir, "photo.png") + if err := os.WriteFile(image, []byte("png-bytes"), 0o644); err != nil { + t.Fatal(err) + } + + t.Run("agentic video streams internally and carries both options", func(t *testing.T) { + server, body := newServer(t) + args := append(plainArgs(server.URL), "--output-format", "json", "analyze", "-i", video, "--processing", "agentic", "--resolution", "high", "What happens?") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + if (*body)["stream"] != true || (*body)["store"] != false { + t.Errorf("stream/store = %v/%v, want true/false", (*body)["stream"], (*body)["store"]) + } + parts := assertUserInputStepParts(t, *body) + if len(parts) != 2 || parts[0]["type"] != "video" || parts[0]["processing"] != "agentic" || parts[0]["resolution"] != "high" { + t.Errorf("video block = %#v, want processing agentic and resolution high", parts) + } + var envelope struct { + Text string `json:"text"` + Usage map[string]any `json:"usage"` + } + if err := json.Unmarshal([]byte(result.stdout), &envelope); err != nil { + t.Fatalf("decode envelope: %v\n%s", err, result.stdout) + } + if envelope.Text != "streamed answer" || envelope.Usage["total_tokens"] != float64(11) { + t.Errorf("envelope = %+v, want the streamed text and usage", envelope) + } + }) + + t.Run("agentic video falls back to step.delta text when completed omits steps", func(t *testing.T) { + const deltaOnlyStream = "" + + "data: {\"event_type\":\"step.delta\",\"index\":0,\"delta\":{\"type\":\"text\",\"text\":\"hello \"}}\n\n" + + "data: {\"event_type\":\"step.delta\",\"index\":0,\"delta\":{\"type\":\"text\",\"text\":\"from deltas\"}}\n\n" + + "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int_2\",\"status\":\"completed\",\"usage\":{\"total_input_tokens\":5,\"total_output_tokens\":3,\"total_tokens\":8}}}\n\n" + + "data: [DONE]\n\n" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, deltaOnlyStream) + })) + defer server.Close() + + args := append(plainArgs(server.URL), "--output-format", "json", "analyze", "-i", video, "--processing", "agentic") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + var envelope struct { + Text string `json:"text"` + Usage map[string]any `json:"usage"` + } + if err := json.Unmarshal([]byte(result.stdout), &envelope); err != nil { + t.Fatalf("decode envelope: %v\n%s", err, result.stdout) + } + if envelope.Text != "hello from deltas" || envelope.Usage["total_tokens"] != float64(8) { + t.Errorf("envelope = %+v, want delta-assembled text and usage", envelope) + } + }) + + t.Run("streamed error event preserves stream error classification", func(t *testing.T) { + const errorStream = "data: {\"event_type\":\"error\",\"error\":{\"code\":\"internal_error\",\"message\":\"backend failed mid-stream\"}}\n\ndata: [DONE]\n\n" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, errorStream) + })) + defer server.Close() + + args := append(plainArgs(server.URL), "--output-format", "json", "analyze", "-i", video, "--processing", "agentic") + result := runCLI(t, dir, nil, args...) + if result.err == nil { + t.Fatal("analyze unexpectedly succeeded on stream error event") + } + var errEnv struct { + ErrorType string `json:"error_type"` + Message string `json:"message"` + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal([]byte(result.stderr), &errEnv); err != nil { + t.Fatalf("decode error envelope: %v\nstderr: %s", err, result.stderr) + } + if errEnv.ErrorType != "api_error" || errEnv.Error.Code != "internal_error" || errEnv.Message != "backend failed mid-stream" { + t.Errorf("error envelope = %+v, want api_error / internal_error / backend failed mid-stream\nraw: %s", errEnv, result.stderr) + } + }) + + t.Run("streamed requires_continuation status is rejected as incomplete", func(t *testing.T) { + const contStream = "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int_3\",\"status\":\"requires_continuation\",\"steps\":[{\"type\":\"model_output\",\"content\":[{\"type\":\"text\",\"text\":\"partial\"}]}]}}\n\ndata: [DONE]\n\n" + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, contStream) + })) + defer server.Close() + + args := append(plainArgs(server.URL), "analyze", "-i", video, "--processing", "agentic") + result := runCLI(t, dir, nil, args...) + if code := exitCode(t, result); code != 1 { + t.Errorf("exit code = %d, want 1\nstderr: %s", code, result.stderr) + } + if !strings.Contains(result.stderr, "requires_continuation") { + t.Errorf("stderr = %q, want requires_continuation status error", result.stderr) + } + }) + + t.Run("static video stays unary", func(t *testing.T) { + server, body := newServer(t) + args := append(plainArgs(server.URL), "analyze", "-i", video, "--processing", "static") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + if (*body)["stream"] != false { + t.Errorf("stream = %v, want false", (*body)["stream"]) + } + parts := assertUserInputStepParts(t, *body) + if len(parts) != 2 || parts[0]["processing"] != "static" || parts[0]["resolution"] != nil { + t.Errorf("video block = %#v, want processing static and no resolution", parts) + } + if strings.TrimSpace(result.stdout) != "unary answer" { + t.Errorf("stdout = %q, want unary answer", result.stdout) + } + }) + + t.Run("image takes resolution and rejects processing before upload", func(t *testing.T) { + server, body := newServer(t) + args := append(plainArgs(server.URL), "analyze", "-i", image, "--resolution", "low") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("analyze failed: %v\nstderr: %s", result.err, result.stderr) + } + parts := assertUserInputStepParts(t, *body) + if len(parts) != 2 || parts[0]["type"] != "image" || parts[0]["resolution"] != "low" { + t.Errorf("image block = %#v, want resolution low", parts) + } + + mock := newUploadMock(t) + result = runCLI(t, dir, nil, append(plainArgs(mock.URL), "analyze", "-i", image, "--upload", "--processing", "agentic")...) + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + if !strings.Contains(result.stderr, "--processing applies to video, audio, and document inputs") { + t.Errorf("stderr = %q, want the modality hint", result.stderr) + } + if got := len(mock.recorded()); got != 0 { + t.Errorf("recorded upload requests = %d, want 0 before option validation", got) + } + + dryResult := runCLI(t, dir, nil, append(plainArgs(mock.URL), "--dry-run", "analyze", "-i", image, "--upload", "--processing", "agentic")...) + if code := exitCode(t, dryResult); code != 2 { + t.Errorf("dry-run exit code = %d, want 2\nstderr: %s", code, dryResult.stderr) + } + if strings.Contains(dryResult.stderr, "[DRY-RUN]") { + t.Errorf("dry-run emitted upload preview before failing validation:\n%s", dryResult.stderr) + } + }) + + t.Run("generate forwards the options on its media input", func(t *testing.T) { + server, body := newServer(t) + args := append(plainArgs(server.URL), "generate", "-i", image, "--resolution", "medium", "--stream=false", "Describe it") + result := runCLI(t, dir, nil, args...) + if result.err != nil { + t.Fatalf("generate failed: %v\nstderr: %s", result.err, result.stderr) + } + parts := assertUserInputStepParts(t, *body) + if len(parts) != 2 || parts[0]["type"] != "image" || parts[0]["resolution"] != "medium" { + t.Errorf("image block = %#v, want resolution medium", parts) + } + }) + + t.Run("media flags without --input are rejected instead of silently dropped", func(t *testing.T) { + cases := []struct { + name string + args []string + stdin string + wantErr string + }{ + {"generate --processing", []string{"generate", "hi", "--processing", "agentic"}, "", "--processing requires --input"}, + {"generate --resolution", []string{"generate", "hi", "--resolution", "high"}, "", "--resolution requires --input"}, + {"generate --upload", []string{"generate", "hi", "--upload"}, "", "--upload requires --input"}, + {"generate bare --processing", []string{"generate", "--processing", "agentic"}, "", "--processing requires --input"}, + {"agent run --processing", []string{"agent", "run", "hi", "--processing", "agentic"}, "", "--processing requires --input"}, + {"agent run --upload", []string{"agent", "run", "hi", "--upload"}, "", "--upload requires --input"}, + {"analyze --stdin --upload", []string{"analyze", "--stdin", "--upload"}, "hello", "--upload requires --input"}, + {"analyze --stdin --processing", []string{"analyze", "--stdin", "--processing", "agentic"}, "hello", "--processing applies to video, audio, and document inputs"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fullArgs := append(plainArgs("https://example.invalid"), tc.args...) + var result commandResult + if tc.stdin != "" { + result = runCLIWithStdin(t, dir, nil, tc.stdin, fullArgs...) + } else { + result = runCLI(t, dir, nil, fullArgs...) + } + if code := exitCode(t, result); code != 2 { + t.Errorf("exit code = %d, want 2\nstderr: %s", code, result.stderr) + } + if !strings.Contains(result.stderr, tc.wantErr) { + t.Errorf("stderr = %q, want %q", result.stderr, tc.wantErr) + } + }) + } + }) +} + func TestAnalyzeBareNonTTYAndAgentMode(t *testing.T) { t.Run("empty pipe is a usage error without hanging", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)