From 4235a5abdc362bef843d97fee00c7b26fe7d7a2f 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:24:52 +0000 Subject: [PATCH] feat: drive generation state via verified PromptState contracts - Normalize video_type to ingredients and reject square video aspect - Block characters and extra frame references in video frames mode - Add PromptComposerFormat for build 20261120.00_p0 and probeStore - Set mode, model family, aspect, and count directly on PromptState - Clear all seven ingredient chip types and block Rp disable codes --- docs/en/tools-reference.md | 8 +- docs/ja/tools-reference.md | 8 +- docs/zh-CN/tools-reference.md | 8 +- src/generation.rs | 143 ++++++++- src/service.rs | 1 + ts/attach_ingredients.ts | 102 +++--- ts/composer.ts | 80 ++++- ts/composer_state.ts | 573 ++++++++++++++++++++++++++++++++++ ts/frontend_builds.ts | 60 ++++ ts/frontend_compatibility.ts | 59 +++- ts/setup_generation.ts | 200 ++++++++++-- ts/submit_generation.ts | 33 ++ ts/types.ts | 50 ++- xtask/src/contracts.rs | 124 +++++++- 14 files changed, 1334 insertions(+), 115 deletions(-) create mode 100644 ts/composer_state.ts diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..9bcd590 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`). | +| `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 to the prompt controls (`"ingredients"` mode 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..dcfab9a 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`)。 | +| `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[]` | いいえ | プロンプトコントロールへ添付するキャラクター ID または名前(`"ingredients"` モードまたは `image` モード)。 | +| `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..eef327b 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`)。 | +| `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[]` | 否 | 附加到提示词控件的角色 ID 或名称(`"ingredients"` 模式或 `image` 模式)。 | +| `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..15fa503 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). 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,11 +87,127 @@ struct AssetWaitSpec<'a> { submit_summary: &'a str, } +/// Normalizes `mode`, `video_type`, `aspect`, and `model` on `scene` and validates constraints. +pub(crate) fn normalize_generation_scene(scene: &mut 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" + }; + scene.mode = Some(mode.to_string()); + + let aspect = scene + .aspect + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("16:9") + .to_string(); + if mode == "video" && (aspect == "1:1" || aspect.eq_ignore_ascii_case("square")) { + anyhow::bail!( + "Video generation does not support aspect ratio '{aspect}'; use '16:9' or '9:16'" + ); + } + scene.aspect = Some(aspect); + + if mode == "video" { + let normalized_vt = match scene + .video_type + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + { + None => "ingredients", + Some(vt) + if vt.eq_ignore_ascii_case("ingredients") + || vt.eq_ignore_ascii_case("ingredient") + || vt.eq_ignore_ascii_case("references") + || vt.eq_ignore_ascii_case("video_ingredients") + || vt.eq_ignore_ascii_case("video_references") => + { + "ingredients" + } + Some(vt) + if vt.eq_ignore_ascii_case("frames") + || vt.eq_ignore_ascii_case("frame") + || vt.eq_ignore_ascii_case("video_frames") => + { + "frames" + } + Some(other) => anyhow::bail!( + "Unsupported video_type '{other}'; expected 'ingredients' or 'frames'" + ), + }; + if normalized_vt == "frames" { + if scene + .characters + .as_ref() + .is_some_and(|chars| chars.iter().any(|c| !c.trim().is_empty())) + { + anyhow::bail!( + "Frame mode does not support character ingredients; 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}" + ); + } + scene.video_type = Some(normalized_vt.to_string()); + } else { + scene.video_type = None; + } + + let resolved_model = match scene + .model + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + { + None => { + if mode == "image" { + "nano-banana-2".to_string() + } else { + "veo_3_1_lite".to_string() + } + } + Some(m) + if m.eq_ignore_ascii_case("veo-3.1-fast") || m.eq_ignore_ascii_case("veo_3_1_fast") => + { + "veo_3_1_lite".to_string() + } + Some(m) => m.to_string(), + }; + scene.model = Some(resolved_model); + Ok(()) +} + /// Configures generation controls, uploads reference frames, writes prompt text, and submits. async fn apply_generation_controls( engine: &ChromeEngine, scene: &SceneParams, ) -> Result { + let mut normalized; + let scene = if scene.mode.is_some() || scene.edit_from.is_none() && scene.aspect.is_some() { + normalized = scene.clone(); + if normalized.mode.is_some() { + normalize_generation_scene(&mut normalized)?; + } + &normalized + } else { + scene + }; validate_local_files(scene.frames.as_deref(), "Reference image").await?; let raw_mode = scene.mode.as_deref().unwrap_or("video"); @@ -103,8 +219,13 @@ async fn apply_generation_controls( let model = scene.model.as_deref().unwrap_or(if mode == "image" { "nano-banana-2" } else { - "veo-3.1-fast" + "veo_3_1_lite" }); + let video_type = if scene.mode.is_some() && mode == "video" { + Some(scene.video_type.as_deref().unwrap_or("ingredients")) + } else { + scene.video_type.as_deref() + }; let count = scene.count.unwrap_or(2).clamp(1, 4); let cfg = json!({ @@ -115,7 +236,7 @@ async fn apply_generation_controls( "prompt": scene.prompt, "asset_ids": scene.asset_ids, "characters": scene.characters, - "video_type": scene.video_type, + "video_type": video_type, "duration": scene.duration, "resolution": scene.resolution, }); @@ -525,17 +646,11 @@ pub(crate) async fn run_generation( scene: &SceneParams, on_progress: ProgressCallback, ) -> Result<(Vec, Vec, Vec)> { + let mut normalized_scene = scene.clone(); + normalize_generation_scene(&mut normalized_scene)?; + let scene = &normalized_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}" - ); - } // 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/src/service.rs b/src/service.rs index 4b8223b..ef92f88 100644 --- a/src/service.rs +++ b/src/service.rs @@ -180,6 +180,7 @@ impl FlowService { resolution: req.resolution, ..Default::default() }; + generation::normalize_generation_scene(&mut scene)?; characters::apply_character_look(&self.db, &mut scene).await?; Ok(self.queue.enqueue(scene).await) } diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 10bef6d..8fba002 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -21,6 +21,13 @@ import { findTextbox, settingsOpen, } from "./composer"; +import { + clearPromptComposerItems, + findPromptItemsDisableReason, + isPromptItemLoading, + itemDisableReason, + readPromptItems, +} from "./composer_state"; import { characterLooksOf, cleanMediaId, @@ -68,14 +75,9 @@ 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. */ +/** Returns true while a prompt item is loading or carries a defined `Rp` disable code. */ 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); - }); + return isPromptItemLoading(item) || itemDisableReason(item) !== null; } /** Verifies the requested frame in each slot before the prompt can be submitted. */ @@ -188,26 +190,18 @@ 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 staleRemoveBtns = Array.from( + if (!onEditPage) { + if (!(runtimeState.ngLViewMap instanceof Map)) { + const tipEls = 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', + "[mattooltip], button[aria-label], flow-prompt-box, flow-project-page", ), - ).filter((el): el is HTMLElement => { - 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( - lbl, - ); + ).slice(0, 8); + await withLViewMapCapture(async () => { + await hoverProbe(tipEls, 50); }); - if (staleRemoveBtns.length === 0) break; - for (const btn of staleRemoveBtns) { - btn.click(); - } - await delay(100); } + await clearPromptComposerItems(); } const scope: ParentNode = (() => { @@ -228,6 +222,8 @@ export async function attachIngredients(cfg: GenerationConfig): Promise page: ReturnType, ux?: ReturnType, ): Array> | null => { + const direct = readPromptItems(false); + if (Array.isArray(direct)) return direct; const raw = page?.Qa?.oc?.all?.() ?? page?.Qa?.kc?.all?.() ?? @@ -237,19 +233,6 @@ export async function attachIngredients(cfg: GenerationConfig): Promise 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; @@ -296,6 +279,9 @@ export async function attachIngredients(cfg: GenerationConfig): Promise String(cfg.mode || "video").toLowerCase() === "video") || (!hasAddIngredientsBtn && hasFrameSlotBtn)); + if (isVideoFrames && ingredientTargets.some((t) => Boolean(t.character))) { + return { ok: false, error: "characters_not_supported_in_frames" }; + } if (isVideoFrames && ingredientTargets.length > 2) { return { ok: false, error: "ingredient_attach_failed" }; } @@ -574,18 +560,48 @@ 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 + ? readPageItems(projPage, liveUx) + : readPromptItems(true); + const ready = (): boolean => + isVideoFrames + ? framesReady(finalItems, ingredientTargets) + : finalItems === null || + (finalItems.length >= ingredientTargets.length && + !finalItems.some(itemNotReady)); + for ( + let attempt = 0; + attachedSteps === ingredientTargets.length && + !ready() && + findPromptItemsDisableReason(finalItems) === null && + attempt < 25; + attempt++ + ) { await delay(100); - finalItems = readPageItems(projPage, liveUx); + finalItems = !onEditPage + ? readPageItems(projPage, liveUx) + : readPromptItems(true); + } + const disableReason = findPromptItemsDisableReason(finalItems); + if (disableReason) { + return { + ok: false, + error: `ingredient_disabled:${disableReason}`, + disable_reason: disableReason, + }; } if (attachedSteps < ingredientTargets.length || !ready()) { return { ok: false, error: "ingredient_attach_failed" }; } + } else if (!onEditPage) { + const residualDisable = findPromptItemsDisableReason(readPromptItems(false)); + if (residualDisable) { + return { + ok: false, + error: `ingredient_disabled:${residualDisable}`, + disable_reason: residualDisable, + }; + } } const tb = findTextbox(onEditPage); diff --git a/ts/composer.ts b/ts/composer.ts index 9f86053..7476020 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -5,12 +5,14 @@ import { isLiveLView, readAngularTooltip, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; +import { promptComposerFormat } from "./frontend_builds"; import { runtimeState } from "./state"; import type { BasePromptBoxInstance, NgLView, ProjectPageInstance, PromptBoxHost, + PromptStateController, } from "./types"; /** Selector matching editable prompt textboxes in Flow composer UI. */ @@ -264,8 +266,10 @@ export function findLiveBasePromptBox( } } } - return scanElementForBasePromptBox( - document.querySelector("flow-prompt-box flow-base-prompt-box"), + return ( + scanElementForBasePromptBox( + document.querySelector("flow-prompt-box flow-base-prompt-box"), + ) ?? scanElementForBasePromptBox(document.querySelector("flow-prompt-box")) ); } return scanElementForBasePromptBox( @@ -275,6 +279,78 @@ export function findLiveBasePromptBox( ); } +/** Resolved manual or edit composer controllers for the active Flow view. */ +export interface ResolvedComposerControllers { + /** Live `flow-project-page` instance when mounted. */ + page: ProjectPageInstance | null; + /** Live `flow-prompt-box` host managing manual and Agent composer modes. */ + host: PromptBoxHost | null; + /** Live `flow-base-prompt-box` controller when mounted. */ + ux: BasePromptBoxInstance | null; + /** Live `PromptState` (`Qa`) controller on `ux` or `page`. */ + qa: PromptStateController | null; +} + +/** Scans LViews starting at `el` for an instance of the verified `PromptState` class. */ +function scanElementForPromptState( + el: Element | null, + stateCtor: unknown, +): PromptStateController | null { + if (!el || typeof stateCtor !== "function") return null; + let cur: Element | null = el; + for (let depth = 0; depth < 6 && cur; depth += 1) { + let lv: NgLView | null = resolveLView(cur); + for (let pDepth = 0; pDepth < 6 && Array.isArray(lv); pDepth += 1) { + for (const cand of lv) { + if (cand && typeof cand === "object" && cand instanceof stateCtor) { + return cand as PromptStateController; + } + } + lv = Array.isArray(lv[3]) ? lv[3] : Array.isArray(lv[15]) ? lv[15] : null; + } + cur = cur.parentElement; + } + return null; +} + +/** Resolves `BasePromptBoxInstance` and `PromptStateController` (`Qa`) for the active route. */ +export function resolveComposerControllers(editFlag: boolean): ResolvedComposerControllers { + const page = !editFlag ? findProjectPageInstance() : null; + const host = !editFlag ? findPromptBoxHost(page) : null; + const ux = findLiveBasePromptBox(editFlag, host); + let qa: PromptStateController | null = ux?.Qa ?? page?.Qa ?? null; + if (!qa) { + const format = promptComposerFormat(); + const stateCtor = format + ? readOwn(readOwn(window, "default_AiSandboxAngularFrontend"), format.exports.promptState) + : null; + const root = editFlag + ? document.querySelector("flow-edit-video-prompt-box, flow-editor-page, flow-scene-builder") + : document.querySelector("flow-prompt-box flow-base-prompt-box, flow-prompt-box, flow-project-page"); + qa = scanElementForPromptState(root, stateCtor); + if (!qa && typeof stateCtor === "function" && runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if (!isLiveLView(lv)) continue; + if (!editFlag && lv[0] instanceof Element && lv[0].closest(AGENT_COMPOSER)) continue; + const hit = lv.find((c): c is PromptStateController => + Boolean(c && typeof c === "object" && c instanceof stateCtor), + ); + if (hit) { + qa = hit; + break; + } + } + } + } + if (!qa && !editFlag && runtimeState.promptState) { + qa = runtimeState.promptState; + } + if (qa && !editFlag) { + runtimeState.promptState = qa; + } + return { page, host, ux, qa }; +} + /** 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; diff --git a/ts/composer_state.ts b/ts/composer_state.ts new file mode 100644 index 0000000..9336cf2 --- /dev/null +++ b/ts/composer_state.ts @@ -0,0 +1,573 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Direct PromptState mutations, chip cleanup, and item disable checks for verified builds. + +import { readOwn } from "./angular"; +import { resolveComposerControllers } from "./composer"; +import { delay, elText, isVisibleEnabled } from "./dom"; +import { + PROMPT_COMPOSER_EXPORTS, + promptComposerFormat, + type PromptComposerFormat, +} from "./frontend_builds"; +import type { + GenerationConfig, + PromptModelCatalogFamily, + PromptModelOption, + PromptStateController, +} from "./types"; + +/** Custom element tags for all seven Google Flow ingredient chip components. */ +export const INGREDIENT_CHIP_TAGS = [ + "flow-character-ingredient-chip", + "flow-image-ingredient-chip", + "flow-likeness-ingredient-chip", + "flow-style-pack-ingredient-chip", + "flow-audio-ingredient-chip", + "flow-video-ingredient-chip", + "flow-file-ingredient-chip", +] as const; + +/** Live `Rp` disable reason codes assigned to prompt items in `PromptState`. */ +export const LIVE_DISABLE_REASON_CODES = [ + "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", +] as const; + +/** Selector matching Agent composer containers excluded from manual composer queries. */ +const AGENT_COMPOSER = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + +/** Selector matching any of the seven ingredient chip custom elements in `flow-prompt-box`. */ +const PROMPT_BOX_CHIP_SELECTOR = INGREDIENT_CHIP_TAGS.map( + (tag) => `flow-prompt-box ${tag}`, +).join(", "); + +/** Normalized generation settings prepared before PromptState or DOM updates. */ +export interface NormalizedComposerConfig { + /** Normalized media category (`"image"` or `"video"`). */ + modeCategory: "image" | "video"; + /** Target `PromptState` mode enum (`"IMAGE"`, `"VIDEO_FRAMES"`, or `"VIDEO_REFERENCES"`). */ + targetMode: "IMAGE" | "VIDEO_FRAMES" | "VIDEO_REFERENCES"; + /** Normalized video submode (`"ingredients"` or `"frames"`) when `modeCategory` is `"video"`. */ + videoType: "ingredients" | "frames" | null; + /** Requested aspect ratio label or enum key. */ + aspect: string; + /** Requested or default model identifier. */ + model: string; + /** Clamped output count (`1..4`) when specified. */ + count: number | null; +} + +/** Result of normalizing `GenerationConfig` inputs. */ +export type ComposerConfigCheck = + | { ok: true; config: NormalizedComposerConfig } + | { ok: false; error: string }; + +/** Result of applying `PromptState` controls on the active page. */ +export type ApplyComposerStateResult = + | { ok: true; mode: string; model: string; aspect: string } + | { ok: false; fallback: true } + | { ok: false; fallback?: false; error: string }; + +/** Verified runtime functions bound from `window.default_AiSandboxAngularFrontend`. */ +interface BoundPromptComposerRuntime { + /** Build field descriptor. */ + format: PromptComposerFormat; + /** Live `PromptState` controller. */ + qa: PromptStateController; + /** Native mode setter (`_.AQ`). */ + setMode: (qa: PromptStateController, mode: string) => void; + /** Native model family setter (`_.BQ`). */ + setModel: (qa: PromptStateController, modelId: string) => void; + /** Native output count setter (`_.scc`). */ + setCount: (qa: PromptStateController, count: number) => void; + /** Map of native aspect enum keys to `{ label, icon }` descriptors (`_.NE`). */ + aspectLabels: Record; + /** Allowed native video aspect enum keys (`_.$O`). */ + videoAspects: unknown[]; +} + +/** Escapes regular expression metacharacters in literal text. */ +function escapeRegex(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Normalizes a model identifier or display label to an exact comparison key. */ +export function normalizeModelKey(raw: string): string { + const cleaned = raw + .trim() + .toLowerCase() + .replace(/^models\//, "") + .replace(/[\s\-_.]+/g, "_") + .replace(/^_+|_+$/g, ""); + return cleaned === "veo_3_1_fast" ? "veo_3_1_lite" : cleaned; +} + +/** Builds an anchored regular expression (`^...$`) for DOM fallback model selection. */ +export function buildAnchoredModelRegex(rawModel: string): RegExp { + const canonical = + normalizeModelKey(rawModel) === "veo_3_1_lite" + ? "veo 3 1 lite" + : rawModel.trim().replace(/^models\//i, ""); + const tokens = canonical + .split(/[\s\-_.]+/) + .map((part) => part.trim()) + .filter(Boolean) + .map(escapeRegex); + if (tokens.length === 0) { + return new RegExp(`^${escapeRegex(rawModel.trim())}$`, "i"); + } + return new RegExp(`^${tokens.join("(?:[\\s\\-_.]|\\s+-\\s+)*")}$`, "i"); +} + +/** Normalizes `cfg` and validates video aspect ratio, `video_type`, and frame characters. */ +export function normalizeComposerConfig(cfg: GenerationConfig): ComposerConfigCheck { + const rawMode = String(cfg.mode || "video").trim().toLowerCase(); + const isImage = + rawMode === "image" || rawMode === "character" || rawMode === "scene"; + const modeCategory: "image" | "video" = isImage ? "image" : "video"; + const aspect = String(cfg.aspect || "16:9").trim() || "16:9"; + + if ( + modeCategory === "video" && + (aspect === "1:1" || /^square$/i.test(aspect)) + ) { + return { ok: false, error: "invalid_video_aspect_ratio" }; + } + + let videoType: "ingredients" | "frames" | null = null; + let targetMode: "IMAGE" | "VIDEO_FRAMES" | "VIDEO_REFERENCES" = "IMAGE"; + if (modeCategory === "video") { + const rawVt = String(cfg.video_type || "").trim(); + if ( + !rawVt || + /^(?:ingredients?|references?|video_ingredients|video_references)$/i.test(rawVt) + ) { + videoType = "ingredients"; + targetMode = "VIDEO_REFERENCES"; + } else if (/^(?:frames?|video_frames)$/i.test(rawVt)) { + videoType = "frames"; + targetMode = "VIDEO_FRAMES"; + } else { + return { ok: false, error: `invalid_video_type:${rawVt}` }; + } + if ( + videoType === "frames" && + Array.isArray(cfg.characters) && + cfg.characters.some((c) => String(c || "").trim().length > 0) + ) { + return { ok: false, error: "characters_not_supported_in_frames" }; + } + } + + const rawModel = String(cfg.model || "").trim(); + const defaultModel = modeCategory === "image" ? "nano-banana-2" : "veo_3_1_lite"; + const model = !rawModel + ? defaultModel + : normalizeModelKey(rawModel) === "veo_3_1_lite" + ? "veo_3_1_lite" + : rawModel; + const count = + cfg.count != null && Number.isFinite(Number(cfg.count)) + ? Math.min(4, Math.max(1, Math.round(Number(cfg.count)))) + : null; + + return { + ok: true, + config: { modeCategory, targetMode, videoType, aspect, model, count }, + }; +} + +/** Resolves verified `PromptState` exports and the live `Qa` controller when available. */ +function bindPromptComposerRuntime(): BoundPromptComposerRuntime | null { + const format = promptComposerFormat(); + if (!format) return null; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + for (const name of PROMPT_COMPOSER_EXPORTS) { + const value = readOwn(namespace, format.exports[name]); + const ok = + name === "videoAspects" + ? Array.isArray(value) && value.length > 0 + : name === "aspectLabels" + ? value !== null && typeof value === "object" + : typeof value === "function"; + if (!ok) return null; + } + const { qa } = resolveComposerControllers(false); + if ( + !qa || + typeof qa.setAspectRatio !== "function" || + typeof qa.clear !== "function" + ) { + return null; + } + return { + format, + qa, + setMode: readOwn(namespace, format.exports.setMode) as ( + qa: PromptStateController, + mode: string, + ) => void, + setModel: readOwn(namespace, format.exports.setModel) as ( + qa: PromptStateController, + modelId: string, + ) => void, + setCount: readOwn(namespace, format.exports.setCount) as ( + qa: PromptStateController, + count: number, + ) => void, + aspectLabels: readOwn(namespace, format.exports.aspectLabels) as Record< + string, + unknown + >, + videoAspects: readOwn(namespace, format.exports.videoAspects) as unknown[], + }; +} + +/** Returns true when the active build defines `promptComposer`. */ +export function buildDefinesPromptComposer(): boolean { + return Boolean(promptComposerFormat()); +} + +/** Maps a caller aspect string (`"16:9"`, `"9:16"`, `"1:1"`, or enum key) to Flow's enum key. */ +function resolveNativeAspectKey( + aspect: string, + aspectLabels: Record, +): string | null { + const trimmed = aspect.trim(); + const low = trimmed.toLowerCase(); + const enumAlias = + low === "landscape" + ? "16:9" + : low === "portrait" + ? "9:16" + : low === "square" + ? "1:1" + : low; + for (const [key, entry] of Object.entries(aspectLabels)) { + if (key.toLowerCase() === low) return key; + const label = String(readOwn(entry, "label") ?? "") + .trim() + .toLowerCase(); + if (label && (label === low || label === enumAlias)) return key; + } + return null; +} + +/** Resolves `requestedModel` to an exact `hg` family ID using anchored comparisons. */ +function resolveTargetModelFamilyId( + requestedModel: string, + qa: PromptStateController, + format: PromptComposerFormat, +): { ok: true; id: string } | { ok: false; error: string } { + const modelObj = readOwn(qa, "model"); + const readFamilies = readOwn(modelObj, format.families); + if (typeof readFamilies !== "function") { + return { ok: false, error: "model_families_signal_missing" }; + } + const rawOptions = readFamilies.call(modelObj) as unknown; + const options: PromptModelOption[] = Array.isArray(rawOptions) + ? (rawOptions as PromptModelOption[]) + : []; + const readCatalog = readOwn(modelObj, format.catalogFamilies); + const rawCatalog = + typeof readCatalog === "function" + ? (readCatalog.call(modelObj) as unknown) + : null; + const catalog: PromptModelCatalogFamily[] = Array.isArray(rawCatalog) + ? (rawCatalog as PromptModelCatalogFamily[]) + : []; + + const catalogAliases = new Map(); + for (const fam of catalog) { + const famId = String(readOwn(fam, "id") ?? "").trim(); + if (!famId) continue; + const names: string[] = [famId]; + const disp = String(readOwn(fam, "displayName") ?? "").trim(); + if (disp) names.push(disp); + const aliases = readOwn(fam, "aliases"); + if (Array.isArray(aliases)) { + for (const alias of aliases) { + if (typeof alias === "string" && alias.trim()) names.push(alias.trim()); + } + } + catalogAliases.set(famId, names); + } + + const targetKey = normalizeModelKey(requestedModel); + const matches: Array<{ id: string; disabled: boolean }> = []; + for (const option of options) { + const id = String(readOwn(option, format.modelId) ?? "").trim(); + if (!id) continue; + const displayName = String(readOwn(option, "displayName") ?? "").trim(); + const candidates = [id, displayName, ...(catalogAliases.get(id) ?? [])].filter( + Boolean, + ); + const matched = candidates.some( + (cand) => normalizeModelKey(cand) === targetKey, + ); + if (matched) { + matches.push({ id, disabled: readOwn(option, "isDisabled") === true }); + } + } + + if (matches.length === 0) { + return { ok: false, error: `unknown_model:${requestedModel}` }; + } + const enabled = matches.find((entry) => !entry.disabled); + if (!enabled) { + return { ok: false, error: `model_disabled:${matches[0].id}` }; + } + return { ok: true, id: enabled.id }; +} + +/** Applies mode, aspect ratio, model family, and output count directly on `PromptState`. */ +export function applyPromptComposerState( + cfg: GenerationConfig, +): ApplyComposerStateResult { + const checked = normalizeComposerConfig(cfg); + if (!checked.ok) { + return { ok: false, error: checked.error }; + } + if (!buildDefinesPromptComposer()) { + return { ok: false, fallback: true }; + } + const runtime = bindPromptComposerRuntime(); + if (!runtime) { + return { ok: false, error: "prompt_composer_unavailable" }; + } + const { format, qa, setMode, setModel, setCount, aspectLabels, videoAspects } = + runtime; + const { modeCategory, targetMode, aspect, model, count } = checked.config; + + const nativeAspect = resolveNativeAspectKey(aspect, aspectLabels); + if (!nativeAspect) { + return { ok: false, error: `unsupported_aspect_ratio:${aspect}` }; + } + if ( + modeCategory === "video" && + !videoAspects.some((entry) => String(entry) === nativeAspect) + ) { + return { ok: false, error: `invalid_video_aspect_ratio:${aspect}` }; + } + + setMode(qa, targetMode); + if (qa.config?.mode?.() !== targetMode) { + return { ok: false, error: `mode_update_failed:${targetMode}` }; + } + + qa.setAspectRatio?.(nativeAspect); + + const modelMatch = resolveTargetModelFamilyId(model, qa, format); + if (!modelMatch.ok) { + return { ok: false, error: modelMatch.error }; + } + setModel(qa, modelMatch.id); + const readActiveFamily = readOwn(readOwn(qa, "model"), format.activeFamily); + const activeFamily = + typeof readActiveFamily === "function" + ? String(readActiveFamily.call(readOwn(qa, "model")) ?? "") + : ""; + if (activeFamily !== modelMatch.id) { + return { ok: false, error: `model_update_failed:${modelMatch.id}` }; + } + + if (qa.config?.aspectRatio?.() !== nativeAspect) { + qa.setAspectRatio?.(nativeAspect); + } + if ( + typeof qa.config?.aspectRatio === "function" && + qa.config.aspectRatio() !== nativeAspect + ) { + return { ok: false, error: `aspect_ratio_not_supported:${aspect}` }; + } + + if (count !== null) { + setCount(qa, count); + if ( + typeof qa.config?.outputCount === "function" && + Number(qa.config.outputCount()) !== count + ) { + return { ok: false, error: `count_update_failed:${count}` }; + } + } + + return { + ok: true, + mode: targetMode, + model: modelMatch.id, + aspect: nativeAspect, + }; +} + +/** Reads the current attached prompt items array (`Qa.oc.all()`) for the active route. */ +export function readPromptItems( + editFlag: boolean, +): Array> | null { + const format = promptComposerFormat(); + const itemsKey = format?.items ?? "oc"; + const { page, ux, qa } = resolveComposerControllers(editFlag); + const candidates: unknown[] = [qa, ux?.Qa, page?.Qa, page]; + for (const holder of candidates) { + if (!holder || typeof holder !== "object") continue; + for (const key of [itemsKey, "oc", "kc"]) { + const container = readOwn(holder, key); + const allFn = readOwn(container, "all"); + if (typeof allFn === "function") { + const list = allFn.call(container) as unknown; + if (Array.isArray(list)) { + return list as Array>; + } + } + } + } + return null; +} + +/** Returns true while `item` reports `isLoading === true`. */ +export function isPromptItemLoading(item: unknown): boolean { + return readOwn(item, "isLoading") === true; +} + +/** Returns the defined `Rp` disable code on `item`, or `null` when the item is enabled. */ +export function itemDisableReason(item: unknown): string | null { + if (!item || typeof item !== "object") return null; + const format = promptComposerFormat(); + const fields = format + ? [format.disableReason, "Rp", "tl"] + : ["Rp", "tl"]; + for (const field of fields) { + const raw = readOwn(item, field); + if (typeof raw === "string") { + const trimmed = raw.trim(); + if (trimmed.length > 0) return trimmed; + } + } + return null; +} + +/** Returns the first defined `Rp` disable code across `items`, or `null` when all items are valid. */ +export function findPromptItemsDisableReason( + items: readonly unknown[] | null | undefined, +): string | null { + if (!Array.isArray(items)) return null; + for (const item of items) { + const code = itemDisableReason(item); + if (code) return code; + } + return null; +} + +/** Finds the remove button inside one of the seven `` elements. */ +function findChipRemoveButton(chip: Element): HTMLElement | null { + const buttons = Array.from(chip.querySelectorAll("button")).filter( + isVisibleEnabled, + ); + if (buttons.length === 0) return null; + const explicit = buttons.find((btn) => { + const label = ( + btn.getAttribute("aria-label") || + elText(btn) || + btn.getAttribute("title") || + "" + ).trim(); + return /\b(?:remove|delete|clear|close|cancel)\b/i.test(label); + }); + return explicit ?? buttons[buttons.length - 1] ?? null; +} + +/** Clears `PromptState`, emits `lF` (`"all"`), and removes any remaining ingredient chips. */ +export async function clearPromptComposerItems(): Promise { + const format = promptComposerFormat(); + const clearOutputKey = format?.clearOutput ?? "lF"; + const { ux, qa } = resolveComposerControllers(false); + + try { + ux?.lW?.nPa?.(); + } catch { + // Ignore optional uploader cancellation errors. + } + try { + qa?.clear?.(); + } catch { + // Fall back to DOM clear controls below if Qa.clear throws. + } + try { + const emitter = readOwn(ux, clearOutputKey) as + | { emit?: (scope: string) => void } + | undefined; + emitter?.emit?.("all"); + } catch { + // Ignore optional emitter errors. + } + try { + const onCleared = ux?.C7?.(); + if (typeof onCleared === "function") onCleared(); + } catch { + // Ignore optional clear callback errors. + } + + const hasRemainingChipsOrItems = (): boolean => + (readPromptItems(false)?.length ?? 0) > 0 || + Array.from(document.querySelectorAll(PROMPT_BOX_CHIP_SELECTOR)).some( + (chip) => !chip.closest(AGENT_COMPOSER) && chip.isConnected, + ); + + if (hasRemainingChipsOrItems()) { + await delay(40); + } + + if (hasRemainingChipsOrItems()) { + 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), + ); + if (clearBtn) { + clearBtn.click(); + await delay(60); + } + } + + for (let pass = 0; pass < 4 && hasRemainingChipsOrItems(); pass += 1) { + const removeButtons = new Set(); + for (const chip of document.querySelectorAll(PROMPT_BOX_CHIP_SELECTOR)) { + if (chip.closest(AGENT_COMPOSER)) continue; + const btn = findChipRemoveButton(chip); + if (btn) removeButtons.add(btn); + } + for (const el of document.querySelectorAll( + 'flow-prompt-box button[aria-label*="Remove" i], flow-prompt-box [class*="chip"] button', + )) { + if (!(el instanceof HTMLElement) || !isVisibleEnabled(el)) continue; + if (el.closest(AGENT_COMPOSER)) continue; + const lbl = (el.getAttribute("aria-label") || elText(el)).trim(); + if ( + /^remove\b|remove ingredient|remove reference|remove frame|remove character|remove audio|remove video|remove file|remove style|remove likeness/i.test( + lbl, + ) + ) { + removeButtons.add(el); + } + } + if (removeButtons.size === 0) break; + for (const btn of removeButtons) { + btn.click(); + } + await delay(80); + } +} diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index c10c146..37191b2 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -153,6 +153,39 @@ export const AGENT_ATTACHMENT_EXPORTS = [ "confirmUpload", ] as const satisfies readonly AgentAttachmentExport[]; +/** Browser exports required for direct PromptState control on the manual composer. */ +export const PROMPT_COMPOSER_EXPORTS = [ + "promptState", + "setMode", + "setModel", + "setCount", + "aspectLabels", + "videoAspects", +] as const; + +/** Keys in a build's PromptState export table. */ +export type PromptComposerExport = (typeof PROMPT_COMPOSER_EXPORTS)[number]; + +/** Browser exports and PromptState fields for manual generation setup and submission checks. */ +export interface PromptComposerFormat { + /** Browser exports on `window.default_AiSandboxAngularFrontend`. */ + exports: Readonly>; + /** Signal on `Qa.model` that lists filtered model options for the active mode. */ + families: string; + /** Signal on `Qa.model` that returns the active model family ID. */ + activeFamily: string; + /** Signal on `Qa.model` that returns raw `MODEL_CONFIG` family descriptors and aliases. */ + catalogFamilies: string; + /** Family ID property on each entry returned by `families`. */ + modelId: string; + /** Attached prompt items container on `Qa`. */ + items: string; + /** Disable reason code property on each entry in `Qa[items].all()`. */ + disableReason: string; + /** Output emitter on `BasePromptBoxInstance` notified when leading items clear. */ + clearOutput: string; +} + /** Browser exports and service fields for Agent settings. */ export interface AgentSettingsFormat { /** Project metadata service's query client. */ @@ -718,6 +751,8 @@ interface FrontendBuildFields { characterCreate?: CharacterCreateFormat; /** Native fields of editable project titles. */ projectTitle?: ProjectTitleFormat; + /** Native exports and PromptState fields for direct manual composer control. */ + promptComposer?: PromptComposerFormat; } /** A verified build with full or pre-Agent operation coverage. */ @@ -831,6 +866,25 @@ const LEGACY_CHARACTER_CREATE: CharacterCreateFormat = { /** Editable project title format of earlier builds. */ const LEGACY_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "tJa", stateSignal: "state" }; +/** Manual prompt composer format for Flow build 20261120.00_p0. */ +const NOVEMBER_20_PROMPT_COMPOSER: PromptComposerFormat = { + exports: { + promptState: "fP", + setMode: "AQ", + setModel: "BQ", + setCount: "scc", + aspectLabels: "NE", + videoAspects: "$O", + }, + families: "Wqa", + activeFamily: "ala", + catalogFamilies: "jx", + modelId: "hg", + items: "oc", + disableReason: "Rp", + clearOutput: "lF", +}; + /** Request formats by exact build label. Include only verified operations. */ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261117.10_p0", { @@ -887,6 +941,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], }, projectTitle: { saveEmitter: "HSa", stateSignal: "state" }, + promptComposer: NOVEMBER_20_PROMPT_COMPOSER, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -978,3 +1033,8 @@ export function projectTitleFormat(): ProjectTitleFormat { export function snapshotFormat(): SnapshotFormat | undefined { return frontendBuild(readBuildLabel())?.snapshot; } + +/** Returns the verified manual prompt composer format for the active build. */ +export function promptComposerFormat(): PromptComposerFormat | undefined { + return frontendBuild(readBuildLabel())?.promptComposer; +} diff --git a/ts/frontend_compatibility.ts b/ts/frontend_compatibility.ts index 26f1f1a..d5ed02d 100644 --- a/ts/frontend_compatibility.ts +++ b/ts/frontend_compatibility.ts @@ -4,7 +4,7 @@ // Check the build and runtime requirements of internal Flow operations. import { readOwn } from "./angular"; -import { AGENT_ATTACHMENT_EXPORTS, AGENT_EXPORTS, AGENT_SETTINGS_EXPORTS, FRONTEND_OPERATIONS, frontendBuild, MEDIA_UPLOAD_EXPORTS, readBuildLabel, withMutationAliases } from "./frontend_builds"; +import { AGENT_ATTACHMENT_EXPORTS, AGENT_EXPORTS, AGENT_SETTINGS_EXPORTS, FRONTEND_OPERATIONS, frontendBuild, MEDIA_UPLOAD_EXPORTS, PROMPT_COMPOSER_EXPORTS, readBuildLabel, withMutationAliases } from "./frontend_builds"; export { withMutationAliases }; import type { AgentAttachmentFormat, @@ -15,7 +15,9 @@ import type { CollectionWriteFormat, FrontendFormats, ProjectUploadFormat, + PromptComposerFormat, } from "./frontend_builds"; +import { resolveComposerControllers } from "./composer"; import { findProjectPage } from "./project_upload"; import { projectWriteChecks } from "./project_store"; import { legacyTile, pickTileUrl } from "./dom"; @@ -426,10 +428,60 @@ function operationStatus(result: FrontendCompatibility): { return { ok: result.ok, failed_checks: result.ok ? [] : result.failed_checks }; } +/** Checks the PromptState exports and live manual composer controller when configured. */ +function promptComposerCheck(format: PromptComposerFormat): StoreProbeCheck { + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const failed: string[] = []; + for (const name of PROMPT_COMPOSER_EXPORTS) { + const value = readOwn(namespace, format.exports[name]); + const ok = + name === "videoAspects" + ? Array.isArray(value) && value.length > 0 + : name === "aspectLabels" + ? value !== null && typeof value === "object" + : typeof value === "function"; + if (!ok) failed.push(name); + } + const stateCtor = readOwn(namespace, format.exports.promptState); + const proto = + typeof stateCtor === "function" + ? (stateCtor as { prototype?: unknown }).prototype + : null; + if (typeof readOwn(proto, "clear") !== "function") failed.push("clear"); + if (typeof readOwn(proto, "setAspectRatio") !== "function") { + failed.push("setAspectRatio"); + } + if (document.querySelector("flow-project-page")) { + const { qa } = resolveComposerControllers(false); + const model = readOwn(qa, "model"); + const items = readOwn(qa, format.items); + if (!qa) { + failed.push("qa"); + } else { + if (typeof readOwn(model, format.families) !== "function") { + failed.push("families"); + } + if (typeof readOwn(model, format.activeFamily) !== "function") { + failed.push("activeFamily"); + } + if (typeof readOwn(items, "all") !== "function") { + failed.push("items"); + } + } + } + return { + name: "prompt_composer", + ok: failed.length === 0, + detail: + failed.length === 0 ? "verified" : `missing ${failed.join(", ")}`, + }; +} + /** Reports the general store checks and compatibility of each managed operation. */ export function probeStore(): StoreProbeResult { const build = readBuildLabel(); const verified = buildCheck(build); + const verifiedBuild = frontendBuild(build); const liveStore = runtimeState.store?.isCurrent() ? runtimeState.store : null; const trashChecks = assetTrashChecks(liveStore?.getTileMap()); const views = runtimeState.ngLViewMap; @@ -441,6 +493,9 @@ export function probeStore(): StoreProbeResult { detail: views ? `${views.size} views` : "not captured", }, ...trashChecks, + ...(verifiedBuild?.promptComposer + ? [promptComposerCheck(verifiedBuild.promptComposer)] + : []), ]; const pageChecks = projectPageOperationChecks(build); const operations: Record< @@ -455,7 +510,7 @@ export function probeStore(): StoreProbeResult { character_bio: operationStatus(characterBioCompatibility()), asset_trash_store: operationStatus(assetTrashCompatibility()), }; - const formats = frontendBuild(build)?.operations; + const formats = verifiedBuild?.operations; const operationsOk = FRONTEND_OPERATIONS.every((name) => !formats?.[name] || operations[name].ok); return { build, diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..2b3d0be 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -13,6 +13,12 @@ import { findPromptBoxHost, settingsOpen, } from "./composer"; +import { + applyPromptComposerState, + buildAnchoredModelRegex, + buildDefinesPromptComposer, + normalizeComposerConfig, +} from "./composer_state"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; import { runtimeState } from "./state"; import type { GenerationConfig, NgLView } from "./types"; @@ -93,6 +99,52 @@ function clickByText( return false; } +/** Clicks a visible model family option whose primary label matches anchored `modelRe`. */ +function clickModelOption(modelRe: RegExp, scopeRoot: ParentNode): boolean { + const interactiveSel = + 'button, [role="option"], [role="menuitem"], [role="radio"]'; + const isExcludedButton = (el: Element): boolean => { + const aria = (el.getAttribute("aria-label") || "").trim(); + return aria === "Select model family" || aria === "Settings trigger"; + }; + const els = Array.from( + scopeRoot.querySelectorAll( + '.model-select-option, [role="option"], [role="menuitem"], [role="radio"], button', + ), + ); + const hit = els.find((el): el is HTMLElement => { + if (!isVisibleEnabled(el) || isExcludedButton(el)) return false; + if (!el.matches(interactiveSel)) { + const inner = el.querySelector(interactiveSel); + if (inner && (!isVisibleEnabled(inner) || isExcludedButton(inner))) { + return false; + } + } + const aria = (el.getAttribute("aria-label") || "").trim(); + const propLabel = (el.getAttribute("label") || "").trim(); + const raw = elText(el).trim(); + const lines = raw + .split(/\r?\n/) + .map((s) => s.trim()) + .filter(Boolean); + const firstLine = lines[0] || ""; + return ( + (Boolean(aria) && modelRe.test(aria)) || + (Boolean(propLabel) && modelRe.test(propLabel)) || + (Boolean(firstLine) && modelRe.test(firstLine)) || + (Boolean(raw) && modelRe.test(raw)) + ); + }); + if (!hit) return false; + const targetBtn = hit.matches(interactiveSel) + ? hit + : Array.from(hit.querySelectorAll(interactiveSel)).find( + (b): b is HTMLElement => isVisibleEnabled(b) && !isExcludedButton(b), + ) || hit; + targetBtn.click(); + return true; +} + /** Clicks a settings control matching `regex` within the labeled group container. */ function clickInsideGroup( groupLabel: string, @@ -228,6 +280,60 @@ async function ensureLViewCapture(allowSettingsClick = false): Promise { } } +/** Applies optional video duration and resolution controls inside the settings panel. */ +async function applyVideoDurationAndResolution( + cfg: GenerationConfig, + scope: ParentNode, +): Promise { + if (!cfg.duration && !cfg.resolution) return; + const settingsBtn = document.querySelector( + 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', + ); + if (isVisibleEnabled(settingsBtn) && !settingsOpen()) { + await withLViewMapCapture(async () => { + settingsBtn.click(); + await delay(180); + }); + } + const settingsScope = (): ParentNode => + document.querySelector( + "flow-prompt-box-settings, .settings-content-overlay", + ) || scope; + try { + if (cfg.resolution) { + const rRe = new RegExp(escapeRegex(String(cfg.resolution).trim()), "i"); + if (clickInsideGroup("Video resolution", rRe, settingsScope())) { + await delay(120); + } + } + } catch { + // Optional resolution control may be unavailable. + } + try { + if (cfg.duration) { + const rawDur = String(cfg.duration).replace(/s$/i, "").trim(); + const secs = Number.parseInt(rawDur, 10); + const curScope = settingsScope(); + if (Number.isFinite(secs) && (await setLengthSlider(secs, curScope))) { + await delay(160); + } else { + const d = escapeRegex(rawDur); + const hasDurGroup = Boolean( + document.querySelector('[aria-label*="Video duration" i]'), + ); + const durRe = hasDurGroup + ? new RegExp(`\\b${d}\\s*s\\b|\\b${d}\\b`, "i") + : new RegExp(`\\b${d}\\s*(?:s|sec)\\b`, "i"); + if (clickInsideGroup("Video duration", durRe, curScope)) { + await delay(120); + } + } + } + } catch { + // Optional duration control may be unavailable. + } +} + /** Configures generation mode, video type, aspect ratio, output count, duration, resolution, and model. */ export async function setupGeneration( cfg: GenerationConfig, @@ -235,14 +341,49 @@ export async function setupGeneration( const onEditPage = /\/edit\//.test(location.pathname || ""); if (!onEditPage) { + const checked = normalizeComposerConfig(cfg); + if (!checked.ok) { + return { ok: false, error: checked.error }; + } + const normalized = checked.config; + const textbox = await ensureManualComposer(); if (!textbox) return { ok: false, error: "manual_prompt_not_ready" }; + const scope = findComposerRoot(textbox); + + if (buildDefinesPromptComposer()) { + await ensureLViewCapture(false); + let direct = applyPromptComposerState(cfg); + if ( + !direct.ok && + !direct.fallback && + direct.error === "prompt_composer_unavailable" + ) { + await ensureLViewCapture(true); + direct = applyPromptComposerState(cfg); + } + if (direct.ok) { + if (normalized.modeCategory === "video" && (cfg.duration || cfg.resolution)) { + await applyVideoDurationAndResolution(cfg, scope); + } + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: true }; + } + if (!direct.fallback) { + if (settingsOpen()) { + await closeSettingsAndMenus(); + } + return { ok: false, error: direct.error }; + } + } + await ensureLViewCapture(true); const settingsBtn = document.querySelector( 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', ); - const scope = findComposerRoot(textbox); if (isVisibleEnabled(settingsBtn) && !settingsOpen()) { await withLViewMapCapture(async () => { @@ -255,8 +396,8 @@ export async function setupGeneration( document.querySelector( "flow-prompt-box-settings, .settings-content-overlay", ) || scope; - const mode = String(cfg.mode || "video").toLowerCase(); - if (mode === "image" || mode === "character" || mode === "scene") { + const mode = normalized.modeCategory; + if (mode === "image") { clickInsideGroup( "Mode", /\b(image|images|create image)\b/i, @@ -272,11 +413,11 @@ 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 (mode === "video" && normalized.videoType) { + const vtRe = + normalized.videoType === "ingredients" + ? /\bingredients?\b/i + : /\bframes?\b/i; if (clickInsideGroup("Video type", vtRe, settingsScope())) { await delay(120); } @@ -286,8 +427,8 @@ export async function setupGeneration( } try { - if (cfg.aspect) { - const a = String(cfg.aspect).trim(); + if (normalized.aspect) { + const a = normalized.aspect; const aspectRe = a === "16:9" ? /\b16:9\b|\blandscape\b/i @@ -305,8 +446,8 @@ export async function setupGeneration( } try { - if (cfg.count != null) { - const n = escapeRegex(String(cfg.count)); + if (normalized.count != null) { + const n = escapeRegex(String(normalized.count)); const countRe = new RegExp( `^(?:${n}|x${n}|${n}x|${n}\\s*(?:outputs?|results?|images?|videos?))$`, "i", @@ -355,12 +496,8 @@ export async function setupGeneration( } try { - if (cfg.model) { - const flexPattern = escapeRegex(String(cfg.model).trim()).replace( - /[-_\s]+/g, - "[\\s\\-_]*", - ); - const modelRe = new RegExp(flexPattern, "i"); + if (normalized.model) { + const modelRe = buildAnchoredModelRegex(normalized.model); const familyBtn = document.querySelector( 'button[aria-label="Select model family"]', ); @@ -381,11 +518,11 @@ export async function setupGeneration( if (pickerPane) break; } if (pickerPane) { - clickByText(modelRe, pickerPane, false); + clickModelOption(modelRe, pickerPane); } await delay(120); await closeModelMenu(); - } else if (clickByText(modelRe, settingsScope(), false)) { + } else if (clickModelOption(modelRe, settingsScope())) { await delay(120); } } @@ -395,7 +532,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 (mode === "video" && normalized.model) { if (cfg.resolution) { const rRe = new RegExp(escapeRegex(String(cfg.resolution).trim()), "i"); if (clickInsideGroup("Video resolution", rRe, settingsScope())) { @@ -419,28 +556,27 @@ export async function setupGeneration( findPromptBoxHost(findProjectPageInstance()), ); const curMode = String(liveUx?.Qa?.config?.mode?.() || ""); - const wantImageMode = - mode === "image" || mode === "character" || mode === "scene"; + const wantImageMode = mode === "image"; 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 (normalized.videoType) { + const vtRe = + normalized.videoType === "ingredients" + ? /\bingredients?\b/i + : /\bframes?\b/i; if (clickInsideGroup("Video type", vtRe, settingsScope())) { await delay(120); } } } if ( - cfg.count != null && + normalized.count != null && typeof liveUx?.Qa?.config?.outputCount === "function" && - Number(liveUx.Qa.config.outputCount()) !== Number(cfg.count) + Number(liveUx.Qa.config.outputCount()) !== normalized.count ) { const settingsEl = document.querySelector("flow-prompt-box-settings"); if (settingsEl) { @@ -463,9 +599,9 @@ export async function setupGeneration( ); if (iw) { if (typeof iw.Osa === "function") { - iw.Osa(Number(cfg.count)); + iw.Osa(normalized.count); } else if (typeof iw.Ula === "function") { - iw.Ula(Number(cfg.count)); + iw.Ula(normalized.count); } await delay(100); break; diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..b04985e 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -5,6 +5,11 @@ import { readAngularTooltip, readOwn, resolveLView } from "./angular"; import { findComposerWarning } from "./composer"; +import { + findPromptItemsDisableReason, + isPromptItemLoading, + readPromptItems, +} from "./composer_state"; import { delay, elText, isVisibleEnabled } from "./dom"; import { runtimeState } from "./state"; import type { NgLView } from "./types"; @@ -166,9 +171,34 @@ export async function submitGeneration(): Promise { return fallback ?? null; }; + const checkDisabledPromptItems = (): { + ok: false; + error: string; + detail: string; + } | null => { + const disableReason = findPromptItemsDisableReason( + readPromptItems(onEditPage), + ); + if (!disableReason) return null; + return { + ok: false, + error: `ingredient_disabled:${disableReason}`, + detail: disableReason, + }; + }; + for (let i = 0; i < 120; i += 1) { + const disabledItem = checkDisabledPromptItems(); + if (disabledItem) return disabledItem; + const items = readPromptItems(onEditPage); + if (items?.some(isPromptItemLoading)) { + await delay(100); + continue; + } const exact = findStartButton(); if (isVisibleEnabled(exact)) { + const recheckDisabled = checkDisabledPromptItems(); + if (recheckDisabled) return recheckDisabled; return await prepareTarget(exact, "aria_start_generation"); } const warning = checkWarning(); @@ -180,6 +210,9 @@ export async function submitGeneration(): Promise { } } + const disabledAfter = checkDisabledPromptItems(); + if (disabledAfter) return disabledAfter; + const warningAfter = checkWarning(); if (warningAfter) return warningAfter; diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..0612dd5 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -306,12 +306,40 @@ export interface PromptDocumentPayload { Te?: PromptTextSegment[]; } +/** Filtered model family option returned by `PromptState.model` signals. */ +export interface PromptModelOption { + /** Model family identifier in build 20261120.00. */ + hg?: string; + /** Human-readable model family name. */ + displayName?: string; + /** True when the model family is unavailable for the active tier or status. */ + isDisabled?: boolean; + /** Optional subtitle shown in the model family menu. */ + caption?: string; +} + +/** Raw model family descriptor in `MODEL_CONFIG`. */ +export interface PromptModelCatalogFamily { + /** Canonical family identifier. */ + id?: string; + /** Human-readable model family name. */ + displayName?: string; + /** Alternate model identifiers mapped to this family. */ + aliases?: string[]; + /** Media category (`"image"` or `"video"`). */ + type?: string; +} + /** Flow prompt validation and submission state controller. */ export interface PromptStateController { /** Applies serialized prompt segments in earlier builds. */ Wn?: (doc: PromptDocumentPayload) => void; /** Applies serialized prompt segments in build 20261120.00. */ Gp?: (doc: PromptDocumentPayload) => void; + /** Clears prompt segments, attached items, and inherited references. */ + clear?: () => void; + /** Sets the active native aspect ratio enum key (for example `"LANDSCAPE"`). */ + setAspectRatio?: (aspect: string) => void; /** Prompt text helper object. */ prompt?: { /** Returns true when the prompt is empty in earlier builds. */ @@ -322,12 +350,24 @@ 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. */ + Ff?: { isValid?: () => boolean; N7a?: () => string; S7a?: () => string }; + /** Mode, aspect ratio, and output count signals. */ config?: { mode?: () => string; + aspectRatio?: () => string; outputCount?: () => number; }; + /** Model family catalogue and selection signals. */ + model?: { + /** Filtered model options for the active mode in build 20261120.00. */ + Wqa?: () => PromptModelOption[]; + /** Active model family ID in build 20261120.00. */ + ala?: () => string | undefined; + /** Raw `MODEL_CONFIG` family descriptors for the active mode. */ + jx?: () => PromptModelCatalogFamily[]; + /** Active `MODEL_CONFIG` family descriptor. */ + family?: () => PromptModelCatalogFamily | undefined; + }; /** Attached item signal container in legacy builds. */ kc?: { all?: () => Array> }; /** Attached item signal container in build 20261120.00 and later. */ @@ -351,6 +391,12 @@ export type BooleanOverlaySignal = export interface BasePromptBoxInstance { /** Prompt state signal container. */ Qa?: PromptStateController; + /** Attachment uploader handle on the prompt box. */ + lW?: { nPa?: () => void } | null; + /** Output emitter notified when leading ingredient chips are deleted. */ + lF?: { emit?: (scope: string) => void }; + /** Signal returning an optional clear callback on the host. */ + C7?: () => (() => void) | undefined; /** Returns the rich editor wrapper in earlier builds. */ CQ?: () => RichTextEditorInstance | null | undefined; /** Returns the rich editor wrapper in build 20261120.00. */ diff --git a/xtask/src/contracts.rs b/xtask/src/contracts.rs index 94815b1..b78a368 100644 --- a/xtask/src/contracts.rs +++ b/xtask/src/contracts.rs @@ -103,6 +103,27 @@ const REQUIRED_AGENT_ATTACHMENT_EXPORTS: &[&str] = &[ "confirmUpload", ]; +/// Required `PromptComposerExport` keys on every `PromptComposerFormat` constant. +const REQUIRED_PROMPT_COMPOSER_EXPORTS: &[&str] = &[ + "promptState", + "setMode", + "setModel", + "setCount", + "aspectLabels", + "videoAspects", +]; + +/// Required string field keys on every `PromptComposerFormat` constant. +const REQUIRED_PROMPT_COMPOSER_FIELDS: &[&str] = &[ + "families", + "activeFamily", + "catalogFamilies", + "modelId", + "items", + "disableReason", + "clearOutput", +]; + /// Validates `VERIFIED_BUILDS`, export tables, and registered stores offline. pub(crate) fn check_flow_contracts(root: &Path) -> Vec { let mut errors = Vec::new(); @@ -142,6 +163,13 @@ pub(crate) fn check_flow_contracts(root: &Path) -> Vec { REQUIRED_AGENT_ATTACHMENT_EXPORTS, &mut errors, ); + check_string_array( + builds_rel, + &clean, + "PROMPT_COMPOSER_EXPORTS", + REQUIRED_PROMPT_COMPOSER_EXPORTS, + &mut errors, + ); check_typed_export_maps( builds_rel, @@ -164,6 +192,20 @@ pub(crate) fn check_flow_contracts(root: &Path) -> Vec { REQUIRED_AGENT_ATTACHMENT_EXPORTS, &mut errors, ); + check_typed_export_maps( + builds_rel, + &clean, + "PromptComposerFormat", + REQUIRED_PROMPT_COMPOSER_EXPORTS, + &mut errors, + ); + check_typed_string_fields( + builds_rel, + &clean, + "PromptComposerFormat", + REQUIRED_PROMPT_COMPOSER_FIELDS, + &mut errors, + ); let declared_stores = collect_typed_consts(&clean, "ProjectStoreFormat"); if declared_stores.is_empty() { @@ -171,13 +213,30 @@ pub(crate) fn check_flow_contracts(root: &Path) -> Vec { "{builds_rel}: no ProjectStoreFormat constants found" )); } + let declared_composers = collect_typed_consts(&clean, "PromptComposerFormat"); + if declared_composers.is_empty() { + errors.push(format!( + "{builds_rel}: no PromptComposerFormat constants found" + )); + } - let build_stores = check_verified_builds(builds_rel, &clean, &declared_stores, &mut errors); + let (build_stores, build_composers) = check_verified_builds( + builds_rel, + &clean, + &declared_stores, + &declared_composers, + &mut errors, + ); for store in declared_stores.difference(&build_stores) { errors.push(format!( "{builds_rel}: store `{store}` has no registered build" )); } + for composer in declared_composers.difference(&build_composers) { + errors.push(format!( + "{builds_rel}: promptComposer `{composer}` has no registered build" + )); + } let compat_rel = "ts/frontend_compatibility.ts"; let compat_path = root.join(compat_rel); @@ -525,29 +584,64 @@ fn check_typed_export_maps( } } -/// Validates every entry in `VERIFIED_BUILDS` and returns referenced `projectStore` names. +/// Verifies top-level string literal fields on every constant of type `type_name`. +fn check_typed_string_fields( + label: &str, + src: &str, + type_name: &str, + expected: &[&str], + errors: &mut Vec, +) { + for name in collect_typed_consts(src, type_name) { + let needle = format!("const {name}: {type_name}"); + let Some(pos) = src.find(&needle) else { + continue; + }; + let Some((obj_body, _)) = delimited_slice(src, pos + needle.len(), b'{', b'}') else { + continue; + }; + let entries = top_level_object_entries(obj_body); + for req in expected { + match entries.iter().find(|(k, _)| k == req) { + Some((_, val)) => { + let unquoted = val.trim_matches('"'); + if !val.starts_with('"') || !val.ends_with('"') || unquoted.is_empty() { + errors.push(format!( + "{label}: `{name}.{req}` must be a non-empty string literal" + )); + } + } + None => errors.push(format!("{label}: `{name}` omits required field `{req}`")), + } + } + } +} + +/// Validates every entry in `VERIFIED_BUILDS` and returns referenced stores and prompt composers. fn check_verified_builds( label: &str, src: &str, declared_stores: &BTreeSet, + declared_composers: &BTreeSet, errors: &mut Vec, -) -> BTreeSet { +) -> (BTreeSet, BTreeSet) { let mut used_stores = BTreeSet::new(); + let mut used_composers = BTreeSet::new(); let Some(pos) = src.find("const VERIFIED_BUILDS") else { errors.push(format!("{label}: missing `VERIFIED_BUILDS` map")); - return used_stores; + return (used_stores, used_composers); }; let Some(map_pos) = src[pos..].find("new Map") else { errors.push(format!( "{label}: `VERIFIED_BUILDS` must initialize `new Map([...])`" )); - return used_stores; + return (used_stores, used_composers); }; let Some((arr_body, _)) = delimited_slice(src, pos + map_pos, b'[', b']') else { errors.push(format!( "{label}: `VERIFIED_BUILDS` has no entry array literal" )); - return used_stores; + return (used_stores, used_composers); }; let mut cursor = 0usize; @@ -583,6 +677,15 @@ fn check_verified_builds( )), None => errors.push(format!("{label}: build `{build_id}` omits `projectStore`")), } + if let Some((_, composer_ident)) = fields.iter().find(|(k, _)| k == "promptComposer") { + if declared_composers.contains(composer_ident.as_str()) { + used_composers.insert(composer_ident.clone()); + } else { + errors.push(format!( + "{label}: build `{build_id}` references unknown promptComposer `{composer_ident}`" + )); + } + } let Some((_, ops_val)) = fields.iter().find(|(k, _)| k == "operations") else { errors.push(format!("{label}: build `{build_id}` omits `operations`")); continue; @@ -618,10 +721,10 @@ fn check_verified_builds( if build_count == 0 { errors.push(format!("{label}: `VERIFIED_BUILDS` must not be empty")); } - used_stores + (used_stores, used_composers) } -/// Verifies that `probeStore()` checks all seven managed operations and build verification. +/// Verifies that `probeStore()` checks managed operations, `promptComposer`, and build status. fn check_probe_store(label: &str, src: &str, errors: &mut Vec) { let Some(fn_pos) = src.find("export function probeStore") else { errors.push(format!("{label}: missing `export function probeStore`")); @@ -639,6 +742,11 @@ fn check_probe_store(label: &str, src: &str, errors: &mut Vec) { )); } } + if !fn_body.contains("promptComposerCheck") { + errors.push(format!( + "{label}: `probeStore` omits runtime check for `promptComposer`" + )); + } if !fn_body.contains("FRONTEND_OPERATIONS.every") { errors.push(format!( "{label}: `probeStore` must require all `FRONTEND_OPERATIONS` in top-level `ok`"