diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..03ff5d2 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"` (`"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. | | `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..773c259 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` | いいえ | モデル上書き。既定は `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[]` | いいえ | 送信前にアップロードするローカル参照またはキーフレーム画像パス。 | | `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..c322ae8 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` | 否 | 模型覆盖。`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[]` | 否 | 提交前上传的本地参考图像或关键帧路径。 | | `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..633e39a 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 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". + /// 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,170 @@ 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 when explicitly provided or defaulted for generation. + aspect: Option, + /// Trimmed explicit model family override when specified by the caller. + model: Option, + /// 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, +} + +/// 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, + kind: SubmissionKind, +) -> Result { + let is_edit = kind != SubmissionKind::Generate; + 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 explicit_aspect = scene + .aspect + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()); + let aspect = if is_edit { + explicit_aspect.map(str::to_string) + } else { + Some(explicit_aspect.unwrap_or("16:9").to_string()) + }; + if let Some(a) = aspect.as_deref() + && mode == "video" + && (a == "1:1" || a.eq_ignore_ascii_case("square")) + { + anyhow::bail!("Video mode does not support aspect ratio '{a}'; use '16:9' or '9:16'"); + } + let explicit_video_type = if mode == "video" && !is_edit { + match scene + .video_type + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + { + None => None, + 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 + }; + let effective_video_type = if mode == "video" && !is_edit { + Some(explicit_video_type.unwrap_or("ingredients")) + } else { + None + }; + let asset_ids = clean_string_list(scene.asset_ids.as_deref()); + let characters = clean_string_list(scene.characters.as_deref()); + if effective_video_type == Some("frames") { + if characters.is_some() { + 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) + asset_ids.as_ref().map_or(0, Vec::len); + anyhow::ensure!( + ref_count <= 2, + "Frame mode accepts at most two references, got {ref_count}" + ); + } + let model = scene + .model + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + Ok(NormalizedControls { + mode, + aspect, + model, + explicit_video_type, + asset_ids, + characters, + 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, + kind: SubmissionKind, ) -> Result { + let controls = resolve_generation_controls(scene, kind)?; 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, + "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": scene.video_type, + "asset_ids": controls.asset_ids, + "characters": controls.characters, + "video_type": controls.explicit_video_type, "duration": scene.duration, "resolution": scene.resolution, }); @@ -134,7 +269,7 @@ async fn apply_generation_controls( } let res = engine - .call_flow_async("attachIngredients", json!([cfg])) + .call_flow_async("attachIngredients", json!([cfg.clone()])) .await?; if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { anyhow::bail!( @@ -195,13 +330,16 @@ async fn apply_generation_controls( } let mut submit_res = engine - .call_flow_async("submitGeneration", json!([])) + .call_flow_async("submitGeneration", json!([cfg])) .await?; if submit_res.get("ok").and_then(|v| v.as_bool()) != Some(true) { let err = submit_res .get("error") .and_then(|v| v.as_str()) .unwrap_or("unknown"); + if matches!(err, "unsupported_model" | "unsupported_aspect_ratio") { + anyhow::bail!("Failed to configure Flow generation UI: {err}"); + } let detail = submit_res .get("detail") .and_then(|v| v.as_str()) @@ -525,17 +663,14 @@ pub(crate) async fn run_generation( scene: &SceneParams, on_progress: ProgressCallback, ) -> Result<(Vec, Vec, Vec)> { + let controls = resolve_generation_controls(scene, SubmissionKind::Generate)?; 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.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. let uploaded_scene; @@ -565,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()); @@ -691,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 10bef6d..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 { @@ -28,6 +32,7 @@ import { elText, fifeBase, hoverProbe, + isDisabledProp, isVisibleEnabled, pickTileUrl, setNativeValue, @@ -68,15 +73,32 @@ 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); - }); -} +/** 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(", "); /** Verifies the requested frame in each slot before the prompt can be submitted. */ function framesReady(items: unknown[] | null, targets: IngredientTarget[]): boolean { @@ -85,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 !itemNotReady(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, }); @@ -113,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(); @@ -188,17 +218,42 @@ 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) { + if (!skipCleanup && !(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 (!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_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_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 +263,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_SELECTOR) && + el.getClientRects().length > 0, + ); + let remainingItems = readComposerItems(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 = readComposerItems(cleanupPage, cleanupUx); + } + if (remainingItems && remainingItems.length > 0) { + return { ok: false, error: "stale_composer_items_not_cleared" }; + } } const scope: ParentNode = (() => { @@ -224,32 +307,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; @@ -307,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); @@ -315,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) { @@ -574,14 +631,36 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const liveUx = !onEditPage ? 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++) { + 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 = promptItemDisabledReason(item); + if (reason) return reason; + } + return null; + }; + const ready = (): boolean => + isVideoFrames + ? framesReady(finalItems, ingredientTargets) + : finalItems === null || + (finalItems.length >= ingredientTargets.length && + !finalItems.some(isPromptItemLoading) && + !findDisabledError(finalItems)); + for ( + let attempt = 0; + attachedSteps === ingredientTargets.length && + !ready() && + !findDisabledError(finalItems) && + attempt < 25; + attempt++ + ) { await delay(100); - finalItems = readPageItems(projPage, liveUx); + finalItems = readComposerItems(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" }; @@ -610,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 new file mode 100644 index 0000000..5c4862c --- /dev/null +++ b/ts/generation_state.ts @@ -0,0 +1,508 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Match and verify Google Flow generation model family and aspect ratio signals. + +import { isLiveLView, resolveLView } from "./angular"; +import { + AGENT_COMPOSER_SELECTOR, + findLiveBasePromptBox, + findProjectPageInstance, + findPromptBoxHost, +} from "./composer"; +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` / `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)]; + } + 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)); +} + +/** 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 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(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) { + 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(AGENT_COMPOSER_SELECTOR)) 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 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) { + return true; + } + if (!wantImageMode && actualAspect === "SQUARE") { + return false; + } + if (aspectSpec) { + return actualAspect === aspectSpec.enumValue; + } + return true; +} + +/** 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 (!hasReadableModelState(qa, wantImageMode) || !qa?.model) { + return true; + } + const postOptions = readModelOptions(qa); + const activeId = readActiveModelId(qa, wantImageMode); + const activeFamilyName = readActiveModelFamilyName(qa); + 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(); + return spec.labelRe.test(disp) || spec.hgRe.test(hg); + }); + 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) { + 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 (hasFamilyFn) { + 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 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"; + 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.length > 0 && + !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" }; + } + if (!hasReadableModelState(qa, wantImageMode) || !qa?.model) { + return { ok: true }; + } + const activeId = readActiveModelId(qa, wantImageMode); + const activeName = readActiveModelFamilyName(qa); + const opts = readModelOptions(qa); + 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(); + 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 af2018c..cf5e0d7 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -14,14 +14,20 @@ import { settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { + escapeRegex, + hasReadableModelState, + readModelOptions, + resolveCandidateModelSpecs, + resolveExpectedAspect, + resolvePromptState, + verifyAspectState, + verifyModelSpec, +} from "./generation_state"; +import type { ModelMatcher } from "./generation_state"; import { runtimeState } from "./state"; import type { GenerationConfig, NgLView } from "./types"; -/** Escapes regular expression metacharacters in literal labels. */ -function escapeRegex(s: unknown): string { - return String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - /** Walks up from `tb` to locate the enclosing composer panel container. */ function findComposerRoot(tb: Element | null): ParentNode { if (!tb) return document; @@ -53,17 +59,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 +109,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 +118,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) @@ -200,8 +245,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 () => { @@ -212,7 +258,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) { @@ -232,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(); @@ -256,7 +303,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 +327,61 @@ 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 && !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 + ? !isAlreadyIngredients + : explicitVideoType || hasFrameSlots + : 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 +434,45 @@ export async function setupGeneration( // Optional resolution control may be unavailable. } - try { - if (cfg.model) { - const flexPattern = escapeRegex(String(cfg.model).trim()).replace( - /[-_\s]+/g, - "[\\s\\-_]*", - ); - const modelRe = new RegExp(flexPattern, "i"); + 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; + 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) { + const anyEnabled = preOptions.some((opt) => opt?.isDisabled !== true); + if (isExplicitModel || !anyEnabled) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_model" }; + } + } + } + const specsToTry = targetSpec + ? [targetSpec] + : preOptions !== null && preOptions.length > 0 + ? [] + : candidateSpecs; const familyBtn = document.querySelector( 'button[aria-label="Select model family"]', ); @@ -381,21 +493,62 @@ 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; + 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 if (clickByText(modelRe, settingsScope(), false)) { - await delay(120); + } 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. } - } 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 (mode === "video" && cfg.model) { + if (!wantImageMode && targetSpec) { if (cfg.resolution) { const rRe = new RegExp(escapeRegex(String(cfg.resolution).trim()), "i"); if (clickInsideGroup("Video resolution", rRe, settingsScope())) { @@ -414,29 +567,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"; - if (wantImageMode && curMode && curMode !== "IMAGE") { + let qa = resolvePromptState(); + let curMode = String(qa?.config?.mode?.() || ""); + if (wantImageMode && curMode && !curMode.startsWith("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 && !cfg.edit) { + 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 +659,40 @@ export async function setupGeneration( // Ignore non-fatal post-settings sync check. } + const verifiedQa = resolvePromptState(); + if (aspectSpec && !verifyAspectState(verifiedQa, wantImageMode, aspectSpec)) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_aspect_ratio" }; + } + + 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" }; + } + } + + if (!aspectSpec && !verifyAspectState(verifiedQa, wantImageMode, null)) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: "unsupported_aspect_ratio" }; + } + if (settingsOpen()) { await closeSettingsAndMenus(); } diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..32e4eed 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -4,10 +4,15 @@ // Locate the enabled Flow generation submit button and compute its viewport click point. import { readAngularTooltip, readOwn, resolveLView } from "./angular"; -import { findComposerWarning } from "./composer"; +import { + AGENT_COMPOSER_SELECTOR, + findComposerWarning, + inspectPromptAttachments, +} 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"; /** Extracts a disabled submit validator message from a component or controller candidate. */ function readCandidateValidatorReason(cand: unknown): string { @@ -24,17 +29,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; } @@ -45,7 +56,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); @@ -103,8 +114,7 @@ export async function submitGeneration(): 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"]', @@ -146,7 +156,7 @@ export async function submitGeneration(): 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; @@ -158,7 +168,7 @@ export async function submitGeneration(): 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; @@ -167,19 +177,49 @@ export async function submitGeneration(): Promise { }; for (let i = 0; i < 120; i += 1) { + const attachmentState = inspectPromptAttachments(skipAttachmentCheck); + 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; + } + if (!onEditPage) { + const stateCheck = verifyComposerGenerationState(cfg); + if (!stateCheck.ok) { + return stateCheck; + } + } 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(skipAttachmentCheck); + 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; @@ -187,6 +227,7 @@ export async function submitGeneration(): Promise { if (exactAfter && isVisible(exactAfter) && !isVisibleEnabled(exactAfter)) { let reason = runtimeState.promptState?.Ff?.N7a?.() || + runtimeState.promptState?.Ff?.S7a?.() || runtimeState.promptState?.lf?.jYa?.() || ""; if (!reason) { @@ -213,7 +254,7 @@ export async function submitGeneration(): Promise { if ( !onEditPage && lv[0] instanceof Element && - lv[0].closest(agentSelector) + lv[0].closest(AGENT_COMPOSER_SELECTOR) ) { continue; } @@ -231,7 +272,9 @@ export async function submitGeneration(): 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, @@ -248,7 +291,7 @@ export async function submitGeneration(): 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 ( @@ -277,5 +320,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 2e1369d..c6d1ce0 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -322,12 +322,42 @@ 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 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 hg?: 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. */ @@ -617,14 +647,20 @@ 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; + /** 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. */ @@ -848,7 +884,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. */