From b95bb1c6ed7df10299ab1309bf155d2fa1bd7691 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:28:57 +0000 Subject: [PATCH 1/3] fix(flow): verify generation controls and composer state - Default video_type to ingredients and reject invalid video options - Map veo-3.1-fast and legacy slugs to live model family labels - Match model family labels and Wqa entries with anchored patterns - Verify active Qa model and SKb aspect ratio after UI selection - Clear stale prompt text and ingredient chips before new runs - Reject all 11 Rp disable codes before generation submission --- docs/en/tools-reference.md | 8 +- docs/ja/tools-reference.md | 8 +- docs/zh-CN/tools-reference.md | 8 +- src/generation.rs | 170 +++++++++++--- ts/attach_ingredients.ts | 217 ++++++++++++++---- ts/setup_generation.ts | 405 +++++++++++++++++++++++++++++----- ts/submit_generation.ts | 81 ++++++- ts/types.ts | 34 ++- 8 files changed, 781 insertions(+), 150 deletions(-) diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..ad96007 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -200,13 +200,13 @@ Queue a Veo video or Imagen image generation job on `JobQueue`. Returns a `JobVi | :--- | :--- | :--- | :--- | | `prompt` | `string` | Yes | Text prompt that `flow-mcp` sends to Google Flow. | | `mode` | `string` | No | `"video"` (default) or `"image"`. | -| `model` | `string` | No | Model override. Defaults to `"veo-3.1-fast"` (`video`) or `"nano-banana-2"` (`image`). | -| `aspect` | `string` | No | Aspect ratio: `"16:9"` (default), `"9:16"`, or `"1:1"`. | +| `model` | `string` | No | Model override. Defaults to `"Veo 3.1 Lite"` (`video`) or `"Nano Banana 2"` (`image`), and maps legacy slugs such as `"veo-3.1-fast"`. | +| `aspect` | `string` | No | Aspect ratio: `"16:9"` (default), `"9:16"`, or `"1:1"` (`image` mode only). | | `count` | `integer` | No | Output batch count in `1..=4`. Default `2`. | | `frames` | `string[]` | No | Local reference or keyframe image paths to upload before submission. | | `asset_ids` | `string[]` | No | Existing project image asset IDs to attach as ingredients or frames. | -| `characters` | `string[]` | No | Character IDs or names to attach to the prompt controls. | -| `video_type` | `string` | No | Video generation mode: `"frames"` or `"ingredients"`. | +| `characters` | `string[]` | No | Character IDs or names to attach in `"ingredients"` or `"image"` mode. | +| `video_type` | `string` | No | Video generation mode: `"ingredients"` (default) or `"frames"`. | | `duration` | `string` | No | Video duration setting (for example `"5s"` or `"8s"`). | | `resolution` | `string` | No | Video resolution setting (for example `"720p"`, `"1080p"`, or `"4K"`). | | `name` | `string` | No | Optional scene or asset label for the job. | diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index 559b074..a613538 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -200,13 +200,13 @@ Google Flow でキャラクターボイスピッカーを開き、リスト全 | :--- | :--- | :--- | :--- | | `prompt` | `string` | はい | `flow-mcp` が Google Flow へ送信するテキストプロンプト。 | | `mode` | `string` | いいえ | `"video"`(既定)または `"image"`。 | -| `model` | `string` | いいえ | モデル上書き。既定は `"veo-3.1-fast"`(`video`)または `"nano-banana-2"`(`image`)。 | -| `aspect` | `string` | いいえ | アスペクト比:`"16:9"`(既定)、`"9:16"`、または `"1:1"`。 | +| `model` | `string` | いいえ | モデル上書き。既定は `"Veo 3.1 Lite"`(`video`)または `"Nano Banana 2"`(`image`)で、`"veo-3.1-fast"` などの旧スラッグも対応します。 | +| `aspect` | `string` | いいえ | アスペクト比:`"16:9"`(既定)、`"9:16"`、または `"1:1"`(`image` モードのみ)。 | | `count` | `integer` | いいえ | 出力バッチ数(`1..=4`)。既定は `2`。 | | `frames` | `string[]` | いいえ | 送信前にアップロードするローカル参照またはキーフレーム画像パス。 | | `asset_ids` | `string[]` | いいえ | 素材またはフレームとして添付する既存プロジェクト画像アセット ID。 | -| `characters` | `string[]` | いいえ | プロンプトコントロールへ添付するキャラクター ID または名前。 | -| `video_type` | `string` | いいえ | 動画生成モード:`"frames"` または `"ingredients"`。 | +| `characters` | `string[]` | いいえ | `"ingredients"` または `"image"` モードで添付するキャラクター ID または名前。 | +| `video_type` | `string` | いいえ | 動画生成モード:`"ingredients"`(既定)または `"frames"`。 | | `duration` | `string` | いいえ | 動画尺設定(たとえば `"5s"` または `"8s"`)。 | | `resolution` | `string` | いいえ | 動画解像度設定(たとえば `"720p"`、`"1080p"`、または `"4K"`)。 | | `name` | `string` | いいえ | ジョブ用の任意のシーンまたはアセットラベル。 | diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..fbdc2d4 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -200,13 +200,13 @@ flow-mcp [OPTIONS] | :--- | :--- | :--- | :--- | | `prompt` | `string` | 是 | `flow-mcp` 发送给 Google Flow 的文本提示词。 | | `mode` | `string` | 否 | `"video"`(默认)或 `"image"`。 | -| `model` | `string` | 否 | 模型覆盖。默认为 `"veo-3.1-fast"`(`video`)或 `"nano-banana-2"`(`image`)。 | -| `aspect` | `string` | 否 | 画面比例:`"16:9"`(默认)、`"9:16"` 或 `"1:1"`。 | +| `model` | `string` | 否 | 模型覆盖。默认为 `"Veo 3.1 Lite"`(`video`)或 `"Nano Banana 2"`(`image`),并映射 `"veo-3.1-fast"` 等旧标识。 | +| `aspect` | `string` | 否 | 画面比例:`"16:9"`(默认)、`"9:16"` 或 `"1:1"`(仅限 `image` 模式)。 | | `count` | `integer` | 否 | 输出批次数量,范围 `1..=4`。默认 `2`。 | | `frames` | `string[]` | 否 | 提交前上传的本地参考图像或关键帧路径。 | | `asset_ids` | `string[]` | 否 | 作为素材或关键帧附加的既有项目图像资产 ID。 | -| `characters` | `string[]` | 否 | 附加到提示词控件的角色 ID 或名称。 | -| `video_type` | `string` | 否 | 视频生成模式:`"frames"` 或 `"ingredients"`。 | +| `characters` | `string[]` | 否 | 在 `"ingredients"` 或 `"image"` 模式下附加的角色 ID 或名称。 | +| `video_type` | `string` | 否 | 视频生成模式:`"ingredients"`(默认)或 `"frames"`。 | | `duration` | `string` | 否 | 视频时长设置(例如 `"5s"` 或 `"8s"`)。 | | `resolution` | `string` | 否 | 视频分辨率设置(例如 `"720p"`、`"1080p"` 或 `"4K"`)。 | | `name` | `string` | 否 | 任务的可选场景或资产标签。 | diff --git a/src/generation.rs b/src/generation.rs index b9f3f55..b9e4b4b 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -34,9 +34,9 @@ pub(crate) struct GenerateParams { pub(crate) prompt: String, /// Generation mode: "video" (default) or "image". pub(crate) mode: Option, - /// Model name override (defaults to "veo-3.1-fast" for video or "nano-banana-2" for image). + /// Model name override (defaults to "Veo 3.1 Lite" for video or "Nano Banana 2" for image; maps legacy slugs such as "veo-3.1-fast"). pub(crate) model: Option, - /// Output aspect ratio: "16:9" (default), "9:16", or "1:1". + /// Output aspect ratio: "16:9" (default), "9:16", or "1:1" (image mode only). pub(crate) aspect: Option, /// Output count from 1 to 4 (default 2). #[schemars(range(min = 1, max = 4))] @@ -55,7 +55,7 @@ pub(crate) struct GenerateParams { pub(crate) asset_ids: Option>, /// Existing character IDs or names to attach to video or image generation. pub(crate) characters: Option>, - /// Video generation mode (`"frames"` or `"ingredients"`). + /// Video generation mode ("ingredients" default or "frames"). pub(crate) video_type: Option, /// Video duration setting (for example `"5s"` or `"8s"`). pub(crate) duration: Option, @@ -87,35 +87,150 @@ struct AssetWaitSpec<'a> { submit_summary: &'a str, } +/// Validated and normalized control parameters sent to the browser generation runtime. +struct NormalizedControls { + /// Canonical mode string (`"video"` or `"image"`). + mode: &'static str, + /// Canonical aspect ratio label. + aspect: String, + /// Live `Select model family` display name or caller override. + model: String, + /// Normalized video mode (`Some("ingredients")` or `Some("frames")`) for video runs. + video_type: Option<&'static str>, + /// Clamped batch output count in `1..=4`. + count: u32, +} + +/// Maps legacy model slugs and defaults to live `Select model family` display names. +fn normalize_model_name(raw: Option<&str>, mode: &str) -> String { + let trimmed = raw.map(str::trim).unwrap_or(""); + if trimmed.is_empty() { + return if mode == "image" { + "Nano Banana 2".to_string() + } else { + "Veo 3.1 Lite".to_string() + }; + } + let key = trimmed + .split(|ch: char| ch.is_whitespace() || matches!(ch, '-' | '_' | '.')) + .filter(|part| !part.is_empty()) + .map(str::to_ascii_lowercase) + .collect::>() + .join("_"); + match key.as_str() { + "veo_3_1_fast" | "veo_3_1_lite" => "Veo 3.1 Lite".to_string(), + "veo_3_1" | "veo_3_1_quality" => "Veo 3.1".to_string(), + "veo_3_fast" => "Veo 3 Fast".to_string(), + "veo_3" => "Veo 3".to_string(), + "veo_2" | "veo_2_fast" | "veo_2_quality" => "Veo 2".to_string(), + "gemini_omni" | "macaron_cookie" => "Gemini Omni".to_string(), + "nano_banana" => "Nano Banana".to_string(), + "nano_banana_2" => "Nano Banana 2".to_string(), + "nano_banana_pro" => "Nano Banana Pro".to_string(), + "imagen_3" => "Imagen 3".to_string(), + "imagen_4" => "Imagen 4".to_string(), + _ => trimmed.to_string(), + } +} + +/// Normalizes generation parameters and rejects invalid video aspect, character, and frame combinations. +fn resolve_generation_controls(scene: &SceneParams) -> Result { + let raw_mode = scene + .mode + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("video"); + let mode = if raw_mode.eq_ignore_ascii_case("image") + || raw_mode.eq_ignore_ascii_case("character") + || raw_mode.eq_ignore_ascii_case("scene") + { + "image" + } else { + "video" + }; + let aspect = scene + .aspect + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("16:9"); + if mode == "video" && (aspect == "1:1" || aspect.eq_ignore_ascii_case("square")) { + anyhow::bail!("Video mode does not support aspect ratio '{aspect}'; use '16:9' or '9:16'"); + } + let video_type = if mode == "video" { + match scene + .video_type + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + { + None => Some("ingredients"), + Some(vt) + if vt.eq_ignore_ascii_case("ingredients") + || vt.eq_ignore_ascii_case("ingredient") + || vt.eq_ignore_ascii_case("video_ingredients") + || vt.eq_ignore_ascii_case("video_references") => + { + Some("ingredients") + } + Some(vt) + if vt.eq_ignore_ascii_case("frames") + || vt.eq_ignore_ascii_case("frame") + || vt.eq_ignore_ascii_case("video_frames") => + { + Some("frames") + } + Some(vt) => anyhow::bail!( + "Unsupported video_type '{vt}' for video mode; use 'ingredients' or 'frames'" + ), + } + } else { + None + }; + if video_type == Some("frames") { + let has_characters = scene + .characters + .as_ref() + .is_some_and(|chars| chars.iter().any(|c| !c.trim().is_empty()) || !chars.is_empty()); + if has_characters { + anyhow::bail!( + "Video frames mode does not support character references; use video_type 'ingredients'" + ); + } + let ref_count = scene.frames.as_ref().map_or(0, Vec::len) + + scene.asset_ids.as_ref().map_or(0, Vec::len); + anyhow::ensure!( + ref_count <= 2, + "Frame mode accepts at most two references, got {ref_count}" + ); + } + Ok(NormalizedControls { + mode, + aspect: aspect.to_string(), + model: normalize_model_name(scene.model.as_deref(), mode), + video_type, + count: scene.count.unwrap_or(2).clamp(1, 4), + }) +} + /// Configures generation controls, uploads reference frames, writes prompt text, and submits. async fn apply_generation_controls( engine: &ChromeEngine, scene: &SceneParams, ) -> Result { + let controls = resolve_generation_controls(scene)?; validate_local_files(scene.frames.as_deref(), "Reference image").await?; - let raw_mode = scene.mode.as_deref().unwrap_or("video"); - let mode = match raw_mode { - "image" | "character" | "scene" => "image", - _ => "video", - }; - let aspect = scene.aspect.as_deref().unwrap_or("16:9"); - let model = scene.model.as_deref().unwrap_or(if mode == "image" { - "nano-banana-2" - } else { - "veo-3.1-fast" - }); - let count = scene.count.unwrap_or(2).clamp(1, 4); - let cfg = json!({ - "mode": mode, - "aspect": aspect, - "model": model, - "count": count, + "mode": controls.mode, + "aspect": controls.aspect, + "model": controls.model, + "count": controls.count, "prompt": scene.prompt, "asset_ids": scene.asset_ids, "characters": scene.characters, - "video_type": scene.video_type, + "video_type": controls.video_type, "duration": scene.duration, "resolution": scene.resolution, }); @@ -525,17 +640,12 @@ pub(crate) async fn run_generation( scene: &SceneParams, on_progress: ProgressCallback, ) -> Result<(Vec, Vec, Vec)> { + let controls = resolve_generation_controls(scene)?; ensure_project_workspace_root(engine).await?; ensure_flow_store(engine).await?; - if scene.video_type.as_deref() == Some("frames") { - let count = scene.frames.as_ref().map_or(0, Vec::len) - + scene.asset_ids.as_ref().map_or(0, Vec::len) - + scene.characters.as_ref().map_or(0, Vec::len); - anyhow::ensure!( - count <= 2, - "Frame mode accepts at most two references, got {count}" - ); - } + let mut normalized_scene = scene.clone(); + normalized_scene.video_type = controls.video_type.map(str::to_string); + let scene = &normalized_scene; // Upload local frames into the library first and attach them as assets, so that the // uploaded tiles are not counted as generated outputs. let uploaded_scene; diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 10bef6d..42eff88 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -28,6 +28,7 @@ import { elText, fifeBase, hoverProbe, + isDisabledProp, isVisibleEnabled, pickTileUrl, setNativeValue, @@ -68,14 +69,72 @@ function itemMatchesTarget(item: unknown, target: IngredientTarget): boolean { name.trim().toLowerCase() === target.name.toLowerCase()); } -/** Returns true while a prompt item is loading or when it cannot be submitted. */ -function itemNotReady(item: unknown): boolean { - const invalid = /^(?:INVALID|ERROR|FAILED|PENDING|LOADING)(?:_|$)/i; - return readOwn(item, "isLoading") === true || - ["Rp", "tl"].some((field) => { - const state = readOwn(item, field); - return typeof state === "string" && invalid.test(state); - }); +/** Live `Rp` ingredient disable codes defined in `level1.js` (`n7b` / `l7b`). */ +const LIVE_RP_DISABLE_CODES: ReadonlySet = new Set([ + "CAPACITY_EXCEEDED", + "AGENT_CAPACITY_EXCEEDED", + "IMAGE_REFERENCES_EXCEEDED", + "AUDIO_REFERENCES_EXCEEDED", + "DURATION_NOT_SUPPORTED", + "TYPE_NOT_SUPPORTED", + "IMAGE_MODE_NOT_SUPPORTED", + "MISSING_VISUAL_INGREDIENT", + "INVALID_CHARACTER_NO_IMAGES", + "MISSING_PAIRED_FRAME", + "DIFFERENT_AGENT_SESSION", +]); + +/** Selector matching `flow-ingredient-chip`, all 7 `flow-*-ingredient-chip` tags, and `.upload-slot-filled-chip`. */ +const COMPOSER_CHIP_HOST_SELECTOR = [ + "flow-ingredient-chip", + "flow-image-ingredient-chip", + "flow-character-ingredient-chip", + "flow-video-ingredient-chip", + "flow-audio-ingredient-chip", + "flow-likeness-ingredient-chip", + "flow-style-pack-ingredient-chip", + "flow-file-ingredient-chip", + ".upload-slot-filled-chip", +].join(", "); + +/** Selector matching buttons inside composer ingredient and upload-slot chips. */ +const COMPOSER_CHIP_BUTTON_SELECTOR = [ + "flow-prompt-box flow-ingredient-chip button", + "flow-prompt-box flow-image-ingredient-chip button", + "flow-prompt-box flow-character-ingredient-chip button", + "flow-prompt-box flow-video-ingredient-chip button", + "flow-prompt-box flow-audio-ingredient-chip button", + "flow-prompt-box flow-likeness-ingredient-chip button", + "flow-prompt-box flow-style-pack-ingredient-chip button", + "flow-prompt-box flow-file-ingredient-chip button", + "flow-prompt-box .upload-slot-filled-chip button", + 'flow-prompt-box button[aria-label*="Remove" i]', +].join(", "); + +/** Selector excluding Flow Agent drawer composers from manual composer cleanup. */ +const AGENT_COMPOSER_EXCLUSION_SELECTOR = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + +/** Returns true while a prompt item is still loading asynchronously. */ +function itemLoading(item: unknown): boolean { + return readOwn(item, "isLoading") === true; +} + +/** Returns the terminal `Rp` disable code (or legacy invalid `tl` state) when an item cannot be submitted. */ +function itemDisabledReason(item: unknown): string | null { + const rp = readOwn(item, "Rp"); + if (typeof rp === "string" && rp.trim().length > 0) { + const code = rp.trim(); + return LIVE_RP_DISABLE_CODES.has(code) ? code : code; + } + const tl = readOwn(item, "tl"); + if ( + typeof tl === "string" && + /^(?:INVALID|ERROR|FAILED)(?:_|$)/i.test(tl.trim()) + ) { + return tl.trim(); + } + return null; } /** Verifies the requested frame in each slot before the prompt can be submitted. */ @@ -85,7 +144,7 @@ function framesReady(items: unknown[] | null, targets: IngredientTarget[]): bool return targets.every((target, index) => { const slot = index === 0 ? "FIRST_FRAME" : "LAST_FRAME"; const item = hasSlots ? items.find((entry) => readOwn(entry, "Ud") === slot) : items[index]; - return !itemNotReady(item) && itemMatchesTarget(item, target); + return !itemLoading(item) && !itemDisabledReason(item) && itemMatchesTarget(item, target); }); } @@ -188,17 +247,57 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const initialTb = onEditPage ? findTextbox(true) : await ensureManualComposer(); if (!onEditPage && !initialTb) return { ok: false, error: "manual_prompt_not_ready" }; - if (ingredientTargets.length > 0 && !onEditPage) { - for (let pass = 0; pass < 4; pass += 1) { + const readPageItems = ( + page: ReturnType, + ux?: ReturnType, + ): Array> | null => { + const raw = + page?.Qa?.oc?.all?.() ?? + page?.Qa?.kc?.all?.() ?? + page?.oc?.all?.() ?? + ux?.Qa?.oc?.all?.() ?? + ux?.Qa?.kc?.all?.() ?? + runtimeState.promptState?.oc?.all?.() ?? + runtimeState.promptState?.kc?.all?.(); + return Array.isArray(raw) ? raw : null; + }; + + if (!onEditPage && !(runtimeState.ngLViewMap instanceof Map)) { + const tipEls = Array.from( + document.querySelectorAll("[mattooltip], button[aria-label]"), + ).slice(0, 8); + if (tipEls.length > 0) { + await withLViewMapCapture(async () => { + await hoverProbe(tipEls, 50); + }); + } + } + + if (!onEditPage) { + const clearBtn = Array.from( + document.querySelectorAll( + 'flow-prompt-box button[aria-label="Clear prompt"], button[aria-label="Clear prompt"]', + ), + ).find( + (el): el is HTMLElement => + isVisibleEnabled(el) && !el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR), + ); + if (clearBtn) { + clearBtn.click(); + await delay(120); + } + + for (let pass = 0; pass < 6; pass += 1) { const staleRemoveBtns = Array.from( - document.querySelectorAll( - 'flow-prompt-box flow-image-ingredient-chip button, flow-prompt-box button[aria-label*="Remove" i], flow-prompt-box [class*="chip"] button', - ), + document.querySelectorAll(COMPOSER_CHIP_BUTTON_SELECTOR), ).filter((el): el is HTMLElement => { + if (!(el instanceof HTMLElement)) return false; + if (el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR)) return false; + if (isDisabledProp(el) || el.getClientRects().length === 0) return false; + if (el.closest(COMPOSER_CHIP_HOST_SELECTOR)) return true; if (!isVisibleEnabled(el)) return false; - if (el.closest("flow-image-ingredient-chip")) return true; const lbl = (el.getAttribute("aria-label") || elText(el)).trim(); - return /^remove\b|remove ingredient|remove reference|remove frame/i.test( + return /^remove\b|remove ingredient|remove reference|remove frame|remove uploaded/i.test( lbl, ); }); @@ -208,6 +307,34 @@ export async function attachIngredients(cfg: GenerationConfig): Promise } await delay(100); } + + const cleanupPage = findProjectPageInstance(); + const cleanupUx = findLiveBasePromptBox(false, findPromptBoxHost(cleanupPage)); + const remainingChips = Array.from( + document.querySelectorAll(`flow-prompt-box ${COMPOSER_CHIP_HOST_SELECTOR}`), + ).filter( + (el) => + !el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR) && + el.getClientRects().length > 0, + ); + let remainingItems = readPageItems(cleanupPage, cleanupUx); + if ( + (remainingItems && remainingItems.length > 0) || + remainingChips.length > 0 + ) { + const clearFn = + cleanupUx?.Qa?.clear ?? + cleanupPage?.Qa?.clear ?? + runtimeState.promptState?.clear; + if (typeof clearFn === "function") { + clearFn.call(cleanupUx?.Qa ?? cleanupPage?.Qa ?? runtimeState.promptState); + await delay(100); + } + remainingItems = readPageItems(cleanupPage, cleanupUx); + } + if (remainingItems && remainingItems.length > 0) { + return { ok: false, error: "stale_composer_items_not_cleared" }; + } } const scope: ParentNode = (() => { @@ -224,32 +351,6 @@ export async function attachIngredients(cfg: GenerationConfig): Promise return document; })(); - const readPageItems = ( - page: ReturnType, - ux?: ReturnType, - ): Array> | null => { - const raw = - page?.Qa?.oc?.all?.() ?? - page?.Qa?.kc?.all?.() ?? - page?.oc?.all?.() ?? - ux?.Qa?.oc?.all?.() ?? - ux?.Qa?.kc?.all?.(); - return Array.isArray(raw) ? raw : null; - }; - - if ( - ingredientTargets.length > 0 && - !onEditPage && - !(runtimeState.ngLViewMap instanceof Map) - ) { - const tipEls = Array.from( - document.querySelectorAll("[mattooltip], button[aria-label]"), - ).slice(0, 8); - await withLViewMapCapture(async () => { - await hoverProbe(tipEls, 50); - }); - } - const promptBoxEl = !onEditPage ? document.querySelector("flow-prompt-box") : null; @@ -575,14 +676,36 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ? findLiveBasePromptBox(false, findPromptBoxHost(projPage)) : null; let finalItems = !onEditPage ? readPageItems(projPage, liveUx) : null; - const ready = (): boolean => isVideoFrames - ? framesReady(finalItems, ingredientTargets) - : finalItems === null || - (finalItems.length >= ingredientTargets.length && !finalItems.some(itemNotReady)); - for (let attempt = 0; attachedSteps === ingredientTargets.length && !ready() && attempt < 25; attempt++) { + const findDisabledError = (items: unknown[] | null): string | null => { + if (!items) return null; + for (const item of items) { + const reason = itemDisabledReason(item); + if (reason) return reason; + } + return null; + }; + const ready = (): boolean => + isVideoFrames + ? framesReady(finalItems, ingredientTargets) + : finalItems === null || + (finalItems.length >= ingredientTargets.length && + !finalItems.some(itemLoading) && + !findDisabledError(finalItems)); + for ( + let attempt = 0; + attachedSteps === ingredientTargets.length && + !ready() && + !findDisabledError(finalItems) && + attempt < 25; + attempt++ + ) { await delay(100); finalItems = readPageItems(projPage, liveUx); } + const disabledCode = findDisabledError(finalItems); + if (disabledCode) { + return { ok: false, error: disabledCode }; + } if (attachedSteps < ingredientTargets.length || !ready()) { return { ok: false, error: "ingredient_attach_failed" }; } diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..4eab2a2 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -15,13 +15,163 @@ import { } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; import { runtimeState } from "./state"; -import type { GenerationConfig, NgLView } from "./types"; +import type { GenerationConfig, NgLView, PromptStateController } from "./types"; + +/** Aspect ratio label-to-enum table matching `SKb` / `_.OE` in Google Flow. */ +const SKB_ASPECT_RATIO_MAP: Readonly> = { + "8:1": "LANDSCAPE_8_1", + "4:1": "LANDSCAPE_4_1", + "21:9": "ULTRAWIDE", + "16:9": "LANDSCAPE", + "3:2": "LANDSCAPE_3_2", + "4:3": "LANDSCAPE_4_3", + "5:4": "LANDSCAPE_5_4", + "1:1": "SQUARE", + "4:5": "PORTRAIT_4_5", + "3:4": "PORTRAIT_3_4", + "2:3": "PORTRAIT_2_3", + "9:16": "PORTRAIT", + "1:4": "PORTRAIT_1_4", + "1:8": "PORTRAIT_1_8", +}; + +/** Reverse lookup of valid `SKb` aspect ratio enum values. */ +const SKB_ASPECT_ENUM_VALUES: ReadonlySet = new Set( + Object.values(SKB_ASPECT_RATIO_MAP), +); + +/** Canonical display name and family ID pair for known Google Flow models. */ +interface ModelFamilyAlias { + /** Primary label rendered in `Select model family`. */ + readonly displayName: string; + /** Family ID stored on `Qa.model` (`hg` / `ala`). */ + readonly hg: string; +} + +/** Legacy model slugs and family IDs mapped to live `Select model family` names. */ +const MODEL_FAMILY_ALIASES: Readonly> = { + veo_3_1_fast: { displayName: "Veo 3.1 Lite", hg: "veo_3_1_lite" }, + veo_3_1_lite: { displayName: "Veo 3.1 Lite", hg: "veo_3_1_lite" }, + veo_3_1: { displayName: "Veo 3.1", hg: "veo_3_1" }, + veo_3_1_quality: { displayName: "Veo 3.1", hg: "veo_3_1" }, + veo_3_fast: { displayName: "Veo 3 Fast", hg: "veo_3_fast" }, + veo_3: { displayName: "Veo 3", hg: "veo_3" }, + veo_2: { displayName: "Veo 2", hg: "veo_2" }, + veo_2_fast: { displayName: "Veo 2", hg: "veo_2" }, + veo_2_quality: { displayName: "Veo 2", hg: "veo_2" }, + gemini_omni: { displayName: "Gemini Omni", hg: "macaron_cookie" }, + macaron_cookie: { displayName: "Gemini Omni", hg: "macaron_cookie" }, + nano_banana: { displayName: "Nano Banana", hg: "nano_banana" }, + nano_banana_2: { displayName: "Nano Banana 2", hg: "nano_banana_2" }, + nano_banana_pro: { displayName: "Nano Banana Pro", hg: "nano_banana_pro" }, + imagen_3: { displayName: "Imagen 3", hg: "imagen_3" }, + imagen_4: { displayName: "Imagen 4", hg: "imagen_4" }, +}; /** Escapes regular expression metacharacters in literal labels. */ function escapeRegex(s: unknown): string { return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } +/** Normalizes a model string into an underscore-separated lookup key. */ +function modelAliasKey(raw: string): string { + return raw + .trim() + .split(/[\s\-_.]+/) + .filter(Boolean) + .map((part) => part.toLowerCase()) + .join("_"); +} + +/** Builds anchored `^...$` matchers for model `displayName` and `hg` values. */ +function buildModelMatchers(rawModel: string): { + displayName: string; + expectedHg: string | null; + labelRe: RegExp; + hgRe: RegExp; +} { + const trimmed = rawModel.trim(); + const alias = MODEL_FAMILY_ALIASES[modelAliasKey(trimmed)]; + const displayName = alias ? alias.displayName : trimmed; + const flexLabel = escapeRegex(displayName).replace(/[-_\s]+/g, "[\\s\\-_]*"); + const labelRe = new RegExp(`^${flexLabel}$`, "i"); + const hgPattern = alias + ? `^${escapeRegex(alias.hg)}$` + : `^(?:${flexLabel}|${escapeRegex(modelAliasKey(trimmed))})$`; + return { + displayName, + expectedHg: alias ? alias.hg : null, + labelRe, + hgRe: new RegExp(hgPattern, "i"), + }; +} + +/** Resolves a requested aspect ratio string against `SKb` (`SKB_ASPECT_RATIO_MAP`). */ +function resolveExpectedAspect(rawAspect: string): { + enumValue: string | null; + toggleRe: RegExp; +} { + const trimmed = rawAspect.trim(); + const direct = SKB_ASPECT_RATIO_MAP[trimmed]; + if (direct) { + const toggleRe = + trimmed === "16:9" + ? /^(?:16:9|landscape)$/i + : trimmed === "9:16" + ? /^(?:9:16|portrait)$/i + : trimmed === "1:1" + ? /^(?:1:1|square)$/i + : new RegExp(`^(?:${escapeRegex(trimmed)}|${escapeRegex(direct)})$`, "i"); + return { enumValue: direct, toggleRe }; + } + const upper = trimmed.toUpperCase(); + if (upper === "LANDSCAPE") { + return { enumValue: "LANDSCAPE", toggleRe: /^(?:16:9|landscape)$/i }; + } + if (upper === "PORTRAIT") { + return { enumValue: "PORTRAIT", toggleRe: /^(?:9:16|portrait)$/i }; + } + if (upper === "SQUARE") { + return { enumValue: "SQUARE", toggleRe: /^(?:1:1|square)$/i }; + } + if (SKB_ASPECT_ENUM_VALUES.has(upper)) { + const pair = Object.entries(SKB_ASPECT_RATIO_MAP).find(([, v]) => v === upper); + const lbl = pair ? pair[0] : trimmed; + return { + enumValue: upper, + toggleRe: new RegExp(`^(?:${escapeRegex(lbl)}|${escapeRegex(upper)})$`, "i"), + }; + } + return { + enumValue: null, + toggleRe: new RegExp(`^${escapeRegex(trimmed)}$`, "i"), + }; +} + +/** Resolves the active `PromptStateController` (`Qa`) from the project composer. */ +function resolvePromptState(): PromptStateController | null { + const projPage = findProjectPageInstance(); + const liveUx = findLiveBasePromptBox(false, findPromptBoxHost(projPage)); + return liveUx?.Qa ?? projPage?.Qa ?? runtimeState.promptState ?? null; +} + +/** Reads the model picker option array from `Qa.model.Wqa()` or `Qa.model.Yqa()`. */ +function readModelOptions(qa: PromptStateController | null): ReadonlyArray<{ + readonly hg?: string; + readonly displayName?: string; + readonly isDisabled?: boolean; +}> | null { + const opts = qa?.model?.Wqa?.() ?? qa?.model?.Yqa?.(); + return Array.isArray(opts) ? opts : null; +} + +/** Reads the active model family identifier from `Qa.model.ala()` or `Qa.model.cla()`. */ +function readActiveModelId(qa: PromptStateController | null): string { + const id = + qa?.model?.ala?.() ?? qa?.model?.cla?.() ?? qa?.model?.family?.()?.id ?? ""; + return typeof id === "string" ? id.trim() : ""; +} + /** Walks up from `tb` to locate the enclosing composer panel container. */ function findComposerRoot(tb: Element | null): ParentNode { if (!tb) return document; @@ -53,17 +203,49 @@ function clickByText( const interactiveSel = 'button, [role="tab"], [role="option"], [role="menuitem"], [role="radio"]'; const isExcludedButton = (el: Element): boolean => { + if (el.closest("flow-menu-item-actions")) return true; const aria = (el.getAttribute("aria-label") || "").trim(); return aria === "Select model family" || aria === "Settings trigger"; }; + const isDisabledMenuItem = (menuItem: Element): boolean => { + const attr = menuItem.getAttribute("disabled"); + if (attr === "true" || (attr !== null && attr !== "false")) return true; + if (menuItem.getAttribute("aria-disabled") === "true") return true; + const innerBtn = menuItem.querySelector( + ".flow-internal-menu-item, .flow-internal-menu-item-link, button", + ); + return Boolean(innerBtn && !isVisibleEnabled(innerBtn)); + }; for (const root of searchRoots) { const els = Array.from( root.querySelectorAll( - 'button, [role="tab"], [role="option"], [role="menuitem"], [role="radio"], .model-select-option', + 'flow-menu-item, .model-select-option, button, [role="tab"], [role="option"], [role="menuitem"], [role="menuitemradio"], [role="radio"]', ), ); const hit = els.find((el): el is HTMLElement => { if (!isVisibleEnabled(el) || isExcludedButton(el)) return false; + const menuItem = el.matches("flow-menu-item, .model-select-option") + ? el + : el.closest("flow-menu-item, .model-select-option"); + if (menuItem) { + if (isDisabledMenuItem(menuItem)) return false; + const labelNode = menuItem.querySelector(".label"); + const primaryLabel = ( + (labelNode ? elText(labelNode) : "") || + menuItem.getAttribute("label") || + "" + ).trim(); + const menuAria = ( + el.getAttribute("aria-label") || + menuItem.getAttribute("aria-label") || + "" + ).trim(); + if (primaryLabel) { + return ( + regex.test(primaryLabel) || (menuAria.length > 0 && regex.test(menuAria)) + ); + } + } if (!el.matches(interactiveSel)) { const inner = el.querySelector(interactiveSel); if (inner && (!isVisibleEnabled(inner) || isExcludedButton(inner))) { @@ -71,6 +253,8 @@ function clickByText( } } const aria = (el.getAttribute("aria-label") || "").trim(); + const toggleNode = el.querySelector(".toggle-text"); + const toggleLabel = toggleNode ? elText(toggleNode).trim() : ""; const raw = elText(el); const tail = raw @@ -78,7 +262,12 @@ function clickByText( .map((s) => s.trim()) .filter(Boolean) .pop() || ""; - return regex.test(aria) || regex.test(raw) || regex.test(tail); + return ( + (toggleLabel.length > 0 && regex.test(toggleLabel)) || + (aria.length > 0 && regex.test(aria)) || + regex.test(raw) || + regex.test(tail) + ); }); if (hit) { const targetBtn = hit.matches(interactiveSel) @@ -256,7 +445,15 @@ export async function setupGeneration( "flow-prompt-box-settings, .settings-content-overlay", ) || scope; const mode = String(cfg.mode || "video").toLowerCase(); - if (mode === "image" || mode === "character" || mode === "scene") { + const wantImageMode = + mode === "image" || mode === "character" || mode === "scene"; + const effectiveVideoType = !wantImageMode + ? String(cfg.video_type || "ingredients").trim().toLowerCase() + : ""; + const wantVideoIngredients = + !wantImageMode && !/^(?:frames?|video[\s_-]*frames?)$/i.test(effectiveVideoType); + + if (wantImageMode) { clickInsideGroup( "Mode", /\b(image|images|create image)\b/i, @@ -272,36 +469,43 @@ export async function setupGeneration( await delay(140); try { - if (cfg.video_type && mode === "video") { - const vt = String(cfg.video_type).trim(); - const vtRe = /ingredient/i.test(vt) - ? /\bingredients?\b/i - : /\bframes?\b/i; - if (clickInsideGroup("Video type", vtRe, settingsScope())) { - await delay(120); + if (!wantImageMode) { + const qaMode = String(resolvePromptState()?.config?.mode?.() || ""); + const needsSwitch = wantVideoIngredients + ? !qaMode || qaMode === "VIDEO_FRAMES" || Boolean(cfg.video_type) + : qaMode !== "VIDEO_FRAMES"; + if (needsSwitch) { + const vtRe = wantVideoIngredients + ? /^(?:ingredients?|video[\s_-]*ingredients?)$/i + : /^(?:frames?|video[\s_-]*frames?)$/i; + if (clickInsideGroup("Video type", vtRe, settingsScope())) { + await delay(120); + } } } } catch { // Optional video_type control may not be rendered. } - try { - if (cfg.aspect) { - const a = String(cfg.aspect).trim(); - const aspectRe = - a === "16:9" - ? /\b16:9\b|\blandscape\b/i - : a === "9:16" - ? /\b9:16\b|\bportrait\b/i - : a === "1:1" - ? /\b1:1\b|\bsquare\b/i - : new RegExp(escapeRegex(a), "i"); - if (clickInsideGroup("Aspect ratio", aspectRe, settingsScope())) { + const rawAspect = cfg.aspect != null ? String(cfg.aspect).trim() : ""; + const aspectSpec = rawAspect ? resolveExpectedAspect(rawAspect) : null; + if (aspectSpec) { + if ( + !aspectSpec.enumValue || + (!wantImageMode && aspectSpec.enumValue === "SQUARE") + ) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_aspect_ratio" }; + } + try { + if (clickInsideGroup("Aspect ratio", aspectSpec.toggleRe, settingsScope())) { await delay(120); } + } catch { + // Optional aspect ratio control may be unavailable. } - } catch { - // Optional aspect ratio control may be unavailable. } try { @@ -354,13 +558,23 @@ export async function setupGeneration( // Optional resolution control may be unavailable. } + const rawModel = cfg.model != null ? String(cfg.model).trim() : ""; + const modelSpec = rawModel ? buildModelMatchers(rawModel) : null; + let hadModelPickerItems = false; + let clickedModelItem = false; try { - if (cfg.model) { - const flexPattern = escapeRegex(String(cfg.model).trim()).replace( - /[-_\s]+/g, - "[\\s\\-_]*", - ); - const modelRe = new RegExp(flexPattern, "i"); + if (modelSpec) { + const preQa = resolvePromptState(); + const preOptions = readModelOptions(preQa); + const matchedOption = preOptions?.find((opt) => { + const disp = String(opt?.displayName || "").trim(); + const hg = String(opt?.hg || "").trim(); + return modelSpec.labelRe.test(disp) || modelSpec.hgRe.test(hg); + }); + const exactDisplay = String(matchedOption?.displayName || "").trim(); + const menuRe = exactDisplay + ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") + : modelSpec.labelRe; const familyBtn = document.querySelector( 'button[aria-label="Select model family"]', ); @@ -381,11 +595,23 @@ export async function setupGeneration( if (pickerPane) break; } if (pickerPane) { - clickByText(modelRe, pickerPane, false); + hadModelPickerItems = + pickerPane.querySelectorAll( + 'flow-menu-item, .model-select-option, [role="menuitem"], [role="option"]', + ).length > 0; + clickedModelItem = + clickByText(menuRe, pickerPane, false) || + (menuRe !== modelSpec.labelRe && + clickByText(modelSpec.labelRe, pickerPane, false)) || + clickByText(modelSpec.hgRe, pickerPane, false); } await delay(120); await closeModelMenu(); - } else if (clickByText(modelRe, settingsScope(), false)) { + } else if ( + clickByText(menuRe, settingsScope(), false) || + clickByText(modelSpec.hgRe, settingsScope(), false) + ) { + clickedModelItem = true; await delay(120); } } @@ -395,7 +621,7 @@ export async function setupGeneration( try { // Some models show the resolution toggle and the length slider only after the model changes. - if (mode === "video" && cfg.model) { + if (!wantImageMode && modelSpec) { if (cfg.resolution) { const rRe = new RegExp(escapeRegex(String(cfg.resolution).trim()), "i"); if (clickInsideGroup("Video resolution", rRe, settingsScope())) { @@ -414,29 +640,53 @@ export async function setupGeneration( } try { - const liveUx = findLiveBasePromptBox( - false, - findPromptBoxHost(findProjectPageInstance()), - ); - const curMode = String(liveUx?.Qa?.config?.mode?.() || ""); - const wantImageMode = - mode === "image" || mode === "character" || mode === "scene"; + let qa = resolvePromptState(); + let curMode = String(qa?.config?.mode?.() || ""); if (wantImageMode && curMode && curMode !== "IMAGE") { clickInsideGroup("Mode", /\bimage\b/i, settingsScope()); await delay(140); - } else if (!wantImageMode && curMode && !curMode.startsWith("VIDEO")) { - clickInsideGroup("Mode", /\bvideo\b/i, settingsScope()); - await delay(140); - if (cfg.video_type) { - const vt = String(cfg.video_type).trim(); - const vtRe = /ingredient/i.test(vt) - ? /\bingredients?\b/i - : /\bframes?\b/i; - if (clickInsideGroup("Video type", vtRe, settingsScope())) { + } else if (!wantImageMode) { + if (curMode && !curMode.startsWith("VIDEO")) { + clickInsideGroup("Mode", /\bvideo\b/i, settingsScope()); + await delay(140); + qa = resolvePromptState(); + curMode = String(qa?.config?.mode?.() || ""); + } + if (wantVideoIngredients && curMode === "VIDEO_FRAMES") { + if ( + clickInsideGroup( + "Video type", + /^(?:ingredients?|video[\s_-]*ingredients?)$/i, + settingsScope(), + ) + ) { await delay(120); } + } else if (!wantVideoIngredients && curMode && curMode !== "VIDEO_FRAMES") { + if ( + clickInsideGroup( + "Video type", + /^(?:frames?|video[\s_-]*frames?)$/i, + settingsScope(), + ) + ) { + await delay(120); + } + } + } + if ( + aspectSpec?.enumValue && + typeof qa?.config?.aspectRatio === "function" && + String(qa.config.aspectRatio() || "") !== aspectSpec.enumValue + ) { + if (clickInsideGroup("Aspect ratio", aspectSpec.toggleRe, settingsScope())) { + await delay(120); } } + const liveUx = findLiveBasePromptBox( + false, + findPromptBoxHost(findProjectPageInstance()), + ); if ( cfg.count != null && typeof liveUx?.Qa?.config?.outputCount === "function" && @@ -482,6 +732,61 @@ export async function setupGeneration( // Ignore non-fatal post-settings sync check. } + const verifiedQa = resolvePromptState(); + if (aspectSpec?.enumValue && typeof verifiedQa?.config?.aspectRatio === "function") { + const actualAspect = String(verifiedQa.config.aspectRatio() || "").trim(); + if (actualAspect && actualAspect !== aspectSpec.enumValue) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_aspect_ratio" }; + } + } + + if (modelSpec) { + const postOptions = readModelOptions(verifiedQa); + const activeId = readActiveModelId(verifiedQa); + const activeFamilyName = String( + verifiedQa?.model?.family?.()?.displayName || "", + ).trim(); + let modelVerified = true; + if (postOptions && postOptions.length > 0) { + const matchedOpt = postOptions.find((opt) => { + const disp = String(opt?.displayName || "").trim(); + const hg = String(opt?.hg || "").trim(); + return modelSpec.labelRe.test(disp) || modelSpec.hgRe.test(hg); + }); + if (!matchedOpt || matchedOpt.isDisabled === true) { + modelVerified = false; + } else if (activeId) { + const targetHg = String(matchedOpt.hg || "").trim(); + if ( + targetHg + ? activeId !== targetHg + : !modelSpec.hgRe.test(activeId) && !modelSpec.labelRe.test(activeId) + ) { + modelVerified = false; + } + } + } else if (activeId) { + if ( + !modelSpec.hgRe.test(activeId) && + !modelSpec.labelRe.test(activeId) && + !(activeFamilyName && modelSpec.labelRe.test(activeFamilyName)) + ) { + modelVerified = false; + } + } else if (hadModelPickerItems && !clickedModelItem) { + modelVerified = false; + } + if (!modelVerified) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_model" }; + } + } + if (settingsOpen()) { await closeSettingsAndMenus(); } diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..17e44b6 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -4,11 +4,50 @@ // Locate the enabled Flow generation submit button and compute its viewport click point. import { readAngularTooltip, readOwn, resolveLView } from "./angular"; -import { findComposerWarning } from "./composer"; +import { + findComposerWarning, + findLiveBasePromptBox, + findProjectPageInstance, + findPromptBoxHost, +} from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; import { runtimeState } from "./state"; import type { NgLView } from "./types"; +/** Inspects `Qa.oc.all()` for loading or `Rp`-disabled attachments before submit. */ +function inspectPromptAttachments(onEditPage: boolean): { + loading: boolean; + disabledReason: string | null; +} { + if (onEditPage) { + return { loading: false, disabledReason: null }; + } + const projPage = findProjectPageInstance(); + const liveUx = findLiveBasePromptBox(false, findPromptBoxHost(projPage)); + const raw = + projPage?.Qa?.oc?.all?.() ?? + projPage?.Qa?.kc?.all?.() ?? + projPage?.oc?.all?.() ?? + liveUx?.Qa?.oc?.all?.() ?? + liveUx?.Qa?.kc?.all?.() ?? + runtimeState.promptState?.oc?.all?.() ?? + runtimeState.promptState?.kc?.all?.(); + if (!Array.isArray(raw)) { + return { loading: false, disabledReason: null }; + } + let loading = false; + for (const item of raw) { + const rp = readOwn(item, "Rp"); + if (typeof rp === "string" && rp.trim().length > 0) { + return { loading: false, disabledReason: rp.trim() }; + } + if (readOwn(item, "isLoading") === true) { + loading = true; + } + } + return { loading, disabledReason: null }; +} + /** Extracts a disabled submit validator message from a component or controller candidate. */ function readCandidateValidatorReason(cand: unknown): string { if (!cand || typeof cand !== "object" || cand instanceof Node) return ""; @@ -24,17 +63,23 @@ function readCandidateValidatorReason(cand: unknown): string { if (msg) return msg; } const qa = readOwn(cand, "Qa"); - const qaFf = readOwn(qa, "Ff") as { N7a?: () => string } | undefined; + const qaFf = readOwn(qa, "Ff") as + | { N7a?: () => string; S7a?: () => string } + | undefined; const qaLf = readOwn(qa, "lf") as { jYa?: () => string } | undefined; - const qaMsg = String(qaFf?.N7a?.() || qaLf?.jYa?.() || "").trim(); + const qaMsg = String( + qaFf?.N7a?.() || qaFf?.S7a?.() || qaLf?.jYa?.() || "", + ).trim(); if (qaMsg) return qaMsg; const applyFn = readOwn(cand, "Gp") ?? readOwn(cand, "Wn"); if (typeof applyFn === "function") { - const directFf = readOwn(cand, "Ff") as { N7a?: () => string } | undefined; + const directFf = readOwn(cand, "Ff") as + | { N7a?: () => string; S7a?: () => string } + | undefined; const directLf = readOwn(cand, "lf") as { jYa?: () => string } | undefined; const directMsg = String( - directFf?.N7a?.() || directLf?.jYa?.() || "", + directFf?.N7a?.() || directFf?.S7a?.() || directLf?.jYa?.() || "", ).trim(); if (directMsg) return directMsg; } @@ -167,19 +212,43 @@ export async function submitGeneration(): Promise { }; for (let i = 0; i < 120; i += 1) { + const attachmentState = inspectPromptAttachments(onEditPage); + if (attachmentState.disabledReason) { + return { + ok: false, + error: attachmentState.disabledReason, + detail: "ingredient_disabled", + }; + } const exact = findStartButton(); if (isVisibleEnabled(exact)) { + if (attachmentState.loading) { + await delay(100); + continue; + } return await prepareTarget(exact, "aria_start_generation"); } const warning = checkWarning(); if (warning) return warning; - if (exact && isVisible(exact)) { + if ((exact && isVisible(exact)) || attachmentState.loading) { await delay(100); } else { break; } } + const attachmentAfter = inspectPromptAttachments(onEditPage); + if (attachmentAfter.disabledReason) { + return { + ok: false, + error: attachmentAfter.disabledReason, + detail: "ingredient_disabled", + }; + } + if (attachmentAfter.loading) { + return { ok: false, error: "ingredient_loading_timeout" }; + } + const warningAfter = checkWarning(); if (warningAfter) return warningAfter; diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..f1e5f1b 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -322,12 +322,36 @@ export interface PromptStateController { /** Validator status object in earlier builds. */ lf?: { isValid?: () => boolean; jYa?: () => string }; /** Validator status object in build 20261120.00. */ - Ff?: { isValid?: () => boolean; N7a?: () => string }; - /** Mode, output count, and model config signals. */ - config?: { - mode?: () => string; - outputCount?: () => number; + Ff?: { isValid?: () => boolean; N7a?: () => string; S7a?: () => string }; + /** Mode, output count, and aspect ratio config signals. */ + readonly config?: { + readonly mode?: () => string; + readonly outputCount?: () => number; + readonly aspectRatio?: () => string; }; + /** Active model family and picker option signals. */ + readonly model?: { + /** Active model family ID signal in build 20261120.00. */ + readonly ala?: () => string | undefined; + /** Active model family ID signal in refreshed build 20261120.00 chunks. */ + readonly cla?: () => string | undefined; + /** Active model family descriptor signal. */ + readonly family?: () => { readonly id?: string; readonly displayName?: string } | undefined; + /** Model picker options signal in build 20261120.00. */ + readonly Wqa?: () => ReadonlyArray<{ + readonly hg?: string; + readonly displayName?: string; + readonly isDisabled?: boolean; + }>; + /** Model picker options signal in refreshed build 20261120.00 chunks. */ + readonly Yqa?: () => ReadonlyArray<{ + readonly hg?: string; + readonly displayName?: string; + readonly isDisabled?: boolean; + }>; + }; + /** Clears prompt segments and attached composer ingredients. */ + readonly clear?: () => void; /** Attached item signal container in legacy builds. */ kc?: { all?: () => Array> }; /** Attached item signal container in build 20261120.00 and later. */ From 4cf9227dc50ad46c9b23e969631fd18ebe79b549 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:15:53 +0000 Subject: [PATCH 2/3] fix: preserve explicit model families and verify composer state - Separate default model candidates from explicit model normalization - Preserve explicit Veo 3.1 Fast and reject unavailable model families - Require readable aspect ratio and model state before submission - Update flow_generate model documentation for legacy and live builds --- docs/en/tools-reference.md | 2 +- docs/ja/tools-reference.md | 2 +- docs/zh-CN/tools-reference.md | 2 +- src/generation.rs | 75 ++++-- ts/generation_state.ts | 455 ++++++++++++++++++++++++++++++++++ ts/setup_generation.ts | 382 ++++++++++------------------ ts/submit_generation.ts | 17 +- ts/types.ts | 16 +- 8 files changed, 659 insertions(+), 292 deletions(-) create mode 100644 ts/generation_state.ts diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index ad96007..03ff5d2 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -200,7 +200,7 @@ Queue a Veo video or Imagen image generation job on `JobQueue`. Returns a `JobVi | :--- | :--- | :--- | :--- | | `prompt` | `string` | Yes | Text prompt that `flow-mcp` sends to Google Flow. | | `mode` | `string` | No | `"video"` (default) or `"image"`. | -| `model` | `string` | No | Model override. Defaults to `"Veo 3.1 Lite"` (`video`) or `"Nano Banana 2"` (`image`), and maps legacy slugs such as `"veo-3.1-fast"`. | +| `model` | `string` | No | Model override. Defaults to `"Veo 3.1 Lite"` (`"Veo 3.1 Fast"` on legacy builds) for `video` or `"Nano Banana 2"` for `image`. | | `aspect` | `string` | No | Aspect ratio: `"16:9"` (default), `"9:16"`, or `"1:1"` (`image` mode only). | | `count` | `integer` | No | Output batch count in `1..=4`. Default `2`. | | `frames` | `string[]` | No | Local reference or keyframe image paths to upload before submission. | diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index a613538..773c259 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -200,7 +200,7 @@ Google Flow でキャラクターボイスピッカーを開き、リスト全 | :--- | :--- | :--- | :--- | | `prompt` | `string` | はい | `flow-mcp` が Google Flow へ送信するテキストプロンプト。 | | `mode` | `string` | いいえ | `"video"`(既定)または `"image"`。 | -| `model` | `string` | いいえ | モデル上書き。既定は `"Veo 3.1 Lite"`(`video`)または `"Nano Banana 2"`(`image`)で、`"veo-3.1-fast"` などの旧スラッグも対応します。 | +| `model` | `string` | いいえ | モデル上書き。既定は `video` で `"Veo 3.1 Lite"`(旧ビルドでは `"Veo 3.1 Fast"`)、`image` で `"Nano Banana 2"` です。 | | `aspect` | `string` | いいえ | アスペクト比:`"16:9"`(既定)、`"9:16"`、または `"1:1"`(`image` モードのみ)。 | | `count` | `integer` | いいえ | 出力バッチ数(`1..=4`)。既定は `2`。 | | `frames` | `string[]` | いいえ | 送信前にアップロードするローカル参照またはキーフレーム画像パス。 | diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index fbdc2d4..c322ae8 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -200,7 +200,7 @@ flow-mcp [OPTIONS] | :--- | :--- | :--- | :--- | | `prompt` | `string` | 是 | `flow-mcp` 发送给 Google Flow 的文本提示词。 | | `mode` | `string` | 否 | `"video"`(默认)或 `"image"`。 | -| `model` | `string` | 否 | 模型覆盖。默认为 `"Veo 3.1 Lite"`(`video`)或 `"Nano Banana 2"`(`image`),并映射 `"veo-3.1-fast"` 等旧标识。 | +| `model` | `string` | 否 | 模型覆盖。`video` 默认为 `"Veo 3.1 Lite"`(旧版构建为 `"Veo 3.1 Fast"`),`image` 默认为 `"Nano Banana 2"`。 | | `aspect` | `string` | 否 | 画面比例:`"16:9"`(默认)、`"9:16"` 或 `"1:1"`(仅限 `image` 模式)。 | | `count` | `integer` | 否 | 输出批次数量,范围 `1..=4`。默认 `2`。 | | `frames` | `string[]` | 否 | 提交前上传的本地参考图像或关键帧路径。 | diff --git a/src/generation.rs b/src/generation.rs index b9e4b4b..42fdba0 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -34,7 +34,7 @@ pub(crate) struct GenerateParams { pub(crate) prompt: String, /// Generation mode: "video" (default) or "image". pub(crate) mode: Option, - /// Model name override (defaults to "Veo 3.1 Lite" for video or "Nano Banana 2" for image; maps legacy slugs such as "veo-3.1-fast"). + /// Model family override (defaults to "Veo 3.1 Lite", or "Veo 3.1 Fast" on legacy builds, for video and "Nano Banana 2" for image). pub(crate) model: Option, /// Output aspect ratio: "16:9" (default), "9:16", or "1:1" (image mode only). pub(crate) aspect: Option, @@ -93,23 +93,30 @@ struct NormalizedControls { mode: &'static str, /// Canonical aspect ratio label. aspect: String, - /// Live `Select model family` display name or caller override. - model: String, + /// Explicit model family display name or caller override when specified. + model: Option, + /// Ordered default model family candidates when `model` is omitted. + default_models: &'static [&'static str], /// Normalized video mode (`Some("ingredients")` or `Some("frames")`) for video runs. video_type: Option<&'static str>, /// Clamped batch output count in `1..=4`. count: u32, } -/// Maps legacy model slugs and defaults to live `Select model family` display names. -fn normalize_model_name(raw: Option<&str>, mode: &str) -> String { +/// Returns ordered default `Select model family` names for `mode` when `model` is omitted. +fn default_model_families(mode: &str) -> &'static [&'static str] { + if mode == "image" { + &["Nano Banana 2"] + } else { + &["Veo 3.1 Lite", "Veo 3.1 Fast"] + } +} + +/// Normalizes an explicit model identifier to its canonical family name without cross-family substitution. +fn normalize_explicit_model(raw: Option<&str>) -> Option { let trimmed = raw.map(str::trim).unwrap_or(""); if trimmed.is_empty() { - return if mode == "image" { - "Nano Banana 2".to_string() - } else { - "Veo 3.1 Lite".to_string() - }; + return None; } let key = trimmed .split(|ch: char| ch.is_whitespace() || matches!(ch, '-' | '_' | '.')) @@ -117,20 +124,25 @@ fn normalize_model_name(raw: Option<&str>, mode: &str) -> String { .map(str::to_ascii_lowercase) .collect::>() .join("_"); - match key.as_str() { - "veo_3_1_fast" | "veo_3_1_lite" => "Veo 3.1 Lite".to_string(), - "veo_3_1" | "veo_3_1_quality" => "Veo 3.1".to_string(), - "veo_3_fast" => "Veo 3 Fast".to_string(), - "veo_3" => "Veo 3".to_string(), - "veo_2" | "veo_2_fast" | "veo_2_quality" => "Veo 2".to_string(), - "gemini_omni" | "macaron_cookie" => "Gemini Omni".to_string(), - "nano_banana" => "Nano Banana".to_string(), - "nano_banana_2" => "Nano Banana 2".to_string(), - "nano_banana_pro" => "Nano Banana Pro".to_string(), - "imagen_3" => "Imagen 3".to_string(), - "imagen_4" => "Imagen 4".to_string(), - _ => trimmed.to_string(), - } + let canonical = match key.as_str() { + "veo_3_1_fast" => "Veo 3.1 Fast", + "veo_3_1_lite" => "Veo 3.1 Lite", + "veo_3_1" => "Veo 3.1", + "veo_3_1_quality" => "Veo 3.1 Quality", + "veo_3_fast" => "Veo 3 Fast", + "veo_3" => "Veo 3", + "veo_2" => "Veo 2", + "veo_2_fast" => "Veo 2 Fast", + "veo_2_quality" => "Veo 2 Quality", + "gemini_omni" | "macaron_cookie" => "Gemini Omni", + "nano_banana" => "Nano Banana", + "nano_banana_2" => "Nano Banana 2", + "nano_banana_pro" => "Nano Banana Pro", + "imagen_3" => "Imagen 3", + "imagen_4" => "Imagen 4", + _ => return Some(trimmed.to_string()), + }; + Some(canonical.to_string()) } /// Normalizes generation parameters and rejects invalid video aspect, character, and frame combinations. @@ -208,7 +220,8 @@ fn resolve_generation_controls(scene: &SceneParams) -> Result> = { + "8:1": "LANDSCAPE_8_1", + "4:1": "LANDSCAPE_4_1", + "21:9": "ULTRAWIDE", + "16:9": "LANDSCAPE", + "3:2": "LANDSCAPE_3_2", + "4:3": "LANDSCAPE_4_3", + "5:4": "LANDSCAPE_5_4", + "1:1": "SQUARE", + "4:5": "PORTRAIT_4_5", + "3:4": "PORTRAIT_3_4", + "2:3": "PORTRAIT_2_3", + "9:16": "PORTRAIT", + "1:4": "PORTRAIT_1_4", + "1:8": "PORTRAIT_1_8", +}; + +/** Reverse lookup of valid `SKb` aspect ratio enum values. */ +const SKB_ASPECT_ENUM_VALUES: ReadonlySet = new Set( + Object.values(SKB_ASPECT_RATIO_MAP), +); + +/** Canonical display name and family ID pair for known Google Flow models. */ +interface ModelFamilyAlias { + /** Primary label rendered in `Select model family`. */ + readonly displayName: string; + /** Family ID stored on `Qa.model` (`hg` / `ala` / `cla`). */ + readonly hg: string; +} + +/** Known model slugs and family IDs mapped to their canonical display name and `hg` ID. */ +const MODEL_FAMILY_ALIASES: Readonly> = { + veo_3_1_fast: { displayName: "Veo 3.1 Fast", hg: "veo_3_1_fast" }, + veo_3_1_lite: { displayName: "Veo 3.1 Lite", hg: "veo_3_1_lite" }, + veo_3_1: { displayName: "Veo 3.1", hg: "veo_3_1" }, + veo_3_1_quality: { displayName: "Veo 3.1 Quality", hg: "veo_3_1_quality" }, + veo_3_fast: { displayName: "Veo 3 Fast", hg: "veo_3_fast" }, + veo_3: { displayName: "Veo 3", hg: "veo_3" }, + veo_2: { displayName: "Veo 2", hg: "veo_2" }, + veo_2_fast: { displayName: "Veo 2 Fast", hg: "veo_2_fast" }, + veo_2_quality: { displayName: "Veo 2 Quality", hg: "veo_2_quality" }, + gemini_omni: { displayName: "Gemini Omni", hg: "macaron_cookie" }, + macaron_cookie: { displayName: "Gemini Omni", hg: "macaron_cookie" }, + nano_banana: { displayName: "Nano Banana", hg: "nano_banana" }, + nano_banana_2: { displayName: "Nano Banana 2", hg: "nano_banana_2" }, + nano_banana_pro: { displayName: "Nano Banana Pro", hg: "nano_banana_pro" }, + imagen_3: { displayName: "Imagen 3", hg: "imagen_3" }, + imagen_4: { displayName: "Imagen 4", hg: "imagen_4" }, +}; + +/** Anchored regular expression matchers for a single model family. */ +export interface ModelMatcher { + /** Canonical display name for UI labels. */ + readonly displayName: string; + /** Expected `hg` ID when known. */ + readonly expectedHg: string | null; + /** Anchored `^...$` pattern for primary display labels. */ + readonly labelRe: RegExp; + /** Anchored `^...$` pattern for `hg` identifiers. */ + readonly hgRe: RegExp; +} + +/** Resolved `SKb` enum and UI toggle matcher for a requested aspect ratio. */ +export interface AspectSpec { + /** Expected `SKb` enum value, or null when unrecognized. */ + readonly enumValue: string | null; + /** Anchored pattern matching the UI aspect ratio toggle button. */ + readonly toggleRe: RegExp; +} + +/** Escapes regular expression metacharacters in literal labels. */ +export function escapeRegex(s: unknown): string { + return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Normalizes a model string into an underscore-separated lookup key. */ +function modelAliasKey(raw: string): string { + return raw + .trim() + .split(/[\s\-_.]+/) + .filter(Boolean) + .map((part) => part.toLowerCase()) + .join("_"); +} + +/** Builds anchored `^...$` matchers for model `displayName` and `hg` values. */ +export function buildModelMatchers(rawModel: string): ModelMatcher { + const trimmed = rawModel.trim(); + const alias = MODEL_FAMILY_ALIASES[modelAliasKey(trimmed)]; + const displayName = alias ? alias.displayName : trimmed; + const flexLabel = escapeRegex(displayName).replace(/[-_\s]+/g, "[\\s\\-_]*"); + const labelRe = new RegExp(`^${flexLabel}$`, "i"); + const hgPattern = alias + ? `^${escapeRegex(alias.hg)}$` + : `^(?:${flexLabel}|${escapeRegex(modelAliasKey(trimmed))})$`; + return { + displayName, + expectedHg: alias ? alias.hg : null, + labelRe, + hgRe: new RegExp(hgPattern, "i"), + }; +} + +/** Resolves explicit or ordered default model matchers for `cfg`. */ +export function resolveCandidateModelSpecs( + cfg: GenerationConfig, + wantImageMode: boolean, +): ModelMatcher[] { + const rawModel = cfg.model != null ? String(cfg.model).trim() : ""; + if (rawModel) { + return [buildModelMatchers(rawModel)]; + } + const rawDefaults = Array.isArray(cfg.default_models) + ? cfg.default_models + .map((m) => String(m || "").trim()) + .filter((m) => m.length > 0) + : []; + const defaults = + rawDefaults.length > 0 + ? rawDefaults + : wantImageMode + ? ["Nano Banana 2"] + : ["Veo 3.1 Lite", "Veo 3.1 Fast"]; + return defaults.map((m) => buildModelMatchers(m)); +} + +/** Resolves a requested aspect ratio string against `SKb` (`SKB_ASPECT_RATIO_MAP`). */ +export function resolveExpectedAspect(rawAspect: string): AspectSpec { + const trimmed = rawAspect.trim(); + const direct = SKB_ASPECT_RATIO_MAP[trimmed]; + if (direct) { + const toggleRe = + trimmed === "16:9" + ? /^(?:16:9|landscape)$/i + : trimmed === "9:16" + ? /^(?:9:16|portrait)$/i + : trimmed === "1:1" + ? /^(?:1:1|square)$/i + : new RegExp(`^(?:${escapeRegex(trimmed)}|${escapeRegex(direct)})$`, "i"); + return { enumValue: direct, toggleRe }; + } + const upper = trimmed.toUpperCase(); + if (upper === "LANDSCAPE") { + return { enumValue: "LANDSCAPE", toggleRe: /^(?:16:9|landscape)$/i }; + } + if (upper === "PORTRAIT") { + return { enumValue: "PORTRAIT", toggleRe: /^(?:9:16|portrait)$/i }; + } + if (upper === "SQUARE") { + return { enumValue: "SQUARE", toggleRe: /^(?:1:1|square)$/i }; + } + if (SKB_ASPECT_ENUM_VALUES.has(upper)) { + const pair = Object.entries(SKB_ASPECT_RATIO_MAP).find(([, v]) => v === upper); + const lbl = pair ? pair[0] : trimmed; + return { + enumValue: upper, + toggleRe: new RegExp(`^(?:${escapeRegex(lbl)}|${escapeRegex(upper)})$`, "i"), + }; + } + return { + enumValue: null, + toggleRe: new RegExp(`^${escapeRegex(trimmed)}$`, "i"), + }; +} + +/** Resolves the live `PromptStateController` (`Qa`) from connected project composer views. */ +export function resolvePromptState(): PromptStateController | null { + const projPage = findProjectPageInstance(); + const liveUx = findLiveBasePromptBox(false, findPromptBoxHost(projPage)); + if (liveUx?.Qa) { + return liveUx.Qa; + } + if (projPage?.Qa) { + return projPage.Qa; + } + const agentSel = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + const isPromptState = (cand: unknown): cand is PromptStateController => { + if (!cand || typeof cand !== "object" || cand instanceof Node) return false; + const obj = cand as Partial; + return Boolean( + obj.config || + obj.model || + typeof obj.Gp === "function" || + typeof obj.Wn === "function", + ); + }; + const scanLv = (lv: unknown): PromptStateController | null => { + if (!Array.isArray(lv)) return null; + for (const cand of lv) { + if (!cand || typeof cand !== "object" || cand instanceof Node) continue; + const qaProp = (cand as { Qa?: unknown }).Qa; + if (isPromptState(qaProp)) return qaProp; + if (isPromptState(cand)) return cand; + } + return null; + }; + const seeds = [ + document.querySelector("flow-prompt-box flow-base-prompt-box"), + document.querySelector("flow-prompt-box"), + document.querySelector("flow-project-page"), + ].filter((el): el is Element => Boolean(el && !el.closest(agentSel))); + for (const seed of seeds) { + let lv: NgLView | null = resolveLView(seed); + for (let d = 0; d < 6 && Array.isArray(lv); d += 1) { + const hit = scanLv(lv); + if (hit) return hit; + lv = Array.isArray(lv[3]) ? lv[3] : Array.isArray(lv[15]) ? lv[15] : null; + } + } + if (runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if (!isLiveLView(lv)) continue; + if (lv[0] instanceof Element && lv[0].closest(agentSel)) continue; + const hit = scanLv(lv); + if (hit) return hit; + } + } + return null; +} + +/** Reads the model picker option array from `Qa.model.Wqa()` or `Qa.model.Yqa()`. */ +export function readModelOptions(qa: PromptStateController | null): ReadonlyArray<{ + readonly hg?: string; + readonly displayName?: string; + readonly isDisabled?: boolean; +}> | null { + try { + const opts = qa?.model?.Wqa?.() ?? qa?.model?.Yqa?.(); + return Array.isArray(opts) ? opts : null; + } catch { + return null; + } +} + +/** Reads the active model family identifier from `Qa.model` signals. */ +function readActiveModelId( + qa: PromptStateController | null, + wantImageMode: boolean, +): string { + const pickNonEmpty = (fn?: () => string | undefined): string => { + if (typeof fn !== "function") return ""; + try { + const val = fn.call(qa?.model); + return typeof val === "string" ? val.trim() : ""; + } catch { + return ""; + } + }; + const modeId = wantImageMode + ? pickNonEmpty(qa?.model?.imageModelFamilyId) + : pickNonEmpty(qa?.model?.videoModelFamilyId); + let familyId = ""; + try { + const fam = qa?.model?.family?.(); + const raw = fam?.id ?? fam?.hg ?? ""; + familyId = typeof raw === "string" ? raw.trim() : ""; + } catch { + familyId = ""; + } + return ( + pickNonEmpty(qa?.model?.ala) || + pickNonEmpty(qa?.model?.cla) || + modeId || + familyId + ); +} + +/** Reads the active model family display name from `Qa.model.family()` when available. */ +function readActiveModelFamilyName(qa: PromptStateController | null): string { + try { + const name = qa?.model?.family?.()?.displayName ?? ""; + return typeof name === "string" ? name.trim() : ""; + } catch { + return ""; + } +} + +/** Reads the active `SKb` aspect ratio enum string from `Qa.config.aspectRatio()`. */ +function readActiveAspectRatio(qa: PromptStateController | null): string { + try { + const fn = qa?.config?.aspectRatio; + if (typeof fn !== "function") return ""; + const val = fn.call(qa?.config); + return typeof val === "string" ? val.trim() : ""; + } catch { + return ""; + } +} + +/** Returns true only when `Qa.config.aspectRatio()` is readable, valid for `wantImageMode`, and matches `aspectSpec`. */ +export function verifyAspectState( + qa: PromptStateController | null, + wantImageMode: boolean, + aspectSpec: AspectSpec | null, +): boolean { + const actualAspect = readActiveAspectRatio(qa); + if (!actualAspect || !SKB_ASPECT_ENUM_VALUES.has(actualAspect)) { + return false; + } + if (!wantImageMode && actualAspect === "SQUARE") { + return false; + } + if (aspectSpec) { + return Boolean(aspectSpec.enumValue && actualAspect === aspectSpec.enumValue); + } + return true; +} + +/** Returns true only when `Qa.model` exposes a readable active model matching `spec`. */ +export function verifyModelSpec( + qa: PromptStateController | null, + wantImageMode: boolean, + spec: ModelMatcher, +): boolean { + if (!qa?.model) { + return false; + } + const postOptions = readModelOptions(qa); + const activeId = readActiveModelId(qa, wantImageMode); + const activeFamilyName = readActiveModelFamilyName(qa); + if (!activeId && !activeFamilyName) { + return false; + } + if (postOptions !== null) { + const matchedOpt = postOptions.find((opt) => { + const disp = String(opt?.displayName || "").trim(); + const hg = String(opt?.hg || "").trim(); + return spec.labelRe.test(disp) || spec.hgRe.test(hg); + }); + if (!matchedOpt || matchedOpt.isDisabled === true) { + return false; + } + const targetHg = String(matchedOpt.hg || "").trim(); + const targetDisp = String(matchedOpt.displayName || "").trim(); + if (targetHg) { + if (activeId) { + return activeId.toLowerCase() === targetHg.toLowerCase(); + } + return Boolean( + targetDisp && + activeFamilyName && + activeFamilyName.toLowerCase() === targetDisp.toLowerCase(), + ); + } + if (activeId) { + return spec.hgRe.test(activeId) || spec.labelRe.test(activeId); + } + return Boolean( + targetDisp + ? activeFamilyName.toLowerCase() === targetDisp.toLowerCase() + : spec.labelRe.test(activeFamilyName), + ); + } + if (typeof qa.model.family === "function") { + try { + if (!qa.model.family()) { + return false; + } + } catch { + return false; + } + } + if (activeId) { + if (spec.hgRe.test(activeId) || spec.labelRe.test(activeId)) { + return true; + } + if (activeFamilyName && spec.labelRe.test(activeFamilyName)) { + return ( + !spec.expectedHg || + activeId.toLowerCase() === spec.expectedHg.toLowerCase() + ); + } + return false; + } + return spec.labelRe.test(activeFamilyName); +} + +/** Verifies readable matching aspect ratio and model state on the project composer before submission. */ +export function verifyComposerGenerationState( + cfg?: GenerationConfig, +): { ok: true } | { ok: false; error: string } { + const qa = resolvePromptState(); + if (cfg) { + const mode = String(cfg.mode || "video").toLowerCase(); + const wantImageMode = + mode === "image" || mode === "character" || mode === "scene"; + const rawAspect = cfg.aspect != null ? String(cfg.aspect).trim() : ""; + const aspectSpec = rawAspect ? resolveExpectedAspect(rawAspect) : null; + if (aspectSpec && !verifyAspectState(qa, wantImageMode, aspectSpec)) { + return { ok: false, error: "unsupported_aspect_ratio" }; + } + const candidates = resolveCandidateModelSpecs(cfg, wantImageMode); + if (!candidates.some((spec) => verifyModelSpec(qa, wantImageMode, spec))) { + return { ok: false, error: "unsupported_model" }; + } + if (!aspectSpec && !verifyAspectState(qa, wantImageMode, null)) { + return { ok: false, error: "unsupported_aspect_ratio" }; + } + return { ok: true }; + } + let curMode = ""; + try { + curMode = String(qa?.config?.mode?.() || ""); + } catch { + curMode = ""; + } + const wantImageMode = curMode.startsWith("IMAGE"); + if (!verifyAspectState(qa, wantImageMode, null)) { + return { ok: false, error: "unsupported_aspect_ratio" }; + } + const activeId = readActiveModelId(qa, wantImageMode); + const activeName = readActiveModelFamilyName(qa); + if (!qa?.model || (!activeId && !activeName)) { + return { ok: false, error: "unsupported_model" }; + } + const opts = readModelOptions(qa); + if (opts !== null) { + const found = opts.find((opt) => { + const hg = String(opt?.hg || "").trim(); + const disp = String(opt?.displayName || "").trim(); + return ( + (activeId && hg.toLowerCase() === activeId.toLowerCase()) || + (activeName && disp.toLowerCase() === activeName.toLowerCase()) + ); + }); + if (!found || found.isDisabled === true) { + return { ok: false, error: "unsupported_model" }; + } + } else if (typeof qa.model.family === "function") { + try { + if (!qa.model.family()) { + return { ok: false, error: "unsupported_model" }; + } + } catch { + return { ok: false, error: "unsupported_model" }; + } + } + return { ok: true }; +} diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index 4eab2a2..c199264 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -14,163 +14,18 @@ import { settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { + escapeRegex, + readModelOptions, + resolveCandidateModelSpecs, + resolveExpectedAspect, + resolvePromptState, + verifyAspectState, + verifyModelSpec, +} from "./generation_state"; +import type { ModelMatcher } from "./generation_state"; import { runtimeState } from "./state"; -import type { GenerationConfig, NgLView, PromptStateController } from "./types"; - -/** Aspect ratio label-to-enum table matching `SKb` / `_.OE` in Google Flow. */ -const SKB_ASPECT_RATIO_MAP: Readonly> = { - "8:1": "LANDSCAPE_8_1", - "4:1": "LANDSCAPE_4_1", - "21:9": "ULTRAWIDE", - "16:9": "LANDSCAPE", - "3:2": "LANDSCAPE_3_2", - "4:3": "LANDSCAPE_4_3", - "5:4": "LANDSCAPE_5_4", - "1:1": "SQUARE", - "4:5": "PORTRAIT_4_5", - "3:4": "PORTRAIT_3_4", - "2:3": "PORTRAIT_2_3", - "9:16": "PORTRAIT", - "1:4": "PORTRAIT_1_4", - "1:8": "PORTRAIT_1_8", -}; - -/** Reverse lookup of valid `SKb` aspect ratio enum values. */ -const SKB_ASPECT_ENUM_VALUES: ReadonlySet = new Set( - Object.values(SKB_ASPECT_RATIO_MAP), -); - -/** Canonical display name and family ID pair for known Google Flow models. */ -interface ModelFamilyAlias { - /** Primary label rendered in `Select model family`. */ - readonly displayName: string; - /** Family ID stored on `Qa.model` (`hg` / `ala`). */ - readonly hg: string; -} - -/** Legacy model slugs and family IDs mapped to live `Select model family` names. */ -const MODEL_FAMILY_ALIASES: Readonly> = { - veo_3_1_fast: { displayName: "Veo 3.1 Lite", hg: "veo_3_1_lite" }, - veo_3_1_lite: { displayName: "Veo 3.1 Lite", hg: "veo_3_1_lite" }, - veo_3_1: { displayName: "Veo 3.1", hg: "veo_3_1" }, - veo_3_1_quality: { displayName: "Veo 3.1", hg: "veo_3_1" }, - veo_3_fast: { displayName: "Veo 3 Fast", hg: "veo_3_fast" }, - veo_3: { displayName: "Veo 3", hg: "veo_3" }, - veo_2: { displayName: "Veo 2", hg: "veo_2" }, - veo_2_fast: { displayName: "Veo 2", hg: "veo_2" }, - veo_2_quality: { displayName: "Veo 2", hg: "veo_2" }, - gemini_omni: { displayName: "Gemini Omni", hg: "macaron_cookie" }, - macaron_cookie: { displayName: "Gemini Omni", hg: "macaron_cookie" }, - nano_banana: { displayName: "Nano Banana", hg: "nano_banana" }, - nano_banana_2: { displayName: "Nano Banana 2", hg: "nano_banana_2" }, - nano_banana_pro: { displayName: "Nano Banana Pro", hg: "nano_banana_pro" }, - imagen_3: { displayName: "Imagen 3", hg: "imagen_3" }, - imagen_4: { displayName: "Imagen 4", hg: "imagen_4" }, -}; - -/** Escapes regular expression metacharacters in literal labels. */ -function escapeRegex(s: unknown): string { - return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -/** Normalizes a model string into an underscore-separated lookup key. */ -function modelAliasKey(raw: string): string { - return raw - .trim() - .split(/[\s\-_.]+/) - .filter(Boolean) - .map((part) => part.toLowerCase()) - .join("_"); -} - -/** Builds anchored `^...$` matchers for model `displayName` and `hg` values. */ -function buildModelMatchers(rawModel: string): { - displayName: string; - expectedHg: string | null; - labelRe: RegExp; - hgRe: RegExp; -} { - const trimmed = rawModel.trim(); - const alias = MODEL_FAMILY_ALIASES[modelAliasKey(trimmed)]; - const displayName = alias ? alias.displayName : trimmed; - const flexLabel = escapeRegex(displayName).replace(/[-_\s]+/g, "[\\s\\-_]*"); - const labelRe = new RegExp(`^${flexLabel}$`, "i"); - const hgPattern = alias - ? `^${escapeRegex(alias.hg)}$` - : `^(?:${flexLabel}|${escapeRegex(modelAliasKey(trimmed))})$`; - return { - displayName, - expectedHg: alias ? alias.hg : null, - labelRe, - hgRe: new RegExp(hgPattern, "i"), - }; -} - -/** Resolves a requested aspect ratio string against `SKb` (`SKB_ASPECT_RATIO_MAP`). */ -function resolveExpectedAspect(rawAspect: string): { - enumValue: string | null; - toggleRe: RegExp; -} { - const trimmed = rawAspect.trim(); - const direct = SKB_ASPECT_RATIO_MAP[trimmed]; - if (direct) { - const toggleRe = - trimmed === "16:9" - ? /^(?:16:9|landscape)$/i - : trimmed === "9:16" - ? /^(?:9:16|portrait)$/i - : trimmed === "1:1" - ? /^(?:1:1|square)$/i - : new RegExp(`^(?:${escapeRegex(trimmed)}|${escapeRegex(direct)})$`, "i"); - return { enumValue: direct, toggleRe }; - } - const upper = trimmed.toUpperCase(); - if (upper === "LANDSCAPE") { - return { enumValue: "LANDSCAPE", toggleRe: /^(?:16:9|landscape)$/i }; - } - if (upper === "PORTRAIT") { - return { enumValue: "PORTRAIT", toggleRe: /^(?:9:16|portrait)$/i }; - } - if (upper === "SQUARE") { - return { enumValue: "SQUARE", toggleRe: /^(?:1:1|square)$/i }; - } - if (SKB_ASPECT_ENUM_VALUES.has(upper)) { - const pair = Object.entries(SKB_ASPECT_RATIO_MAP).find(([, v]) => v === upper); - const lbl = pair ? pair[0] : trimmed; - return { - enumValue: upper, - toggleRe: new RegExp(`^(?:${escapeRegex(lbl)}|${escapeRegex(upper)})$`, "i"), - }; - } - return { - enumValue: null, - toggleRe: new RegExp(`^${escapeRegex(trimmed)}$`, "i"), - }; -} - -/** Resolves the active `PromptStateController` (`Qa`) from the project composer. */ -function resolvePromptState(): PromptStateController | null { - const projPage = findProjectPageInstance(); - const liveUx = findLiveBasePromptBox(false, findPromptBoxHost(projPage)); - return liveUx?.Qa ?? projPage?.Qa ?? runtimeState.promptState ?? null; -} - -/** Reads the model picker option array from `Qa.model.Wqa()` or `Qa.model.Yqa()`. */ -function readModelOptions(qa: PromptStateController | null): ReadonlyArray<{ - readonly hg?: string; - readonly displayName?: string; - readonly isDisabled?: boolean; -}> | null { - const opts = qa?.model?.Wqa?.() ?? qa?.model?.Yqa?.(); - return Array.isArray(opts) ? opts : null; -} - -/** Reads the active model family identifier from `Qa.model.ala()` or `Qa.model.cla()`. */ -function readActiveModelId(qa: PromptStateController | null): string { - const id = - qa?.model?.ala?.() ?? qa?.model?.cla?.() ?? qa?.model?.family?.()?.id ?? ""; - return typeof id === "string" ? id.trim() : ""; -} +import type { GenerationConfig, NgLView } from "./types"; /** Walks up from `tb` to locate the enclosing composer panel container. */ function findComposerRoot(tb: Element | null): ParentNode { @@ -389,8 +244,9 @@ async function setLengthSlider(secs: number, scopeRoot: ParentNode): Promise { - const hasLViewMap = (): boolean => runtimeState.ngLViewMap instanceof Map; - if (hasLViewMap()) { + const hasLiveQa = (): boolean => + runtimeState.ngLViewMap instanceof Map && resolvePromptState() !== null; + if (hasLiveQa()) { return; } await withLViewMapCapture(async () => { @@ -401,7 +257,7 @@ async function ensureLViewCapture(allowSettingsClick = false): Promise { const tipEls = (visible.length > 0 ? visible : all).slice(0, 12); await hoverProbe(tipEls, 60); }); - if (hasLViewMap()) { + if (hasLiveQa()) { return; } if (allowSettingsClick) { @@ -558,70 +414,112 @@ export async function setupGeneration( // Optional resolution control may be unavailable. } - const rawModel = cfg.model != null ? String(cfg.model).trim() : ""; - const modelSpec = rawModel ? buildModelMatchers(rawModel) : null; + const candidateSpecs = resolveCandidateModelSpecs(cfg, wantImageMode); + let targetSpec: ModelMatcher | null = null; let hadModelPickerItems = false; let clickedModelItem = false; try { - if (modelSpec) { - const preQa = resolvePromptState(); - const preOptions = readModelOptions(preQa); - const matchedOption = preOptions?.find((opt) => { - const disp = String(opt?.displayName || "").trim(); - const hg = String(opt?.hg || "").trim(); - return modelSpec.labelRe.test(disp) || modelSpec.hgRe.test(hg); - }); - const exactDisplay = String(matchedOption?.displayName || "").trim(); - const menuRe = exactDisplay - ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") - : modelSpec.labelRe; - const familyBtn = document.querySelector( - 'button[aria-label="Select model family"]', - ); - if (isVisibleEnabled(familyBtn)) { - familyBtn.click(); - let pickerPane: Element | null = null; - for (let w = 0; w < 8; w += 1) { - await delay(50); - pickerPane = - document.querySelector(".flow-model-picker-panel") || - Array.from(document.querySelectorAll(".cdk-overlay-pane")) - .reverse() - .find( - (p) => - !p.querySelector(".mdc-tooltip") && !p.contains(familyBtn), - ) || - null; - if (pickerPane) break; + const preQa = resolvePromptState(); + const preOptions = readModelOptions(preQa); + let exactDisplay = ""; + if (preOptions !== null) { + for (const spec of candidateSpecs) { + const hit = preOptions.find((opt) => { + if (opt?.isDisabled === true) return false; + const disp = String(opt?.displayName || "").trim(); + const hg = String(opt?.hg || "").trim(); + return spec.labelRe.test(disp) || spec.hgRe.test(hg); + }); + if (hit) { + targetSpec = spec; + exactDisplay = String(hit.displayName || "").trim(); + break; } - if (pickerPane) { - hadModelPickerItems = - pickerPane.querySelectorAll( - 'flow-menu-item, .model-select-option, [role="menuitem"], [role="option"]', - ).length > 0; - clickedModelItem = + } + if (!targetSpec) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_model" }; + } + } + const specsToTry = targetSpec ? [targetSpec] : candidateSpecs; + const familyBtn = document.querySelector( + 'button[aria-label="Select model family"]', + ); + if (isVisibleEnabled(familyBtn)) { + familyBtn.click(); + let pickerPane: Element | null = null; + for (let w = 0; w < 8; w += 1) { + await delay(50); + pickerPane = + document.querySelector(".flow-model-picker-panel") || + Array.from(document.querySelectorAll(".cdk-overlay-pane")) + .reverse() + .find( + (p) => + !p.querySelector(".mdc-tooltip") && !p.contains(familyBtn), + ) || + null; + if (pickerPane) break; + } + if (pickerPane) { + hadModelPickerItems = + pickerPane.querySelectorAll( + 'flow-menu-item, .model-select-option, [role="menuitem"], [role="option"]', + ).length > 0; + for (const spec of specsToTry) { + const menuRe = + spec === targetSpec && exactDisplay + ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") + : spec.labelRe; + if ( clickByText(menuRe, pickerPane, false) || - (menuRe !== modelSpec.labelRe && - clickByText(modelSpec.labelRe, pickerPane, false)) || - clickByText(modelSpec.hgRe, pickerPane, false); + (menuRe !== spec.labelRe && + clickByText(spec.labelRe, pickerPane, false)) || + clickByText(spec.hgRe, pickerPane, false) + ) { + targetSpec = spec; + clickedModelItem = true; + break; + } + } + } + await delay(120); + await closeModelMenu(); + } else { + for (const spec of specsToTry) { + const menuRe = + spec === targetSpec && exactDisplay + ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") + : spec.labelRe; + if ( + clickByText(menuRe, settingsScope(), false) || + clickByText(spec.hgRe, settingsScope(), false) + ) { + targetSpec = spec; + clickedModelItem = true; + await delay(120); + break; } - await delay(120); - await closeModelMenu(); - } else if ( - clickByText(menuRe, settingsScope(), false) || - clickByText(modelSpec.hgRe, settingsScope(), false) - ) { - clickedModelItem = true; - await delay(120); } } + if (!targetSpec) { + const postTryQa = resolvePromptState(); + targetSpec = + candidateSpecs.find((spec) => + verifyModelSpec(postTryQa, wantImageMode, spec), + ) ?? + candidateSpecs[0] ?? + null; + } } catch { // Optional model selector may differ by mode. } try { // Some models show the resolution toggle and the length slider only after the model changes. - if (!wantImageMode && modelSpec) { + if (!wantImageMode && targetSpec) { if (cfg.resolution) { const rRe = new RegExp(escapeRegex(String(cfg.resolution).trim()), "i"); if (clickInsideGroup("Video resolution", rRe, settingsScope())) { @@ -733,58 +631,30 @@ export async function setupGeneration( } const verifiedQa = resolvePromptState(); - if (aspectSpec?.enumValue && typeof verifiedQa?.config?.aspectRatio === "function") { - const actualAspect = String(verifiedQa.config.aspectRatio() || "").trim(); - if (actualAspect && actualAspect !== aspectSpec.enumValue) { - if (settingsOpen()) { - await closeSettingsAndMenus(); - } - return { ok: false, error: "unsupported_aspect_ratio" }; + if (aspectSpec && !verifyAspectState(verifiedQa, wantImageMode, aspectSpec)) { + if (settingsOpen()) { + await closeSettingsAndMenus(); } + return { ok: false, error: "unsupported_aspect_ratio" }; } - if (modelSpec) { - const postOptions = readModelOptions(verifiedQa); - const activeId = readActiveModelId(verifiedQa); - const activeFamilyName = String( - verifiedQa?.model?.family?.()?.displayName || "", - ).trim(); - let modelVerified = true; - if (postOptions && postOptions.length > 0) { - const matchedOpt = postOptions.find((opt) => { - const disp = String(opt?.displayName || "").trim(); - const hg = String(opt?.hg || "").trim(); - return modelSpec.labelRe.test(disp) || modelSpec.hgRe.test(hg); - }); - if (!matchedOpt || matchedOpt.isDisabled === true) { - modelVerified = false; - } else if (activeId) { - const targetHg = String(matchedOpt.hg || "").trim(); - if ( - targetHg - ? activeId !== targetHg - : !modelSpec.hgRe.test(activeId) && !modelSpec.labelRe.test(activeId) - ) { - modelVerified = false; - } - } - } else if (activeId) { - if ( - !modelSpec.hgRe.test(activeId) && - !modelSpec.labelRe.test(activeId) && - !(activeFamilyName && modelSpec.labelRe.test(activeFamilyName)) - ) { - modelVerified = false; - } - } else if (hadModelPickerItems && !clickedModelItem) { - modelVerified = false; + const pickerRejected = hadModelPickerItems && !clickedModelItem; + if ( + pickerRejected || + !targetSpec || + !verifyModelSpec(verifiedQa, wantImageMode, targetSpec) + ) { + if (settingsOpen()) { + await closeSettingsAndMenus(); } - if (!modelVerified) { - if (settingsOpen()) { - await closeSettingsAndMenus(); - } - return { ok: false, error: "unsupported_model" }; + return { ok: false, error: "unsupported_model" }; + } + + if (!aspectSpec && !verifyAspectState(verifiedQa, wantImageMode, null)) { + if (settingsOpen()) { + await closeSettingsAndMenus(); } + return { ok: false, error: "unsupported_aspect_ratio" }; } if (settingsOpen()) { diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index 17e44b6..da9aa32 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -11,8 +11,9 @@ import { findPromptBoxHost, } from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; +import { verifyComposerGenerationState } from "./generation_state"; import { runtimeState } from "./state"; -import type { NgLView } from "./types"; +import type { GenerationConfig, NgLView } from "./types"; /** Inspects `Qa.oc.all()` for loading or `Rp`-disabled attachments before submit. */ function inspectPromptAttachments(onEditPage: boolean): { @@ -90,7 +91,7 @@ function readCandidateValidatorReason(cand: unknown): string { } /** Finds the enabled Start generation button, uncovers it if needed, and returns its viewport point. */ -export async function submitGeneration(): Promise { +export async function submitGeneration(cfg?: GenerationConfig): Promise { const isVisible = (b: Element | null | undefined): b is HTMLElement => Boolean(b instanceof HTMLElement && b.getClientRects().length > 0); @@ -226,6 +227,12 @@ export async function submitGeneration(): Promise { await delay(100); continue; } + if (!onEditPage) { + const stateCheck = verifyComposerGenerationState(cfg); + if (!stateCheck.ok) { + return stateCheck; + } + } return await prepareTarget(exact, "aria_start_generation"); } const warning = checkWarning(); @@ -346,5 +353,11 @@ export async function submitGeneration(): Promise { return b.tagName === "BUTTON" && /\barrow_forward\b/i.test(label); }); if (!createBtn) return { ok: false, error: "submit_button_not_found" }; + if (!onEditPage) { + const stateCheck = verifyComposerGenerationState(cfg); + if (!stateCheck.ok) { + return stateCheck; + } + } return await prepareTarget(createBtn, "fallback_button"); } diff --git a/ts/types.ts b/ts/types.ts index f1e5f1b..a61ff6c 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -335,8 +335,14 @@ export interface PromptStateController { readonly ala?: () => string | undefined; /** Active model family ID signal in refreshed build 20261120.00 chunks. */ readonly cla?: () => string | undefined; + /** Active video model family ID signal across Flow builds. */ + readonly videoModelFamilyId?: () => string | undefined; + /** Active image model family ID signal across Flow builds. */ + readonly imageModelFamilyId?: () => string | undefined; /** Active model family descriptor signal. */ - readonly family?: () => { readonly id?: string; readonly displayName?: string } | undefined; + readonly family?: () => + | { readonly id?: string; readonly hg?: string; readonly displayName?: string } + | undefined; /** Model picker options signal in build 20261120.00. */ readonly Wqa?: () => ReadonlyArray<{ readonly hg?: string; @@ -641,14 +647,16 @@ export type ResolvedMediaResult = media_kind?: "video" | "image" | "audio"; }; -/** Configuration payload shared by `setupGeneration` and `attachIngredients`. */ +/** Configuration payload shared by `setupGeneration`, `attachIngredients`, and `submitGeneration`. */ export interface GenerationConfig { /** Generation mode (`video`, `image`, `character`, or `scene`). */ mode?: string | null; /** Aspect ratio label. */ aspect?: string | null; - /** Model label. */ + /** Explicit model family override when specified by the caller. */ model?: string | null; + /** Ordered default model family candidates used when `model` is omitted. */ + default_models?: string[] | null; /** Requested output count. */ count?: number | null; /** Prompt text. */ @@ -872,7 +880,7 @@ export interface FlowMcpRuntime { /** Opens the asset editor via Angular Router or grid tile UI controls. */ openEditAsset: (assetId: string, mediaUrl: string | null, primaryMediaId: string | null) => Promise; /** Locates the enabled generation submit button and returns its viewport click point. */ - submitGeneration: () => Promise; + submitGeneration: (cfg?: GenerationConfig) => Promise; /** Creates Flow scenes and adds clips. */ sceneOp: (req: SceneOpRequest) => Promise; /** Applies video trim timestamps or drives the scene builder extend workflow. */ From 7b1147a398b83bc2ba0f6c1faee6021330b8c03d Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:37:00 +0000 Subject: [PATCH 3/3] fix(flow): refine composer checks and remove duplicate helpers - Enforce the 10-code Rp disable list and allow single start frames. - Fall back cleanly when Flow omits Qa aspectRatio or model signals. - Keep aspect and model unset for run_edit and preserve inline edits. - Ignore blank character or asset IDs and skip redundant mode clicks. - Share composer readers, agent selectors, and TS-only model aliases. --- src/generation.rs | 169 +++++++++++++++-------------- ts/attach_ingredients.ts | 109 ++++++------------- ts/composer.ts | 91 +++++++++++++++- ts/generation_state.ts | 121 +++++++++++++++------ ts/setup_generation.ts | 222 +++++++++++++++++++++++---------------- ts/submit_generation.ts | 59 +++-------- ts/types.ts | 4 + 7 files changed, 441 insertions(+), 334 deletions(-) diff --git a/src/generation.rs b/src/generation.rs index 42fdba0..633e39a 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -87,66 +87,53 @@ struct AssetWaitSpec<'a> { submit_summary: &'a str, } +/// Context for `apply_generation_controls` distinguishing standard generation from edit flows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SubmissionKind { + /// Standard `flow_generate` request. + Generate, + /// Image edit fallback on the project workspace when no edit view opens. + EditFallback, + /// Edit session already opened via `/edit/` or an inline tile edit button. + InlineEdit, +} + /// Validated and normalized control parameters sent to the browser generation runtime. struct NormalizedControls { /// Canonical mode string (`"video"` or `"image"`). mode: &'static str, - /// Canonical aspect ratio label. - aspect: String, - /// Explicit model family display name or caller override when specified. + /// Canonical aspect ratio label when explicitly provided or defaulted for generation. + aspect: Option, + /// Trimmed explicit model family override when specified by the caller. model: Option, - /// Ordered default model family candidates when `model` is omitted. - default_models: &'static [&'static str], - /// Normalized video mode (`Some("ingredients")` or `Some("frames")`) for video runs. - video_type: Option<&'static str>, + /// Explicit video sub-mode (`Some("ingredients")` or `Some("frames")`) when supplied by the caller. + explicit_video_type: Option<&'static str>, + /// Non-empty trimmed project asset IDs to attach. + asset_ids: Option>, + /// Non-empty trimmed character IDs or names to attach. + characters: Option>, /// Clamped batch output count in `1..=4`. count: u32, } -/// Returns ordered default `Select model family` names for `mode` when `model` is omitted. -fn default_model_families(mode: &str) -> &'static [&'static str] { - if mode == "image" { - &["Nano Banana 2"] - } else { - &["Veo 3.1 Lite", "Veo 3.1 Fast"] - } -} - -/// Normalizes an explicit model identifier to its canonical family name without cross-family substitution. -fn normalize_explicit_model(raw: Option<&str>) -> Option { - let trimmed = raw.map(str::trim).unwrap_or(""); - if trimmed.is_empty() { - return None; - } - let key = trimmed - .split(|ch: char| ch.is_whitespace() || matches!(ch, '-' | '_' | '.')) - .filter(|part| !part.is_empty()) - .map(str::to_ascii_lowercase) - .collect::>() - .join("_"); - let canonical = match key.as_str() { - "veo_3_1_fast" => "Veo 3.1 Fast", - "veo_3_1_lite" => "Veo 3.1 Lite", - "veo_3_1" => "Veo 3.1", - "veo_3_1_quality" => "Veo 3.1 Quality", - "veo_3_fast" => "Veo 3 Fast", - "veo_3" => "Veo 3", - "veo_2" => "Veo 2", - "veo_2_fast" => "Veo 2 Fast", - "veo_2_quality" => "Veo 2 Quality", - "gemini_omni" | "macaron_cookie" => "Gemini Omni", - "nano_banana" => "Nano Banana", - "nano_banana_2" => "Nano Banana 2", - "nano_banana_pro" => "Nano Banana Pro", - "imagen_3" => "Imagen 3", - "imagen_4" => "Imagen 4", - _ => return Some(trimmed.to_string()), - }; - Some(canonical.to_string()) +/// Trims items in `raw` and drops empty strings, returning `None` when none remain. +fn clean_string_list(raw: Option<&[String]>) -> Option> { + let items: Vec = raw + .unwrap_or(&[]) + .iter() + .map(|item| item.trim()) + .filter(|item| !item.is_empty()) + .map(str::to_string) + .collect(); + (!items.is_empty()).then_some(items) } /// Normalizes generation parameters and rejects invalid video aspect, character, and frame combinations. -fn resolve_generation_controls(scene: &SceneParams) -> Result { +fn resolve_generation_controls( + scene: &SceneParams, + kind: SubmissionKind, +) -> Result { + let is_edit = kind != SubmissionKind::Generate; let raw_mode = scene .mode .as_deref() @@ -161,23 +148,30 @@ fn resolve_generation_controls(scene: &SceneParams) -> Result Some("ingredients"), + None => None, Some(vt) if vt.eq_ignore_ascii_case("ingredients") || vt.eq_ignore_ascii_case("ingredient") @@ -200,29 +194,39 @@ fn resolve_generation_controls(scene: &SceneParams) -> Result Result Result { - let controls = resolve_generation_controls(scene)?; + let controls = resolve_generation_controls(scene, kind)?; validate_local_files(scene.frames.as_deref(), "Reference image").await?; let cfg = json!({ "mode": controls.mode, "aspect": controls.aspect, "model": controls.model, - "default_models": if controls.model.is_none() { - Some(controls.default_models) - } else { - None - }, + "edit": kind != SubmissionKind::Generate, + "inline_edit": kind == SubmissionKind::InlineEdit, "count": controls.count, "prompt": scene.prompt, - "asset_ids": scene.asset_ids, - "characters": scene.characters, - "video_type": controls.video_type, + "asset_ids": controls.asset_ids, + "characters": controls.characters, + "video_type": controls.explicit_video_type, "duration": scene.duration, "resolution": scene.resolution, }); @@ -661,11 +663,13 @@ pub(crate) async fn run_generation( scene: &SceneParams, on_progress: ProgressCallback, ) -> Result<(Vec, Vec, Vec)> { - let controls = resolve_generation_controls(scene)?; + let controls = resolve_generation_controls(scene, SubmissionKind::Generate)?; ensure_project_workspace_root(engine).await?; ensure_flow_store(engine).await?; let mut normalized_scene = scene.clone(); - normalized_scene.video_type = controls.video_type.map(str::to_string); + normalized_scene.video_type = controls.explicit_video_type.map(str::to_string); + normalized_scene.asset_ids = controls.asset_ids; + normalized_scene.characters = controls.characters; let scene = &normalized_scene; // Upload local frames into the library first and attach them as assets, so that the // uploaded tiles are not counted as generated outputs. @@ -696,7 +700,7 @@ pub(crate) async fn run_generation( let expected_count = scene.count.unwrap_or(2).clamp(1, 4) as usize; let mut net_rx = engine.subscribe_network().await?; - let submit_res = apply_generation_controls(engine, scene).await?; + let submit_res = apply_generation_controls(engine, scene, SubmissionKind::Generate).await?; let submit_summary = format_submit_progress("submitted generation", &submit_res); on_progress(submit_summary.clone()); @@ -822,8 +826,13 @@ pub(crate) async fn run_edit( count: Some(1), ..Default::default() }; + let edit_kind = if opened_in_ui || in_edit_route { + SubmissionKind::InlineEdit + } else { + SubmissionKind::EditFallback + }; let mut net_rx = engine.subscribe_network().await?; - let submit_res = apply_generation_controls(engine, &scene).await?; + let submit_res = apply_generation_controls(engine, &scene, edit_kind).await?; let submit_summary = format_submit_progress("submitted edit", &submit_res); on_progress(submit_summary.clone()); diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 42eff88..75f301e 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -13,12 +13,16 @@ import { type PickerMatchTarget, } from "./angular"; import { + AGENT_COMPOSER_SELECTOR, closeSettingsAndMenus, ensureManualComposer, findLiveBasePromptBox, findProjectPageInstance, findPromptBoxHost, findTextbox, + isPromptItemLoading, + promptItemDisabledReason, + readComposerItems, settingsOpen, } from "./composer"; import { @@ -69,21 +73,6 @@ function itemMatchesTarget(item: unknown, target: IngredientTarget): boolean { name.trim().toLowerCase() === target.name.toLowerCase()); } -/** Live `Rp` ingredient disable codes defined in `level1.js` (`n7b` / `l7b`). */ -const LIVE_RP_DISABLE_CODES: ReadonlySet = new Set([ - "CAPACITY_EXCEEDED", - "AGENT_CAPACITY_EXCEEDED", - "IMAGE_REFERENCES_EXCEEDED", - "AUDIO_REFERENCES_EXCEEDED", - "DURATION_NOT_SUPPORTED", - "TYPE_NOT_SUPPORTED", - "IMAGE_MODE_NOT_SUPPORTED", - "MISSING_VISUAL_INGREDIENT", - "INVALID_CHARACTER_NO_IMAGES", - "MISSING_PAIRED_FRAME", - "DIFFERENT_AGENT_SESSION", -]); - /** Selector matching `flow-ingredient-chip`, all 7 `flow-*-ingredient-chip` tags, and `.upload-slot-filled-chip`. */ const COMPOSER_CHIP_HOST_SELECTOR = [ "flow-ingredient-chip", @@ -111,32 +100,6 @@ const COMPOSER_CHIP_BUTTON_SELECTOR = [ 'flow-prompt-box button[aria-label*="Remove" i]', ].join(", "); -/** Selector excluding Flow Agent drawer composers from manual composer cleanup. */ -const AGENT_COMPOSER_EXCLUSION_SELECTOR = - "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; - -/** Returns true while a prompt item is still loading asynchronously. */ -function itemLoading(item: unknown): boolean { - return readOwn(item, "isLoading") === true; -} - -/** Returns the terminal `Rp` disable code (or legacy invalid `tl` state) when an item cannot be submitted. */ -function itemDisabledReason(item: unknown): string | null { - const rp = readOwn(item, "Rp"); - if (typeof rp === "string" && rp.trim().length > 0) { - const code = rp.trim(); - return LIVE_RP_DISABLE_CODES.has(code) ? code : code; - } - const tl = readOwn(item, "tl"); - if ( - typeof tl === "string" && - /^(?:INVALID|ERROR|FAILED)(?:_|$)/i.test(tl.trim()) - ) { - return tl.trim(); - } - return null; -} - /** Verifies the requested frame in each slot before the prompt can be submitted. */ function framesReady(items: unknown[] | null, targets: IngredientTarget[]): boolean { if (!items || items.length !== targets.length) return false; @@ -144,26 +107,33 @@ function framesReady(items: unknown[] | null, targets: IngredientTarget[]): bool return targets.every((target, index) => { const slot = index === 0 ? "FIRST_FRAME" : "LAST_FRAME"; const item = hasSlots ? items.find((entry) => readOwn(entry, "Ud") === slot) : items[index]; - return !itemLoading(item) && !itemDisabledReason(item) && itemMatchesTarget(item, target); + return ( + !isPromptItemLoading(item) && + !promptItemDisabledReason(item) && + itemMatchesTarget(item, target) + ); }); } /** Attaches reference ingredients or characters and writes the generation prompt text. */ export async function attachIngredients(cfg: GenerationConfig): Promise { const onEditPage = /\/edit\//.test(location.pathname || ""); + const skipCleanup = onEditPage || Boolean(cfg.inline_edit); const ingredientTargets: IngredientTarget[] = []; const tileMap = runtimeState.store?.getTileMap?.(); if (Array.isArray(cfg.asset_ids)) { for (const id of cfg.asset_ids) { - const t = tileMap?.get(String(id)); + const idStr = String(id ?? "").trim(); + if (!idStr) continue; + const t = tileMap?.get(idStr); const hasDisplayName = Boolean(t?.displayName && String(t.displayName).trim()); ingredientTargets.push({ - id: String(id), + id: idStr, primaryMediaId: t?.primaryMediaId || t?.Fb?.id || t?.Fb?.mediaId || null, hasDisplayName, - name: hasDisplayName && t?.displayName ? String(t.displayName).trim() : String(id), + name: hasDisplayName && t?.displayName ? String(t.displayName).trim() : idStr, url: pickTileUrl(t), tile: t || null, }); @@ -172,7 +142,8 @@ export async function attachIngredients(cfg: GenerationConfig): Promise if (Array.isArray(cfg.characters)) { for (const c of cfg.characters) { - const key = String(c); + const key = String(c ?? "").trim(); + if (!key) continue; let matched: FlowTile | null = tileMap?.get(key) || null; if (!matched && tileMap instanceof Map) { const low = key.toLowerCase(); @@ -247,22 +218,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const initialTb = onEditPage ? findTextbox(true) : await ensureManualComposer(); if (!onEditPage && !initialTb) return { ok: false, error: "manual_prompt_not_ready" }; - const readPageItems = ( - page: ReturnType, - ux?: ReturnType, - ): Array> | null => { - const raw = - page?.Qa?.oc?.all?.() ?? - page?.Qa?.kc?.all?.() ?? - page?.oc?.all?.() ?? - ux?.Qa?.oc?.all?.() ?? - ux?.Qa?.kc?.all?.() ?? - runtimeState.promptState?.oc?.all?.() ?? - runtimeState.promptState?.kc?.all?.(); - return Array.isArray(raw) ? raw : null; - }; - - if (!onEditPage && !(runtimeState.ngLViewMap instanceof Map)) { + if (!skipCleanup && !(runtimeState.ngLViewMap instanceof Map)) { const tipEls = Array.from( document.querySelectorAll("[mattooltip], button[aria-label]"), ).slice(0, 8); @@ -273,14 +229,14 @@ export async function attachIngredients(cfg: GenerationConfig): Promise } } - if (!onEditPage) { + if (!skipCleanup) { const clearBtn = Array.from( document.querySelectorAll( 'flow-prompt-box button[aria-label="Clear prompt"], button[aria-label="Clear prompt"]', ), ).find( (el): el is HTMLElement => - isVisibleEnabled(el) && !el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR), + isVisibleEnabled(el) && !el.closest(AGENT_COMPOSER_SELECTOR), ); if (clearBtn) { clearBtn.click(); @@ -292,7 +248,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise document.querySelectorAll(COMPOSER_CHIP_BUTTON_SELECTOR), ).filter((el): el is HTMLElement => { if (!(el instanceof HTMLElement)) return false; - if (el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR)) return false; + if (el.closest(AGENT_COMPOSER_SELECTOR)) return false; if (isDisabledProp(el) || el.getClientRects().length === 0) return false; if (el.closest(COMPOSER_CHIP_HOST_SELECTOR)) return true; if (!isVisibleEnabled(el)) return false; @@ -314,10 +270,10 @@ export async function attachIngredients(cfg: GenerationConfig): Promise document.querySelectorAll(`flow-prompt-box ${COMPOSER_CHIP_HOST_SELECTOR}`), ).filter( (el) => - !el.closest(AGENT_COMPOSER_EXCLUSION_SELECTOR) && + !el.closest(AGENT_COMPOSER_SELECTOR) && el.getClientRects().length > 0, ); - let remainingItems = readPageItems(cleanupPage, cleanupUx); + let remainingItems = readComposerItems(cleanupPage, cleanupUx); if ( (remainingItems && remainingItems.length > 0) || remainingChips.length > 0 @@ -330,7 +286,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise clearFn.call(cleanupUx?.Qa ?? cleanupPage?.Qa ?? runtimeState.promptState); await delay(100); } - remainingItems = readPageItems(cleanupPage, cleanupUx); + remainingItems = readComposerItems(cleanupPage, cleanupUx); } if (remainingItems && remainingItems.length > 0) { return { ok: false, error: "stale_composer_items_not_cleared" }; @@ -408,7 +364,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise if (!onEditPage && target.tile && (!isVideoFrames || !hasFrameSlotBtn)) { const projPage = findProjectPageInstance(); if (projPage && typeof projPage.Ph === "function") { - const beforeItems = readPageItems(projPage) || []; + const beforeItems = readComposerItems(projPage, null) || []; const prevCount = beforeItems.length; try { projPage.Ph(target.tile); @@ -416,7 +372,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise } catch { // Fall back to DOM picker below. } - const afterItems = readPageItems(projPage) || []; + const afterItems = readComposerItems(projPage, null) || []; const added = afterItems.some((item) => itemMatchesTarget(item, target)) || (!isVideoFrames && afterItems.length > prevCount); if (added) { @@ -675,11 +631,11 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const liveUx = !onEditPage ? findLiveBasePromptBox(false, findPromptBoxHost(projPage)) : null; - let finalItems = !onEditPage ? readPageItems(projPage, liveUx) : null; + let finalItems = !onEditPage ? readComposerItems(projPage, liveUx) : null; const findDisabledError = (items: unknown[] | null): string | null => { if (!items) return null; for (const item of items) { - const reason = itemDisabledReason(item); + const reason = promptItemDisabledReason(item); if (reason) return reason; } return null; @@ -689,7 +645,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ? framesReady(finalItems, ingredientTargets) : finalItems === null || (finalItems.length >= ingredientTargets.length && - !finalItems.some(itemLoading) && + !finalItems.some(isPromptItemLoading) && !findDisabledError(finalItems)); for ( let attempt = 0; @@ -700,7 +656,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise attempt++ ) { await delay(100); - finalItems = readPageItems(projPage, liveUx); + finalItems = readComposerItems(projPage, liveUx); } const disabledCode = findDisabledError(finalItems); if (disabledCode) { @@ -733,10 +689,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const writeInfo = await writePromptBox(tb, cfg.prompt, { liveUx: findLiveBasePromptBox(onEditPage, promptHost), seeds: composerSeeds, - excludeSelector: - !onEditPage - ? "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box" - : null, + excludeSelector: !onEditPage ? AGENT_COMPOSER_SELECTOR : null, strictSync: true, onCloseSettings: closeSettingsAndMenus, }); diff --git a/ts/composer.ts b/ts/composer.ts index 9f86053..2c887eb 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -18,7 +18,22 @@ const TEXTBOX_SELECTOR = '.ProseMirror[contenteditable="true"], [role="textbox"][contenteditable="true"], [contenteditable="true"], textarea'; /** Containers that belong to the Agent composer. */ -const AGENT_COMPOSER = "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; +export const AGENT_COMPOSER_SELECTOR = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + +/** Live `Rp` terminal ingredient disable codes in Google Flow (`l7b`). */ +const LIVE_RP_DISABLE_CODES: ReadonlySet = new Set([ + "CAPACITY_EXCEEDED", + "AGENT_CAPACITY_EXCEEDED", + "IMAGE_REFERENCES_EXCEEDED", + "AUDIO_REFERENCES_EXCEEDED", + "DURATION_NOT_SUPPORTED", + "TYPE_NOT_SUPPORTED", + "IMAGE_MODE_NOT_SUPPORTED", + "MISSING_VISUAL_INGREDIENT", + "INVALID_CHARACTER_NO_IMAGES", + "DIFFERENT_AGENT_SESSION", +]); /** Detected quota or high-demand warning button inside a Flow composer. */ export interface ComposerWarning { @@ -33,7 +48,7 @@ function composerTextbox(root: ParentNode | null, edit: boolean): HTMLElement | return Array.from(root?.querySelectorAll(TEXTBOX_SELECTOR) ?? []).find( (el): el is HTMLElement => el instanceof HTMLElement && el.getClientRects().length > 0 && - !isDisabledProp(el) && (edit || !el.closest(AGENT_COMPOSER)), + !isDisabledProp(el) && (edit || !el.closest(AGENT_COMPOSER_SELECTOR)), ) ?? null; } @@ -275,11 +290,81 @@ export function findLiveBasePromptBox( ); } +/** Reads attached composer items from live `Qa.oc.all()` or `Qa.kc.all()` signals. */ +export function readComposerItems( + page?: ProjectPageInstance | null, + ux?: BasePromptBoxInstance | null, +): Array> | null { + const resolvedPage = page === undefined ? findProjectPageInstance() : page; + const resolvedUx = + ux === undefined + ? findLiveBasePromptBox(false, findPromptBoxHost(resolvedPage)) + : ux; + const raw = + resolvedPage?.Qa?.oc?.all?.() ?? + resolvedPage?.Qa?.kc?.all?.() ?? + resolvedPage?.oc?.all?.() ?? + resolvedUx?.Qa?.oc?.all?.() ?? + resolvedUx?.Qa?.kc?.all?.() ?? + runtimeState.promptState?.oc?.all?.() ?? + runtimeState.promptState?.kc?.all?.(); + return Array.isArray(raw) ? raw : null; +} + +/** Returns true while a composer prompt item is still loading asynchronously. */ +export function isPromptItemLoading(item: unknown): boolean { + return readOwn(item, "isLoading") === true; +} + +/** Returns a known terminal `Rp` disable code (or legacy invalid `tl` code) when an item is disabled. */ +export function promptItemDisabledReason(item: unknown): string | null { + const rp = readOwn(item, "Rp"); + if (typeof rp === "string") { + const code = rp.trim(); + if (LIVE_RP_DISABLE_CODES.has(code)) { + return code; + } + } + const tl = readOwn(item, "tl"); + if ( + typeof tl === "string" && + /^(?:INVALID|ERROR|FAILED)(?:_|$)/i.test(tl.trim()) + ) { + return tl.trim(); + } + return null; +} + +/** Inspects attached composer items for loading state or known `Rp` disable codes. */ +export function inspectPromptAttachments(skipCheck: boolean): { + loading: boolean; + disabledReason: string | null; +} { + if (skipCheck) { + return { loading: false, disabledReason: null }; + } + const items = readComposerItems(); + if (!items) { + return { loading: false, disabledReason: null }; + } + let loading = false; + for (const item of items) { + const reason = promptItemDisabledReason(item); + if (reason) { + return { loading: false, disabledReason: reason }; + } + if (isPromptItemLoading(item)) { + loading = true; + } + } + return { loading, disabledReason: null }; +} + /** Returns true when a custom warning element or one of its children is visible on screen. */ function isWarningElementVisible(el: Element, excludeAgent: boolean): boolean { if (!(el instanceof HTMLElement) || !el.isConnected) return false; if (el.closest('[hidden], [aria-hidden="true"]')) return false; - if (excludeAgent && el.closest(AGENT_COMPOSER)) return false; + if (excludeAgent && el.closest(AGENT_COMPOSER_SELECTOR)) return false; const style = window.getComputedStyle(el); if (style.display === "none" || style.visibility === "hidden") return false; if (el.getClientRects().length > 0) return true; diff --git a/ts/generation_state.ts b/ts/generation_state.ts index 8dc1c95..5c4862c 100644 --- a/ts/generation_state.ts +++ b/ts/generation_state.ts @@ -5,6 +5,7 @@ import { isLiveLView, resolveLView } from "./angular"; import { + AGENT_COMPOSER_SELECTOR, findLiveBasePromptBox, findProjectPageInstance, findPromptBoxHost, @@ -125,17 +126,18 @@ export function resolveCandidateModelSpecs( if (rawModel) { return [buildModelMatchers(rawModel)]; } - const rawDefaults = Array.isArray(cfg.default_models) - ? cfg.default_models - .map((m) => String(m || "").trim()) - .filter((m) => m.length > 0) - : []; - const defaults = - rawDefaults.length > 0 - ? rawDefaults - : wantImageMode - ? ["Nano Banana 2"] - : ["Veo 3.1 Lite", "Veo 3.1 Fast"]; + if (cfg.edit) { + return []; + } + if (Array.isArray(cfg.default_models)) { + return cfg.default_models + .map((m) => String(m || "").trim()) + .filter((m) => m.length > 0) + .map((m) => buildModelMatchers(m)); + } + const defaults = wantImageMode + ? ["Nano Banana 2"] + : ["Veo 3.1 Lite", "Veo 3.1 Fast"]; return defaults.map((m) => buildModelMatchers(m)); } @@ -188,8 +190,6 @@ export function resolvePromptState(): PromptStateController | null { if (projPage?.Qa) { return projPage.Qa; } - const agentSel = - "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; const isPromptState = (cand: unknown): cand is PromptStateController => { if (!cand || typeof cand !== "object" || cand instanceof Node) return false; const obj = cand as Partial; @@ -214,7 +214,7 @@ export function resolvePromptState(): PromptStateController | null { document.querySelector("flow-prompt-box flow-base-prompt-box"), document.querySelector("flow-prompt-box"), document.querySelector("flow-project-page"), - ].filter((el): el is Element => Boolean(el && !el.closest(agentSel))); + ].filter((el): el is Element => Boolean(el && !el.closest(AGENT_COMPOSER_SELECTOR))); for (const seed of seeds) { let lv: NgLView | null = resolveLView(seed); for (let d = 0; d < 6 && Array.isArray(lv); d += 1) { @@ -226,7 +226,7 @@ export function resolvePromptState(): PromptStateController | null { if (runtimeState.ngLViewMap instanceof Map) { for (const lv of runtimeState.ngLViewMap.values()) { if (!isLiveLView(lv)) continue; - if (lv[0] instanceof Element && lv[0].closest(agentSel)) continue; + if (lv[0] instanceof Element && lv[0].closest(AGENT_COMPOSER_SELECTOR)) continue; const hit = scanLv(lv); if (hit) return hit; } @@ -303,41 +303,66 @@ function readActiveAspectRatio(qa: PromptStateController | null): string { } } -/** Returns true only when `Qa.config.aspectRatio()` is readable, valid for `wantImageMode`, and matches `aspectSpec`. */ +/** Returns true when Flow exposes readable `Qa.model` options, IDs, or family state. */ +export function hasReadableModelState( + qa: PromptStateController | null, + wantImageMode: boolean, +): boolean { + if (!qa?.model) { + return false; + } + const opts = readModelOptions(qa); + if (opts !== null && opts.length > 0) { + return true; + } + return Boolean( + typeof qa.model.family === "function" || + readActiveModelId(qa, wantImageMode) || + readActiveModelFamilyName(qa), + ); +} + +/** Verifies `Qa.config.aspectRatio()` when exposed, falling back to best-effort when absent. */ export function verifyAspectState( qa: PromptStateController | null, wantImageMode: boolean, aspectSpec: AspectSpec | null, ): boolean { + if (aspectSpec) { + if ( + !aspectSpec.enumValue || + (!wantImageMode && aspectSpec.enumValue === "SQUARE") + ) { + return false; + } + } const actualAspect = readActiveAspectRatio(qa); - if (!actualAspect || !SKB_ASPECT_ENUM_VALUES.has(actualAspect)) { - return false; + if (!actualAspect) { + return true; } if (!wantImageMode && actualAspect === "SQUARE") { return false; } if (aspectSpec) { - return Boolean(aspectSpec.enumValue && actualAspect === aspectSpec.enumValue); + return actualAspect === aspectSpec.enumValue; } return true; } -/** Returns true only when `Qa.model` exposes a readable active model matching `spec`. */ +/** Verifies `Qa.model` matches `spec` when Flow exposes model signals, or returns true when unexposed. */ export function verifyModelSpec( qa: PromptStateController | null, wantImageMode: boolean, spec: ModelMatcher, ): boolean { - if (!qa?.model) { - return false; + if (!hasReadableModelState(qa, wantImageMode) || !qa?.model) { + return true; } const postOptions = readModelOptions(qa); const activeId = readActiveModelId(qa, wantImageMode); const activeFamilyName = readActiveModelFamilyName(qa); - if (!activeId && !activeFamilyName) { - return false; - } - if (postOptions !== null) { + const hasFamilyFn = typeof qa.model.family === "function"; + if (postOptions !== null && postOptions.length > 0) { const matchedOpt = postOptions.find((opt) => { const disp = String(opt?.displayName || "").trim(); const hg = String(opt?.hg || "").trim(); @@ -346,6 +371,16 @@ export function verifyModelSpec( if (!matchedOpt || matchedOpt.isDisabled === true) { return false; } + if (!activeId && !activeFamilyName) { + if (hasFamilyFn) { + try { + return Boolean(qa.model.family?.()); + } catch { + return false; + } + } + return true; + } const targetHg = String(matchedOpt.hg || "").trim(); const targetDisp = String(matchedOpt.displayName || "").trim(); if (targetHg) { @@ -367,9 +402,9 @@ export function verifyModelSpec( : spec.labelRe.test(activeFamilyName), ); } - if (typeof qa.model.family === "function") { + if (hasFamilyFn) { try { - if (!qa.model.family()) { + if (!qa.model.family?.()) { return false; } } catch { @@ -391,12 +426,15 @@ export function verifyModelSpec( return spec.labelRe.test(activeFamilyName); } -/** Verifies readable matching aspect ratio and model state on the project composer before submission. */ +/** Verifies aspect ratio and model state on the project composer when Flow exposes those signals. */ export function verifyComposerGenerationState( cfg?: GenerationConfig, ): { ok: true } | { ok: false; error: string } { const qa = resolvePromptState(); if (cfg) { + if (cfg.inline_edit) { + return { ok: true }; + } const mode = String(cfg.mode || "video").toLowerCase(); const wantImageMode = mode === "image" || mode === "character" || mode === "scene"; @@ -406,7 +444,10 @@ export function verifyComposerGenerationState( return { ok: false, error: "unsupported_aspect_ratio" }; } const candidates = resolveCandidateModelSpecs(cfg, wantImageMode); - if (!candidates.some((spec) => verifyModelSpec(qa, wantImageMode, spec))) { + if ( + candidates.length > 0 && + !candidates.some((spec) => verifyModelSpec(qa, wantImageMode, spec)) + ) { return { ok: false, error: "unsupported_model" }; } if (!aspectSpec && !verifyAspectState(qa, wantImageMode, null)) { @@ -424,13 +465,25 @@ export function verifyComposerGenerationState( if (!verifyAspectState(qa, wantImageMode, null)) { return { ok: false, error: "unsupported_aspect_ratio" }; } + if (!hasReadableModelState(qa, wantImageMode) || !qa?.model) { + return { ok: true }; + } const activeId = readActiveModelId(qa, wantImageMode); const activeName = readActiveModelFamilyName(qa); - if (!qa?.model || (!activeId && !activeName)) { - return { ok: false, error: "unsupported_model" }; - } const opts = readModelOptions(qa); - if (opts !== null) { + if (opts !== null && opts.length > 0) { + if (!activeId && !activeName) { + if (typeof qa.model.family === "function") { + try { + if (!qa.model.family()) { + return { ok: false, error: "unsupported_model" }; + } + } catch { + return { ok: false, error: "unsupported_model" }; + } + } + return { ok: true }; + } const found = opts.find((opt) => { const hg = String(opt?.hg || "").trim(); const disp = String(opt?.displayName || "").trim(); diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index c199264..cf5e0d7 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -16,6 +16,7 @@ import { import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; import { escapeRegex, + hasReadableModelState, readModelOptions, resolveCandidateModelSpecs, resolveExpectedAspect, @@ -277,7 +278,8 @@ async function ensureLViewCapture(allowSettingsClick = false): Promise { export async function setupGeneration( cfg: GenerationConfig, ): Promise<{ ok: boolean; error?: string }> { - const onEditPage = /\/edit\//.test(location.pathname || ""); + const onEditPage = + /\/edit\//.test(location.pathname || "") || Boolean(cfg.inline_edit); if (!onEditPage) { const textbox = await ensureManualComposer(); @@ -325,10 +327,28 @@ export async function setupGeneration( await delay(140); try { - if (!wantImageMode) { + if (!wantImageMode && !cfg.edit) { const qaMode = String(resolvePromptState()?.config?.mode?.() || ""); + const explicitVideoType = Boolean( + cfg.video_type && String(cfg.video_type).trim(), + ); + const hasFrameSlots = Array.from( + document.querySelectorAll( + 'flow-prompt-box button, flow-prompt-box [role="button"]', + ), + ).some( + (el) => + isVisibleEnabled(el) && + /^(?:start|end)$/i.test( + (el.getAttribute("aria-label") || elText(el)).trim(), + ), + ); + const isAlreadyIngredients = + qaMode === "VIDEO_REFERENCES" || qaMode === "VIDEO_INGREDIENTS"; const needsSwitch = wantVideoIngredients - ? !qaMode || qaMode === "VIDEO_FRAMES" || Boolean(cfg.video_type) + ? qaMode + ? !isAlreadyIngredients + : explicitVideoType || hasFrameSlots : qaMode !== "VIDEO_FRAMES"; if (needsSwitch) { const vtRe = wantVideoIngredients @@ -414,107 +434,116 @@ export async function setupGeneration( // Optional resolution control may be unavailable. } + const isExplicitModel = Boolean(cfg.model && String(cfg.model).trim()); const candidateSpecs = resolveCandidateModelSpecs(cfg, wantImageMode); let targetSpec: ModelMatcher | null = null; let hadModelPickerItems = false; let clickedModelItem = false; - try { - const preQa = resolvePromptState(); - const preOptions = readModelOptions(preQa); - let exactDisplay = ""; - if (preOptions !== null) { - for (const spec of candidateSpecs) { - const hit = preOptions.find((opt) => { - if (opt?.isDisabled === true) return false; - const disp = String(opt?.displayName || "").trim(); - const hg = String(opt?.hg || "").trim(); - return spec.labelRe.test(disp) || spec.hgRe.test(hg); - }); - if (hit) { - targetSpec = spec; - exactDisplay = String(hit.displayName || "").trim(); - break; + if (candidateSpecs.length > 0) { + try { + const preQa = resolvePromptState(); + const preOptions = readModelOptions(preQa); + let exactDisplay = ""; + if (preOptions !== null && preOptions.length > 0) { + for (const spec of candidateSpecs) { + const hit = preOptions.find((opt) => { + if (opt?.isDisabled === true) return false; + const disp = String(opt?.displayName || "").trim(); + const hg = String(opt?.hg || "").trim(); + return spec.labelRe.test(disp) || spec.hgRe.test(hg); + }); + if (hit) { + targetSpec = spec; + exactDisplay = String(hit.displayName || "").trim(); + break; + } } - } - if (!targetSpec) { - if (settingsOpen()) { - await closeSettingsAndMenus(); + if (!targetSpec) { + const anyEnabled = preOptions.some((opt) => opt?.isDisabled !== true); + if (isExplicitModel || !anyEnabled) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_model" }; + } } - return { ok: false, error: "unsupported_model" }; } - } - const specsToTry = targetSpec ? [targetSpec] : candidateSpecs; - const familyBtn = document.querySelector( - 'button[aria-label="Select model family"]', - ); - if (isVisibleEnabled(familyBtn)) { - familyBtn.click(); - let pickerPane: Element | null = null; - for (let w = 0; w < 8; w += 1) { - await delay(50); - pickerPane = - document.querySelector(".flow-model-picker-panel") || - Array.from(document.querySelectorAll(".cdk-overlay-pane")) - .reverse() - .find( - (p) => - !p.querySelector(".mdc-tooltip") && !p.contains(familyBtn), - ) || - null; - if (pickerPane) break; - } - if (pickerPane) { - hadModelPickerItems = - pickerPane.querySelectorAll( - 'flow-menu-item, .model-select-option, [role="menuitem"], [role="option"]', - ).length > 0; + const specsToTry = targetSpec + ? [targetSpec] + : preOptions !== null && preOptions.length > 0 + ? [] + : candidateSpecs; + const familyBtn = document.querySelector( + 'button[aria-label="Select model family"]', + ); + if (isVisibleEnabled(familyBtn)) { + familyBtn.click(); + let pickerPane: Element | null = null; + for (let w = 0; w < 8; w += 1) { + await delay(50); + pickerPane = + document.querySelector(".flow-model-picker-panel") || + Array.from(document.querySelectorAll(".cdk-overlay-pane")) + .reverse() + .find( + (p) => + !p.querySelector(".mdc-tooltip") && !p.contains(familyBtn), + ) || + null; + if (pickerPane) break; + } + if (pickerPane) { + hadModelPickerItems = + pickerPane.querySelectorAll( + 'flow-menu-item, .model-select-option, [role="menuitem"], [role="option"]', + ).length > 0; + for (const spec of specsToTry) { + const menuRe = + spec === targetSpec && exactDisplay + ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") + : spec.labelRe; + if ( + clickByText(menuRe, pickerPane, false) || + (menuRe !== spec.labelRe && + clickByText(spec.labelRe, pickerPane, false)) || + clickByText(spec.hgRe, pickerPane, false) + ) { + targetSpec = spec; + clickedModelItem = true; + break; + } + } + } + await delay(120); + await closeModelMenu(); + } else { for (const spec of specsToTry) { const menuRe = spec === targetSpec && exactDisplay ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") : spec.labelRe; if ( - clickByText(menuRe, pickerPane, false) || - (menuRe !== spec.labelRe && - clickByText(spec.labelRe, pickerPane, false)) || - clickByText(spec.hgRe, pickerPane, false) + clickByText(menuRe, settingsScope(), false) || + clickByText(spec.hgRe, settingsScope(), false) ) { targetSpec = spec; clickedModelItem = true; + await delay(120); break; } } } - await delay(120); - await closeModelMenu(); - } else { - for (const spec of specsToTry) { - const menuRe = - spec === targetSpec && exactDisplay - ? new RegExp(`^${escapeRegex(exactDisplay)}$`, "i") - : spec.labelRe; - if ( - clickByText(menuRe, settingsScope(), false) || - clickByText(spec.hgRe, settingsScope(), false) - ) { - targetSpec = spec; - clickedModelItem = true; - await delay(120); - break; - } + if (!targetSpec && (isExplicitModel || specsToTry.length > 0)) { + const postTryQa = resolvePromptState(); + targetSpec = + candidateSpecs.find((spec) => + verifyModelSpec(postTryQa, wantImageMode, spec), + ) ?? + (isExplicitModel ? (candidateSpecs[0] ?? null) : null); } + } catch { + // Optional model selector may differ by mode. } - if (!targetSpec) { - const postTryQa = resolvePromptState(); - targetSpec = - candidateSpecs.find((spec) => - verifyModelSpec(postTryQa, wantImageMode, spec), - ) ?? - candidateSpecs[0] ?? - null; - } - } catch { - // Optional model selector may differ by mode. } try { @@ -540,10 +569,10 @@ export async function setupGeneration( try { let qa = resolvePromptState(); let curMode = String(qa?.config?.mode?.() || ""); - if (wantImageMode && curMode && curMode !== "IMAGE") { + if (wantImageMode && curMode && !curMode.startsWith("IMAGE")) { clickInsideGroup("Mode", /\bimage\b/i, settingsScope()); await delay(140); - } else if (!wantImageMode) { + } else if (!wantImageMode && !cfg.edit) { if (curMode && !curMode.startsWith("VIDEO")) { clickInsideGroup("Mode", /\bvideo\b/i, settingsScope()); await delay(140); @@ -638,16 +667,23 @@ export async function setupGeneration( return { ok: false, error: "unsupported_aspect_ratio" }; } - const pickerRejected = hadModelPickerItems && !clickedModelItem; - if ( - pickerRejected || - !targetSpec || - !verifyModelSpec(verifiedQa, wantImageMode, targetSpec) - ) { - if (settingsOpen()) { - await closeSettingsAndMenus(); + if (candidateSpecs.length > 0) { + const modelStateExposed = hasReadableModelState(verifiedQa, wantImageMode); + const pickerRejected = + hadModelPickerItems && !clickedModelItem && isExplicitModel; + if ( + pickerRejected || + (isExplicitModel && !targetSpec) || + (targetSpec && !verifyModelSpec(verifiedQa, wantImageMode, targetSpec)) || + (!targetSpec && + modelStateExposed && + readModelOptions(verifiedQa)?.every((opt) => opt?.isDisabled === true)) + ) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_model" }; } - return { ok: false, error: "unsupported_model" }; } if (!aspectSpec && !verifyAspectState(verifiedQa, wantImageMode, null)) { diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index da9aa32..32e4eed 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -5,50 +5,15 @@ import { readAngularTooltip, readOwn, resolveLView } from "./angular"; import { + AGENT_COMPOSER_SELECTOR, findComposerWarning, - findLiveBasePromptBox, - findProjectPageInstance, - findPromptBoxHost, + inspectPromptAttachments, } from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; import { verifyComposerGenerationState } from "./generation_state"; import { runtimeState } from "./state"; import type { GenerationConfig, NgLView } from "./types"; -/** Inspects `Qa.oc.all()` for loading or `Rp`-disabled attachments before submit. */ -function inspectPromptAttachments(onEditPage: boolean): { - loading: boolean; - disabledReason: string | null; -} { - if (onEditPage) { - return { loading: false, disabledReason: null }; - } - const projPage = findProjectPageInstance(); - const liveUx = findLiveBasePromptBox(false, findPromptBoxHost(projPage)); - const raw = - projPage?.Qa?.oc?.all?.() ?? - projPage?.Qa?.kc?.all?.() ?? - projPage?.oc?.all?.() ?? - liveUx?.Qa?.oc?.all?.() ?? - liveUx?.Qa?.kc?.all?.() ?? - runtimeState.promptState?.oc?.all?.() ?? - runtimeState.promptState?.kc?.all?.(); - if (!Array.isArray(raw)) { - return { loading: false, disabledReason: null }; - } - let loading = false; - for (const item of raw) { - const rp = readOwn(item, "Rp"); - if (typeof rp === "string" && rp.trim().length > 0) { - return { loading: false, disabledReason: rp.trim() }; - } - if (readOwn(item, "isLoading") === true) { - loading = true; - } - } - return { loading, disabledReason: null }; -} - /** Extracts a disabled submit validator message from a component or controller candidate. */ function readCandidateValidatorReason(cand: unknown): string { if (!cand || typeof cand !== "object" || cand instanceof Node) return ""; @@ -149,8 +114,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise } const onEditPage = /\/edit\//.test(location.pathname || ""); - const agentSelector = - "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + const skipAttachmentCheck = onEditPage || Boolean(cfg?.inline_edit); const scopedSelectors = onEditPage ? [ 'flow-edit-video-prompt-box button[aria-label="Start generation"]', @@ -192,7 +156,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise const match = Array.from(document.querySelectorAll(sel)).find( (b): b is HTMLElement => { if (!isVisible(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { + if (!onEditPage && b.closest(AGENT_COMPOSER_SELECTOR)) { return false; } return true; @@ -204,7 +168,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise document.querySelectorAll('button[aria-label="Start generation"]'), ).find((b): b is HTMLElement => { if (!isVisible(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { + if (!onEditPage && b.closest(AGENT_COMPOSER_SELECTOR)) { return false; } return true; @@ -213,7 +177,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise }; for (let i = 0; i < 120; i += 1) { - const attachmentState = inspectPromptAttachments(onEditPage); + const attachmentState = inspectPromptAttachments(skipAttachmentCheck); if (attachmentState.disabledReason) { return { ok: false, @@ -244,7 +208,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise } } - const attachmentAfter = inspectPromptAttachments(onEditPage); + const attachmentAfter = inspectPromptAttachments(skipAttachmentCheck); if (attachmentAfter.disabledReason) { return { ok: false, @@ -263,6 +227,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise if (exactAfter && isVisible(exactAfter) && !isVisibleEnabled(exactAfter)) { let reason = runtimeState.promptState?.Ff?.N7a?.() || + runtimeState.promptState?.Ff?.S7a?.() || runtimeState.promptState?.lf?.jYa?.() || ""; if (!reason) { @@ -289,7 +254,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise if ( !onEditPage && lv[0] instanceof Element && - lv[0].closest(agentSelector) + lv[0].closest(AGENT_COMPOSER_SELECTOR) ) { continue; } @@ -307,7 +272,9 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise reason = readAngularTooltip(exactAfter); } const visiblePm = Array.from(document.querySelectorAll(".ProseMirror")).find( - (el) => el.getClientRects().length > 0 && (!onEditPage ? !el.closest(agentSelector) : true), + (el) => + el.getClientRects().length > 0 && + (!onEditPage ? !el.closest(AGENT_COMPOSER_SELECTOR) : true), ); const detail = [ reason, @@ -324,7 +291,7 @@ export async function submitGeneration(cfg?: GenerationConfig): Promise const btns = Array.from(document.querySelectorAll('button, [role="button"]')); const createBtn = btns.find((b): b is HTMLElement => { if (b.tagName === "A" || !isVisibleEnabled(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { + if (!onEditPage && b.closest(AGENT_COMPOSER_SELECTOR)) { return false; } if ( diff --git a/ts/types.ts b/ts/types.ts index a61ff6c..c6d1ce0 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -657,6 +657,10 @@ export interface GenerationConfig { model?: string | null; /** Ordered default model family candidates used when `model` is omitted. */ default_models?: string[] | null; + /** True when `flow_edit` reuses the composer without forcing default model or aspect ratio. */ + edit?: boolean | null; + /** True when `openEditAsset` already opened an inline edit session in the workspace UI. */ + inline_edit?: boolean | null; /** Requested output count. */ count?: number | null; /** Prompt text. */