diff --git a/src/edit.rs b/src/edit.rs new file mode 100644 index 0000000..821a7b5 --- /dev/null +++ b/src/edit.rs @@ -0,0 +1,180 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Google Flow asset editing workflow. +//! +//! Opens the asset editor through the browser runtime, submits edit prompts, and tracks updated +//! outputs. + +use anyhow::{Context, Result}; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::json; +use std::collections::HashSet; +use tokio::time::Duration; + +use crate::assets::{list_assets_with_project, match_asset}; +use crate::db::FlowDb; +use crate::engine::ChromeEngine; +use crate::generation::{ + AssetWaitSpec, WatchedAsset, apply_generation_controls, collect_created_assets, + format_submit_progress, wait_for_new_assets, +}; +use crate::project::{ensure_flow_store, ensure_project_workspace_root}; +use crate::queue::{ProgressCallback, SceneParams}; + +/// Parameters for `flow_edit`. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub(crate) struct EditParams { + /// Case-insensitive asset ID, name, or prompt substring that selects the source asset. + #[serde(rename = "match")] + pub(crate) r#match: String, + /// Edit prompt for the matched asset. + pub(crate) prompt: String, +} + +/// Exits any editor subroute and returns an error when `openEditAsset` reports a blocking alert. +async fn check_open_edit_errors( + engine: &ChromeEngine, + open_res: &serde_json::Value, + label: &str, +) -> Result<()> { + if let Some(alert) = open_res + .get("alert") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!("Flow cannot edit '{}': {}", label, alert); + } + Ok(()) +} + +/// Opens an edit flow for an asset that matches `match_str`, submits `prompt`, and downloads/indexes outputs. +pub(crate) async fn run_edit( + engine: &ChromeEngine, + db: &FlowDb, + match_str: &str, + prompt: &str, + on_progress: ProgressCallback, +) -> Result<(Vec, Vec, Vec)> { + ensure_project_workspace_root(engine).await?; + let snap = list_assets_with_project(engine).await?; + let target = match_asset(&snap.assets, match_str, true) + .cloned() + .with_context(|| format!("No asset matches '{}' for edit", match_str))?; + match target.kind.as_str() { + "scene" if target.duration.is_none() => anyhow::bail!( + "Cannot edit scene '{}' without a duration; pass a video asset ID to flow_edit.", + target.id + ), + "character" => anyhow::bail!( + "Cannot edit character '{}' with flow_edit; use flow_character_edit instead.", + target.id + ), + "audio" => anyhow::bail!("Cannot edit audio asset '{}' with flow_edit.", target.id), + _ => {} + } + let before: HashSet = snap.assets.into_iter().map(|a| a.id).collect(); + + let label = if target.name.is_empty() { + target.id.clone() + } else { + target.name.clone() + }; + on_progress(format!("preparing edit for {}", label)); + + let edit_mode = + if target.kind == "video" || (target.kind == "scene" && target.duration.is_some()) { + "video" + } else { + "image" + }; + + let open_args = json!([target.id, target.url, target.primary_media_id]); + let mut open_res = engine + .call_flow_async("openEditAsset", open_args.clone()) + .await + .unwrap_or_default(); + check_open_edit_errors(engine, &open_res, &label).await?; + let is_editor_open = |res: &serde_json::Value| { + res.get("opened").and_then(|v| v.as_bool()) == Some(true) + && res.get("has_textbox").and_then(|v| v.as_bool()) == Some(true) + }; + let mut opened_in_ui = is_editor_open(&open_res); + + if !opened_in_ui && let Some(edit_url) = open_res.get("edit_url").and_then(|v| v.as_str()) { + engine.navigate(edit_url).await?; + tokio::time::sleep(Duration::from_millis(1200)).await; + let _ = ensure_flow_store(engine).await; + open_res = engine + .call_flow_async("openEditAsset", open_args) + .await + .unwrap_or_default(); + check_open_edit_errors(engine, &open_res, &label).await?; + opened_in_ui = is_editor_open(&open_res); + } else if opened_in_ui { + let _ = ensure_flow_store(engine).await; + } + + if !opened_in_ui { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!( + "Could not open an edit prompt box for {} asset '{}'", + edit_mode, + label + ); + } + + let cur_url = engine.current_url().await.unwrap_or_default(); + let in_edit_route = cur_url.contains("/edit/") || cur_url.contains("/scene/"); + on_progress(format!("submitting edit for {}", label)); + let scene = SceneParams { + prompt: prompt.to_string(), + mode: if in_edit_route { + None + } else { + Some(edit_mode.to_string()) + }, + frames: None, + count: Some(1), + ..Default::default() + }; + let mut net_rx = engine.subscribe_network().await?; + let submit_res = apply_generation_controls(engine, &scene).await?; + let submit_summary = format_submit_progress("submitted edit", &submit_res); + on_progress(submit_summary.clone()); + + let target_was_failed = matches!(target.media_status.as_deref(), Some("failed" | "canceled")); + let (created, project_id, project_title) = wait_for_new_assets( + engine, + AssetWaitSpec { + before_ids: &before, + watch_updated: Some(WatchedAsset { + id: target.id.as_str(), + primary_media_id: target.primary_media_id.as_deref(), + url: target.url.as_deref(), + prev_media_error: target.media_error.as_deref(), + prev_created_at: target.created_at.as_deref(), + was_failed: target_was_failed, + }), + expected_count: 1, + timeout_secs: 420, + submit_summary: &submit_summary, + }, + &mut net_rx, + &on_progress, + ) + .await?; + ensure_project_workspace_root(engine).await?; + Ok(collect_created_assets( + engine, + db, + created, + project_id, + project_title, + true, + &on_progress, + ) + .await) +} diff --git a/src/generation.rs b/src/generation.rs index b9f3f55..c90640e 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -14,7 +14,7 @@ use std::collections::HashSet; use tokio::sync::broadcast; use tokio::time::{Duration, Instant}; -use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; +use crate::assets::{FlowAsset, list_assets_with_project}; use crate::db::FlowDb; use crate::download::download_resolved_asset; use crate::engine::{ChromeEngine, NetworkResponseEvent, validate_local_files}; @@ -63,32 +63,39 @@ pub(crate) struct GenerateParams { pub(crate) resolution: Option, } -/// Parameters for `flow_edit`. -#[derive(Debug, Clone, Deserialize, JsonSchema)] -pub(crate) struct EditParams { - /// Case-insensitive asset ID, name, or prompt substring that selects the source asset. - #[serde(rename = "match")] - pub(crate) r#match: String, - /// Edit prompt for the matched asset. - pub(crate) prompt: String, +/// Baseline state of an existing asset watched for edit updates or failures. +#[derive(Clone, Copy)] +pub(crate) struct WatchedAsset<'a> { + /// Asset workflow ID. + pub(crate) id: &'a str, + /// Primary media ID before edit submission. + pub(crate) primary_media_id: Option<&'a str>, + /// Resolved media URL before edit submission. + pub(crate) url: Option<&'a str>, + /// Primary failure description recorded before edit submission. + pub(crate) prev_media_error: Option<&'a str>, + /// ISO creation timestamp recorded before edit submission. + pub(crate) prev_created_at: Option<&'a str>, + /// True when the primary media already reported a failed or canceled status before submission. + pub(crate) was_failed: bool, } /// Specification controlling asset polling during generation and edit jobs. -struct AssetWaitSpec<'a> { +pub(crate) struct AssetWaitSpec<'a> { /// Asset IDs already present before submission. - before_ids: &'a HashSet, - /// Optional existing tile `(asset_id, primary_media_id, url)` watched for replacement updates. - watch_updated: Option<(&'a str, Option<&'a str>, Option<&'a str>)>, + pub(crate) before_ids: &'a HashSet, + /// Optional existing tile watched for replacement updates or variant failures. + pub(crate) watch_updated: Option>, /// Target number of generated outputs in the batch. - expected_count: usize, + pub(crate) expected_count: usize, /// Maximum wait time in seconds before failing with timeout. - timeout_secs: u64, + pub(crate) timeout_secs: u64, /// Compact submission diagnostics included in progress updates. - submit_summary: &'a str, + pub(crate) submit_summary: &'a str, } /// Configures generation controls, uploads reference frames, writes prompt text, and submits. -async fn apply_generation_controls( +pub(crate) async fn apply_generation_controls( engine: &ChromeEngine, scene: &SceneParams, ) -> Result { @@ -226,7 +233,7 @@ async fn apply_generation_controls( } /// Formats compact setup and submit diagnostics for generation progress logs. -fn format_submit_progress(prefix: &str, submit_res: &serde_json::Value) -> String { +pub(crate) fn format_submit_progress(prefix: &str, submit_res: &serde_json::Value) -> String { fn str_or<'a>(obj: Option<&'a serde_json::Value>, key: &str, fallback: &'a str) -> &'a str { obj.and_then(|v| v.get(key)) .and_then(|v| v.as_str()) @@ -323,7 +330,7 @@ pub(crate) fn inspect_generation_network( } /// Polls project snapshots until expected generated outputs resolve or fail. -async fn wait_for_new_assets( +pub(crate) async fn wait_for_new_assets( engine: &ChromeEngine, spec: AssetWaitSpec<'_>, net_rx: &mut broadcast::Receiver, @@ -335,6 +342,8 @@ async fn wait_for_new_assets( let mut accepted_status: Option = None; let mut last_pending_count = 0usize; let mut last_pending_info = String::from("none"); + let mut watched_restarted = false; + let mut stalled_failed_polls = 0u32; while Instant::now() < deadline { tokio::time::sleep(Duration::from_secs(3)).await; @@ -363,15 +372,15 @@ async fn wait_for_new_assets( if !spec.before_ids.contains(&a.id) && a.url.is_some() { return true; } - if let Some((tid, prev_pmid, prev_url)) = spec.watch_updated - && a.id == tid + if let Some(watched) = spec.watch_updated + && a.id == watched.id && a.url.is_some() { let pmid_changed = a .primary_media_id .as_deref() - .is_some_and(|p| Some(p) != prev_pmid); - let url_changed = a.url.as_deref() != prev_url; + .is_some_and(|p| Some(p) != watched.primary_media_id); + let url_changed = a.url.as_deref() != watched.url; return pmid_changed || url_changed; } false @@ -387,10 +396,10 @@ async fn wait_for_new_assets( .collect(); last_pending_count = new_tiles.len(); last_pending_info = if new_tiles.is_empty() { - if let Some((tid, _, _)) = spec.watch_updated { + if let Some(watched) = spec.watch_updated { snap.assets .iter() - .find(|a| a.id == tid) + .find(|a| a.id == watched.id) .map(|a| { format!("{}:{}", a.id, a.media_status.as_deref().unwrap_or("none")) }) @@ -420,20 +429,44 @@ async fn wait_for_new_assets( .unwrap_or(first.media_status.as_deref().unwrap_or("failed")) ); } - if let Some((tid, prev_pmid, _)) = spec.watch_updated - && let Some(watched) = snap.assets.iter().find(|a| a.id == tid) - && matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) - && (watched.primary_media_id.as_deref() != prev_pmid - || watched.media_error.is_some()) + if let Some(w) = spec.watch_updated + && let Some(watched) = snap.assets.iter().find(|a| a.id == w.id) { - anyhow::bail!( - "Flow edit failed on {}: {}", - tid, - watched - .media_error - .as_deref() - .unwrap_or(watched.media_status.as_deref().unwrap_or("failed")) - ); + let cur_failed = + matches!(watched.media_status.as_deref(), Some("failed" | "canceled")); + if !cur_failed { + watched_restarted = true; + stalled_failed_polls = 0; + } else if new_tiles.is_empty() { + stalled_failed_polls += 1; + } else { + stalled_failed_polls = 0; + } + let primary_changed = watched + .primary_media_id + .as_deref() + .is_some_and(|cur| Some(cur) != w.primary_media_id); + let error_changed = watched.media_error.as_deref() != w.prev_media_error; + let timestamp_changed = watched.created_at.as_deref() != w.prev_created_at; + let stalled_refailure = (accepted_status.is_some() && stalled_failed_polls >= 2) + || stalled_failed_polls >= 4; + if cur_failed + && (!w.was_failed + || watched_restarted + || primary_changed + || error_changed + || timestamp_changed + || stalled_refailure) + { + anyhow::bail!( + "Flow edit failed on {}: {}", + w.id, + watched + .media_error + .as_deref() + .unwrap_or(watched.media_status.as_deref().unwrap_or("failed")) + ); + } } } @@ -594,134 +627,3 @@ pub(crate) async fn run_generation( ) .await) } - -/// Opens an edit flow for an asset that matches `match_str`, submits `prompt`, and downloads/indexes outputs. -pub(crate) async fn run_edit( - engine: &ChromeEngine, - db: &FlowDb, - match_str: &str, - prompt: &str, - on_progress: ProgressCallback, -) -> Result<(Vec, Vec, Vec)> { - ensure_project_workspace_root(engine).await?; - let snap = list_assets_with_project(engine).await?; - let target = match_asset(&snap.assets, match_str, true) - .cloned() - .with_context(|| format!("No asset matches '{}' for edit", match_str))?; - let before: HashSet = snap.assets.into_iter().map(|a| a.id).collect(); - - let label = if target.name.is_empty() { - target.id.clone() - } else { - target.name.clone() - }; - on_progress(format!("preparing edit for {}", label)); - - let edit_mode = - if target.kind == "video" || (target.kind == "scene" && target.duration.is_some()) { - "video" - } else { - "image" - }; - - let open_res = engine - .call_flow_async( - "openEditAsset", - json!([target.id, target.url, target.primary_media_id]), - ) - .await - .unwrap_or_default(); - let mut opened_in_ui = open_res - .get("opened") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - if !opened_in_ui { - if let Some(edit_url) = open_res.get("edit_url").and_then(|v| v.as_str()) { - engine.navigate(edit_url).await?; - tokio::time::sleep(Duration::from_millis(1200)).await; - ensure_flow_store(engine).await?; - opened_in_ui = true; - } - } else { - let _ = ensure_flow_store(engine).await; - } - - let mut attached_frames: Option> = None; - if !opened_in_ui { - if edit_mode == "video" { - anyhow::bail!( - "Could not open an inline edit control or /edit/ route for video asset '{}'", - label - ); - } - if target.url.is_some() || target.primary_media_id.is_some() { - let local_path = - if let Some(cached) = db.find_existing_file_for_asset(&target.id).await? { - cached.file_path - } else { - let downloaded = download_resolved_asset( - engine, - db, - &target, - snap.project_id.clone(), - snap.project_title.clone(), - ) - .await?; - downloaded.file_path - }; - attached_frames = Some(vec![local_path]); - } - } - - let in_edit_route = engine - .current_url() - .await - .unwrap_or_default() - .contains("/edit/"); - on_progress(format!("submitting edit for {}", label)); - let scene = SceneParams { - prompt: prompt.to_string(), - mode: if in_edit_route { - None - } else { - Some(edit_mode.to_string()) - }, - frames: attached_frames, - count: Some(1), - ..Default::default() - }; - let mut net_rx = engine.subscribe_network().await?; - let submit_res = apply_generation_controls(engine, &scene).await?; - let submit_summary = format_submit_progress("submitted edit", &submit_res); - on_progress(submit_summary.clone()); - - let (created, project_id, project_title) = wait_for_new_assets( - engine, - AssetWaitSpec { - before_ids: &before, - watch_updated: Some(( - target.id.as_str(), - target.primary_media_id.as_deref(), - target.url.as_deref(), - )), - expected_count: 1, - timeout_secs: 420, - submit_summary: &submit_summary, - }, - &mut net_rx, - &on_progress, - ) - .await?; - ensure_project_workspace_root(engine).await?; - Ok(collect_created_assets( - engine, - db, - created, - project_id, - project_title, - true, - &on_progress, - ) - .await) -} diff --git a/src/main.rs b/src/main.rs index d180c44..781b9b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ mod config; mod cookies; mod db; mod download; +mod edit; mod engine; mod generation; mod http; diff --git a/src/mcp.rs b/src/mcp.rs index 2a0eef9..cdfcd36 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -27,7 +27,8 @@ use crate::auth::LoginParams; use crate::characters::{CharacterEditParams, CharacterParams, VoicesParams}; use crate::collections::CollectionsParams; use crate::db::{DOWNLOAD_ASSET_RESOURCE_PREFIX, DOWNLOAD_RESOURCE_PREFIX, DownloadsParams}; -use crate::generation::{EditParams, GenerateParams}; +use crate::edit::EditParams; +use crate::generation::GenerateParams; use crate::project::{NewProjectParams, ProjectsParams, StatusParams}; use crate::queue::{JobIdParams, WaitParams}; use crate::scenes::{ScenesParams, VideoParams}; diff --git a/src/service.rs b/src/service.rs index 4b8223b..9e043d0 100644 --- a/src/service.rs +++ b/src/service.rs @@ -20,8 +20,9 @@ use crate::db::{ FlowDb, effective_mime_type, }; use crate::download; +use crate::edit::{self, EditParams}; use crate::engine::{ChromeEngine, ENGINE_NAME}; -use crate::generation::{self, EditParams, GenerateParams}; +use crate::generation::{self, GenerateParams}; use crate::media_files; use crate::project::{self, ProjectsParams}; use crate::queue::{JobQueue, JobResult, JobRunner, JobView, SceneParams, WaitParams}; @@ -94,8 +95,7 @@ impl FlowService { ) .await? } else if let Some(ref edit_from) = scene.edit_from { - generation::run_edit(&engine, &db, edit_from, &scene.prompt, on_progress) - .await? + edit::run_edit(&engine, &db, edit_from, &scene.prompt, on_progress).await? } else if scene.character.is_some() { let is_edit = scene.character_edit.unwrap_or(false); characters::create_or_update_character_job( diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index dc2d23e..d0af9d4 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -19,6 +19,8 @@ import { findProjectPageInstance, findPromptBoxHost, findTextbox, + isEditOrSceneRoute, + NON_COMPOSER_PANELS, settingsOpen, } from "./composer"; import { @@ -32,9 +34,10 @@ import { pickTileUrl, setNativeValue, } from "./dom"; +import { characterPreviewFormat, promptComposerFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; import { runtimeState } from "./state"; -import type { FlowTile, GenerationConfig, NgLView } from "./types"; +import type { FlowTile, GenerationConfig, NgLView, PromptStateController } from "./types"; /** Normalized target ingredient asset or character descriptor. */ interface IngredientTarget { @@ -93,7 +96,7 @@ function framesReady(items: unknown[] | null, targets: IngredientTarget[]): bool /** 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 onEditPage = isEditOrSceneRoute(); const ingredientTargets: IngredientTarget[] = []; const tileMap = runtimeState.store?.getTileMap?.(); @@ -250,7 +253,9 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ) { const tipEls = Array.from( document.querySelectorAll("[mattooltip], button[aria-label]"), - ).slice(0, 8); + ) + .filter((el) => !el.closest(NON_COMPOSER_PANELS)) + .slice(0, 8); await withLViewMapCapture(async () => { await hoverProbe(tipEls, 50); }); @@ -264,18 +269,23 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ...(scope && scope !== document && scope !== promptBoxEl ? [scope] : []), document, ]; + const fmt = promptComposerFormat(); const initialPage = !onEditPage ? findProjectPageInstance() : null; const initialUx = !onEditPage ? findLiveBasePromptBox(false, findPromptBoxHost(initialPage)) : null; + const initialUxState = readOwn(initialUx, fmt.promptState) as PromptStateController | undefined; const initialQaMode = String( - initialPage?.Oa?.config?.mode?.() || initialPage?.Qa?.config?.mode?.() || - initialUx?.Qa?.config?.mode?.() || "", + initialPage?.Oa?.config?.mode?.() || + initialPage?.Qa?.config?.mode?.() || + initialUxState?.config?.mode?.() || + "", ); const hasAddIngredientsBtn = ingSearchRoots.some((root) => Array.from(root.querySelectorAll('button, [role="button"]')).some( (el) => isVisibleEnabled(el) && + !el.closest(NON_COMPOSER_PANELS) && /add ingredients to the prompt box|\bingredients\b/i.test( ( el.getAttribute("aria-label") || @@ -290,6 +300,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise Array.from(root.querySelectorAll('button, [role="button"]')).some( (el) => isVisibleEnabled(el) && + !el.closest(NON_COMPOSER_PANELS) && /^(?:start|end)$/i.test( (el.getAttribute("aria-label") || elText(el)).trim(), ), @@ -342,7 +353,9 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ingBtn = Array.from(root.querySelectorAll('button, [role="button"]')).find( (el): el is HTMLElement => { - if (!isVisibleEnabled(el)) return false; + if (!isVisibleEnabled(el) || el.closest(NON_COMPOSER_PANELS)) { + return false; + } const label = ( el.getAttribute("aria-label") || elText(el) || @@ -359,7 +372,9 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ingBtn = Array.from(root.querySelectorAll('button, [role="button"]')).find( (el): el is HTMLElement => { - if (!isVisibleEnabled(el)) return false; + if (!isVisibleEnabled(el) || el.closest(NON_COMPOSER_PANELS)) { + return false; + } const label = ( el.getAttribute("aria-label") || elText(el) || @@ -416,28 +431,25 @@ export async function attachIngredients(cfg: GenerationConfig): Promise }; let attached = false; + const popFmt = characterPreviewFormat(); const popEl = overlay.querySelector("flow-add-menu-popover-content") || document.querySelector("flow-add-menu-popover-content"); interface PopoverComponent { isPending?: () => boolean; - ka?: () => unknown[]; - Hi?: ((item?: unknown) => unknown) | undefined; - r9?: (item: unknown) => void; - Qda?: (item: unknown) => void; } + const readPopSelect = (cand: unknown): ((item: unknown) => unknown) | null => { + for (const key of [popFmt.pickerSelect, "r9", "Hi"]) { + const fn = readOwn(cand, key); + if (typeof fn === "function") return fn as (item: unknown) => unknown; + } + return null; + }; if (popEl) { const findPopInst = (lv: NgLView | null): PopoverComponent | null => { if (!Array.isArray(lv)) return null; for (const cand of lv) { - if ( - cand && - typeof cand === "object" && - !(cand instanceof Node) && - (typeof (cand as PopoverComponent).Qda === "function" || - typeof (cand as PopoverComponent).r9 === "function" || - typeof (cand as PopoverComponent).Hi === "function") - ) { + if (cand && typeof cand === "object" && !(cand instanceof Node) && readPopSelect(cand)) { return cand as PopoverComponent; } } @@ -465,10 +477,12 @@ export async function attachIngredients(cfg: GenerationConfig): Promise break; } } + const readAssets = + readOwn(popInst, popFmt.pickerAssets) ?? + readOwn(popInst, "ka") ?? + readOwn(popInst, "Hi"); const pool = - (typeof popInst.ka === "function" ? popInst.ka() : null) || - (typeof popInst.Hi === "function" ? popInst.Hi() : null) || - []; + typeof readAssets === "function" ? readAssets.call(popInst) : []; const m = Array.isArray(pool) ? pool.find((a) => pickerAssetMatches(a, matchTarget)) || (lowName @@ -481,18 +495,11 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ) : null) : null; - if (m) { - if (typeof popInst.Qda === "function") { - popInst.Qda(m); - attached = true; - } else if (typeof popInst.r9 === "function") { - popInst.r9(m); - attached = true; - } else if (typeof popInst.Hi === "function") { - popInst.Hi(m); - attached = true; - } - if (attached) await delay(180); + const selectAsset = readPopSelect(popInst); + if (m && selectAsset) { + selectAsset.call(popInst, m); + attached = true; + await delay(180); } } } @@ -600,27 +607,27 @@ export async function attachIngredients(cfg: GenerationConfig): Promise const promptHost = !onEditPage ? findPromptBoxHost(findProjectPageInstance()) : null; - const composerSeeds = onEditPage - ? [ - document.querySelector("flow-edit-video-prompt-box"), - document.querySelector("flow-editor-page flow-rich-text-editor"), - document.querySelector("flow-scene-builder flow-rich-text-editor"), - document.querySelector("flow-rich-text-editor"), - ] - : [ - document.querySelector( - "flow-prompt-box flow-base-prompt-box flow-rich-text-editor", - ), - document.querySelector("flow-prompt-box flow-base-prompt-box"), - document.querySelector("flow-prompt-box flow-rich-text-editor"), - ]; + const composerSeeds = ( + onEditPage + ? [ + document.querySelector("flow-edit-image-prompt-box"), + document.querySelector("flow-edit-video-prompt-box"), + document.querySelector("flow-editor-page flow-rich-text-editor"), + document.querySelector("flow-scene-builder flow-rich-text-editor"), + document.querySelector("flow-rich-text-editor"), + ] + : [ + document.querySelector( + "flow-prompt-box flow-base-prompt-box flow-rich-text-editor", + ), + document.querySelector("flow-prompt-box flow-base-prompt-box"), + document.querySelector("flow-prompt-box flow-rich-text-editor"), + ] + ).filter((el): el is Element => Boolean(el && !el.closest(NON_COMPOSER_PANELS))); 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: NON_COMPOSER_PANELS, strictSync: true, onCloseSettings: closeSettingsAndMenus, }); @@ -631,6 +638,10 @@ export async function attachIngredients(cfg: GenerationConfig): Promise ? findPromptBoxHost(findProjectPageInstance()) : null; const finalUx = findLiveBasePromptBox(onEditPage, finalHost); + const finalState = readOwn(finalUx, fmt.promptState) as PromptStateController | undefined; + const hostIsAgentFn = readOwn(finalHost, fmt.hostIsAgent); + const promptEmptyFn = readOwn(finalState?.prompt, fmt.promptEmpty); + const canSubmitFn = readOwn(finalUx, fmt.canSubmit); const tbLen = (tb instanceof HTMLTextAreaElement || tb instanceof HTMLInputElement ? tb.value @@ -638,32 +649,26 @@ export async function attachIngredients(cfg: GenerationConfig): Promise return { ok: true, composer: - tb - .closest( - "flow-edit-video-prompt-box, flow-creative-agent-prompt-box, flow-agent-panel, flow-base-prompt-box", - ) - ?.tagName?.toLowerCase() || null, + ( + tb.closest( + "flow-edit-image-prompt-box, flow-edit-video-prompt-box, flow-creative-agent-prompt-box, flow-agent-panel", + ) ?? tb.closest("flow-base-prompt-box") + )?.tagName?.toLowerCase() || null, prompt_tier: writeInfo.tier, prompt_len: tbLen.length, settings_open: Boolean(!onEditPage && settingsOpen()), sk_agent: - typeof finalHost?.Nl === "function" - ? Boolean(finalHost.Nl()) - : typeof finalHost?.Sk === "function" - ? Boolean(finalHost.Sk()) - : null, - qa_mode: finalUx?.Qa?.config?.mode?.() || null, + typeof hostIsAgentFn === "function" + ? Boolean(hostIsAgentFn.call(finalHost)) + : null, + qa_mode: finalState?.config?.mode?.() || null, prompt_empty: - typeof finalUx?.Qa?.prompt?.Ke === "function" - ? Boolean(finalUx.Qa.prompt.Ke()) - : typeof finalUx?.Qa?.prompt?.Le === "function" - ? Boolean(finalUx.Qa.prompt.Le()) - : null, + typeof promptEmptyFn === "function" + ? Boolean(promptEmptyFn.call(finalState?.prompt)) + : null, qf: - typeof finalUx?.wf === "function" - ? Boolean(finalUx.wf()) - : typeof finalUx?.qf === "function" - ? Boolean(finalUx.qf()) - : null, + typeof canSubmitFn === "function" + ? Boolean(canSubmitFn.call(finalUx)) + : null, }; } diff --git a/ts/composer.ts b/ts/composer.ts index 49d5a5e..9adb426 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -5,10 +5,11 @@ import { isLiveLView, readAngularTooltip, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { frontendBuild, promptComposerFormat, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; import type { BasePromptBoxInstance, + BooleanOverlaySignal, NgLView, ProjectPageInstance, PromptBoxHost, @@ -18,8 +19,20 @@ import type { 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"; +/** Non-composer panels excluded from manual and edit prompt queries on all routes. */ +export const NON_COMPOSER_PANELS = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box, flow-applet-chat-sidebar, flow-applet-prompt-box, flow-editor-side-panel, flow-editor-history-panel, flow-comments-panel, .embedded-comments-panel, flow-comment-region-overlay, flow-comment-timeline-lane"; + +/** Host elements for image and video edit prompt boxes. */ +export const EDIT_PROMPT_BOX_SELECTOR = + "flow-edit-image-prompt-box, flow-edit-video-prompt-box"; + +/** Returns true when `pathname` is an asset editor or scene builder route. */ +export function isEditOrSceneRoute( + pathname: string = location.pathname || "", +): boolean { + return /\/(?:edit|scene)\//.test(pathname); +} /** Detected quota or high-demand warning button inside a Flow composer. */ export interface ComposerWarning { @@ -29,22 +42,36 @@ export interface ComposerWarning { detail: string; } -/** Finds a visible textbox in a composer root. */ -function composerTextbox(root: ParentNode | null, edit: boolean): HTMLElement | null { +/** Finds a visible textbox in a composer root outside Agent, side, and comment panels. */ +function composerTextbox(root: ParentNode | null): HTMLElement | null { 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)), + el instanceof HTMLElement && + el.getClientRects().length > 0 && + !isDisabledProp(el) && + !el.closest(NON_COMPOSER_PANELS), ) ?? null; } /** Finds the active visible prompt textbox for generation or edit composers. */ export function findTextbox(editFlag: boolean): HTMLElement | null { - const scopedSelector = editFlag - ? "flow-edit-video-prompt-box, flow-editor-page, flow-scene-builder" - : "flow-prompt-box flow-base-prompt-box, flow-prompt-box"; - return composerTextbox(document.querySelector(scopedSelector), editFlag) || - composerTextbox(document, editFlag); + const roots = editFlag + ? [ + ...Array.from(document.querySelectorAll(EDIT_PROMPT_BOX_SELECTOR)), + ...Array.from( + document.querySelectorAll("flow-editor-page, flow-scene-builder"), + ), + ] + : Array.from( + document.querySelectorAll( + "flow-prompt-box flow-base-prompt-box, flow-prompt-box", + ), + ); + for (const root of roots) { + const hit = composerTextbox(root); + if (hit) return hit; + } + return composerTextbox(document); } /** Closes the active Agent panel and waits for the manual prompt to become editable. */ @@ -53,7 +80,7 @@ export async function ensureManualComposer(): Promise { const hosts = new WeakSet(); for (let attempt = 0; attempt < 40; attempt++) { const prompt = document.querySelector("flow-prompt-box"); - const textbox = composerTextbox(prompt, false); + const textbox = composerTextbox(prompt); if (textbox) return textbox; const panel = document.querySelector("flow-agent-panel, .agent-panel-wrapper"); @@ -82,15 +109,11 @@ export async function ensureManualComposer(): Promise { if (host && !hosts.has(host)) { hosts.add(host); try { - const inAgent = - typeof host.Nl === "function" - ? host.Nl() - : typeof host.Sk === "function" - ? host.Sk() - : false; - if (inAgent) { - if (typeof host.Xu === "function") host.Xu(); - else if (typeof host.Tx === "function") host.Tx(); + const fmt = promptComposerFormat(); + const isAgentFn = readOwn(host, fmt.hostIsAgent); + const toggleFn = readOwn(host, fmt.hostToggleAgent); + if (typeof isAgentFn === "function" && isAgentFn.call(host) && typeof toggleFn === "function") { + toggleFn.call(host); } } catch { // Wait for the prompt box if its required inputs are still loading. @@ -104,6 +127,7 @@ export async function ensureManualComposer(): Promise { /** Finds the live `flow-project-page` Angular component instance. */ export function findProjectPageInstance(): ProjectPageInstance | null { + const fmt = promptComposerFormat(); const pageName = frontendBuild(readBuildLabel())?.operations.project_upload?.page.page ?? "uu"; const pageCtor = readOwn(readOwn(window, "default_AiSandboxAngularFrontend"), pageName); const isProjPage = (cand: unknown): cand is ProjectPageInstance => { @@ -111,9 +135,9 @@ export function findProjectPageInstance(): ProjectPageInstance | null { if (typeof pageCtor === "function" && cand instanceof pageCtor) return true; const obj = cand as Partial; return ( - (Boolean(obj.Qa) && + (Boolean(readOwn(cand, fmt.promptState)) && (typeof obj.he?.mutate === "function" || typeof obj.ub?.mutate === "function")) || - typeof obj.NF === "function" || typeof obj.jQ === "function" + typeof readOwn(cand, fmt.pagePromptHost) === "function" ); }; const scanLv = (lv: unknown): ProjectPageInstance | null => @@ -141,23 +165,18 @@ export function findProjectPageInstance(): ProjectPageInstance | null { /** Type guard for the Angular prompt box host managing manual/agent toggle state. */ function isPromptBoxHost(cand: unknown): cand is PromptBoxHost { if (!cand || typeof cand !== "object" || cand instanceof Node) return false; - const obj = cand as Partial; + const fmt = promptComposerFormat(); return ( - (typeof obj.Xu === "function" && typeof obj.Nl === "function") || - (typeof obj.Tx === "function" && typeof obj.Sk === "function") + typeof readOwn(cand, fmt.hostToggleAgent) === "function" && + typeof readOwn(cand, fmt.hostIsAgent) === "function" ); } /** Finds the live `flow-prompt-box` host component instance. */ export function findPromptBoxHost(projPage: ProjectPageInstance | null): PromptBoxHost | null { if (projPage) { - const getHost = - typeof projPage.NF === "function" - ? projPage.NF - : typeof projPage.jQ === "function" - ? projPage.jQ - : null; - if (getHost) { + const getHost = readOwn(projPage, promptComposerFormat().pagePromptHost); + if (typeof getHost === "function") { try { const host = getHost.call(projPage); if (isPromptBoxHost(host)) return host; @@ -210,14 +229,14 @@ export function findPromptBoxHost(projPage: ProjectPageInstance | null): PromptB /** Type guard for `flow-base-prompt-box` controller instances. */ function isBasePromptBoxInst(cand: unknown): cand is BasePromptBoxInstance { if (!cand || typeof cand !== "object" || cand instanceof Node) return false; - const obj = cand as Partial; - const hasSubmit = typeof obj.Gp === "function" || typeof obj.Wn === "function"; - const hasCanSubmit = typeof obj.wf === "function" || typeof obj.qf === "function"; - const hasEditor = typeof obj.IU === "function" || typeof obj.CQ === "function"; - const hasOverlay = - typeof obj.rN?.set === "function" || typeof obj.VJ?.set === "function"; + const fmt = promptComposerFormat(); + const hasSubmit = typeof readOwn(cand, fmt.submit) === "function"; + const hasCanSubmit = typeof readOwn(cand, fmt.canSubmit) === "function"; + const hasEditor = typeof readOwn(cand, fmt.richEditor) === "function"; + const overlay = readOwn(cand, fmt.settingsOverlay) as BooleanOverlaySignal | undefined; + const hasOverlay = typeof overlay?.set === "function"; return Boolean( - obj.Qa && + readOwn(cand, fmt.promptState) && ((hasSubmit && hasCanSubmit) || (hasCanSubmit && (hasEditor || hasOverlay)) || (hasEditor && hasSubmit)), @@ -226,9 +245,10 @@ function isBasePromptBoxInst(cand: unknown): cand is BasePromptBoxInstance { /** Walks up parent elements and LViews from `startEl` to find a `BasePromptBoxInstance`. */ function scanElementForBasePromptBox(startEl: Element | null): BasePromptBoxInstance | null { - if (!startEl) return null; + if (!startEl || startEl.closest(NON_COMPOSER_PANELS)) return null; let cur: Element | null = startEl; for (let depth = 0; depth < 6 && cur; depth += 1) { + if (cur.closest(NON_COMPOSER_PANELS)) break; let lv: NgLView | null = resolveLView(cur); for (let pDepth = 0; pDepth < 6 && Array.isArray(lv); pDepth += 1) { for (const cand of lv) { @@ -248,13 +268,8 @@ export function findLiveBasePromptBox( ): BasePromptBoxInstance | null { if (!editFlag) { if (promptBoxHost) { - const getManualBox = - typeof promptBoxHost.zr === "function" - ? promptBoxHost.zr - : typeof promptBoxHost.mt === "function" - ? promptBoxHost.mt - : null; - if (getManualBox) { + const getManualBox = readOwn(promptBoxHost, promptComposerFormat().hostManualBox); + if (typeof getManualBox === "function") { try { const direct = getManualBox.call(promptBoxHost); if (isBasePromptBoxInst(direct)) return direct; @@ -263,22 +278,36 @@ export function findLiveBasePromptBox( } } } - return scanElementForBasePromptBox( - document.querySelector("flow-prompt-box flow-base-prompt-box"), - ); + const manualCandidates = Array.from( + document.querySelectorAll("flow-prompt-box flow-base-prompt-box"), + ).filter((el) => !el.closest(NON_COMPOSER_PANELS)); + for (const el of manualCandidates) { + const hit = scanElementForBasePromptBox(el); + if (hit) return hit; + } + return null; } - return scanElementForBasePromptBox( - document.querySelector( - "flow-edit-video-prompt-box flow-base-prompt-box, flow-edit-video-prompt-box", + const editCandidates = Array.from( + document.querySelectorAll( + "flow-edit-image-prompt-box flow-base-prompt-box, flow-edit-video-prompt-box flow-base-prompt-box, flow-edit-image-prompt-box, flow-edit-video-prompt-box, flow-editor-page flow-base-prompt-box, flow-scene-builder flow-base-prompt-box", ), - ); + ).filter((el) => !el.closest(NON_COMPOSER_PANELS)); + const ordered = [ + ...editCandidates.filter((el) => el.getClientRects().length > 0), + ...editCandidates.filter((el) => el.getClientRects().length === 0), + ]; + for (const el of ordered) { + const hit = scanElementForBasePromptBox(el); + if (hit) return hit; + } + return null; } /** Returns true when a custom warning element or one of its children is visible on screen. */ -function isWarningElementVisible(el: Element, excludeAgent: boolean): boolean { +function isWarningElementVisible(el: Element, excludeNonComposer: 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 (excludeNonComposer && el.closest(NON_COMPOSER_PANELS)) return false; const style = window.getComputedStyle(el); if (style.display === "none" || style.visibility === "hidden") return false; if (el.getClientRects().length > 0) return true; @@ -387,32 +416,30 @@ export async function closeModelMenu(): Promise { export async function closeSettingsAndMenus(): Promise { await closeModelMenu(); if (!settingsOpen()) return; - const baseEl = document.querySelector( - "flow-prompt-box flow-base-prompt-box, flow-base-prompt-box", - ); + const onEdit = isEditOrSceneRoute(); + const baseEl = Array.from( + document.querySelectorAll( + "flow-prompt-box flow-base-prompt-box, flow-edit-image-prompt-box flow-base-prompt-box, flow-edit-video-prompt-box flow-base-prompt-box, flow-base-prompt-box", + ), + ).find((el) => !el.closest(NON_COMPOSER_PANELS)) ?? null; + const fmt = promptComposerFormat(); + const readOverlay = (cand: unknown): BooleanOverlaySignal | null => { + const sig = readOwn(cand, fmt.settingsOverlay) as BooleanOverlaySignal | undefined; + return typeof sig?.set === "function" ? sig : null; + }; const findBaseInst = (lv: NgLView): BasePromptBoxInstance | null => { for (const cand of lv) { - if ( - cand && - typeof cand === "object" && - !(cand instanceof Node) && - (typeof (cand as BasePromptBoxInstance).rN?.set === "function" || - typeof (cand as BasePromptBoxInstance).VJ?.set === "function") - ) { + if (cand && typeof cand === "object" && !(cand instanceof Node) && readOverlay(cand)) { return cand as BasePromptBoxInstance; } } return null; }; let baseInst: BasePromptBoxInstance | null = findLiveBasePromptBox( - false, - findPromptBoxHost(findProjectPageInstance()), + onEdit, + onEdit ? null : findPromptBoxHost(findProjectPageInstance()), ); - if ( - baseInst && - typeof baseInst.rN?.set !== "function" && - typeof baseInst.VJ?.set !== "function" - ) { + if (baseInst && !readOverlay(baseInst)) { baseInst = null; } if (!baseInst && baseEl) { @@ -426,16 +453,14 @@ export async function closeSettingsAndMenus(): Promise { if (!baseInst && runtimeState.ngLViewMap instanceof Map) { for (const lv of runtimeState.ngLViewMap.values()) { if (!isLiveLView(lv)) continue; + if (lv[0] instanceof Element && lv[0].closest(NON_COMPOSER_PANELS)) { + continue; + } baseInst = findBaseInst(lv); if (baseInst) break; } } - const overlaySignal = - typeof baseInst?.rN?.set === "function" - ? baseInst.rN - : typeof baseInst?.VJ?.set === "function" - ? baseInst.VJ - : null; + const overlaySignal = readOverlay(baseInst); if (overlaySignal?.set) { try { overlaySignal.set(false); @@ -445,9 +470,11 @@ export async function closeSettingsAndMenus(): Promise { await delay(80); } if (settingsOpen()) { - const sBtn = document.querySelector( - 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', - ); + const sBtn = Array.from( + document.querySelectorAll( + 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', + ), + ).find((el) => !el.closest(NON_COMPOSER_PANELS)) ?? null; if (isVisibleEnabled(sBtn)) { sBtn.click(); await delay(80); @@ -475,3 +502,53 @@ export async function closeSettingsAndMenus(): Promise { await delay(50); } } + +/** Returns true when `el` is connected, visible on screen, and outside non-composer panels. */ +export function isVisibleOutsideNonComposer( + el: Element | null | undefined, +): el is HTMLElement { + if (!(el instanceof HTMLElement) || !el.isConnected) return false; + if (el.closest('[hidden], [aria-hidden="true"]')) return false; + if (el.closest(NON_COMPOSER_PANELS)) return false; + const style = window.getComputedStyle(el); + if (style.display === "none" || style.visibility === "hidden") return false; + return el.getClientRects().length > 0; +} + +/** Reads a blocking `.too-long-overlay` or composer alert message from the active editor view. */ +export function readComposerAlert(includePageAlerts: boolean): string | null { + const primaryAlerts = Array.from( + document.querySelectorAll( + `.too-long-overlay, flow-edit-video-prompt-box [role="alert"], flow-edit-image-prompt-box [role="alert"]`, + ), + ); + for (const el of primaryAlerts) { + if (!isVisibleOutsideNonComposer(el)) continue; + const msg = elText(el).replace(/\s+/g, " ").trim(); + if (msg) return msg; + } + if (!includePageAlerts) return null; + const pageAlerts = Array.from( + document.querySelectorAll( + 'flow-editor-page [role="alert"], flow-scene-builder [role="alert"], flow-alert-dialog [role="dialog"], flow-alert-dialog', + ), + ); + for (const el of pageAlerts) { + if (!isVisibleOutsideNonComposer(el)) continue; + const msg = elText(el).replace(/\s+/g, " ").trim(); + if (msg) return msg; + } + return null; +} + +/** Reads the disabled submit reason string from a `PromptState` instance. */ +export function readPromptStateReason(state: unknown): string { + if (!state || typeof state !== "object") return ""; + const fmt = promptComposerFormat(); + const validator = readOwn(state, fmt.validator); + const reasonFn = readOwn(validator, fmt.validatorReason); + return typeof reasonFn === "function" + ? String(reasonFn.call(validator) || "").trim() + : ""; +} + diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index ba0c7cf..bb5a613 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -726,38 +726,19 @@ const NOVEMBER_20_SNAPSHOT: SnapshotFormat = { tile: { trashed: "Cb", parentCollection: "Dc" }, trim: { mediaStart: "Jc", mediaEnd: "Pc", clipStart: "Ji", clipEnd: "Ci", clipDuration: "nc" }, media: { - container: "Kb", - url: "kc", - status: "od", - error: "Bf", - dimensions: "Bc", - duration: "Cf", - date: "lc", - uploaded: "vp", - uploadSource: "QE", + container: "Kb", url: "kc", status: "od", error: "Bf", dimensions: "Bc", + duration: "Cf", date: "lc", uploaded: "vp", uploadSource: "QE", }, character: { - entity: "Rc", - looks: "Ng", - previewMediaId: "Kd", - entityInfoField: 4, - characterInfoField: 3, - audioReferencesField: 2, - presetVoiceField: 2, - customVoiceField: 1, - notesField: 3, + entity: "Rc", looks: "Ng", previewMediaId: "Kd", entityInfoField: 4, characterInfoField: 3, + audioReferencesField: 2, presetVoiceField: 2, customVoiceField: 1, notesField: 3, }, tileTypes: { collection: "COLLECTION", assets: ["IMAGE", "VIDEO", "SCENE", "CHARACTER"], ignored: ["TEXT_TILE", "CUSTOM"], }, - credits: { - service: "EG", - total: "Ts", - query: "query", - balanceMethod: "YR", - }, + credits: { service: "EG", total: "Ts", query: "query", balanceMethod: "YR" }, }; /** Verified operations and store format of one build. */ @@ -776,6 +757,8 @@ interface FrontendBuildFields { characterCreate?: CharacterCreateFormat; /** Native fields of editable project titles. */ projectTitle?: ProjectTitleFormat; + /** Native fields of the manual and edit prompt composers. */ + promptComposer?: PromptComposerFormat; } /** A verified build with full or pre-Agent operation coverage. */ @@ -891,6 +874,64 @@ const LEGACY_CHARACTER_CREATE: CharacterCreateFormat = { /** Editable project title format of earlier builds. */ const LEGACY_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "tJa", stateSignal: "state" }; +/** Native fields of `PromptState`, `flow-base-prompt-box`, `flow-prompt-box`, and ProseMirror. */ +export interface PromptComposerFormat { + /** Property holding `PromptState` on composer and page components. */ + promptState: string; + /** `PromptState` method that applies a serialized prompt document. */ + applyPrompt: string; + /** Segment list key in a serialized prompt document. */ + segments: string; + /** `PromptState.prompt` signal that returns true when the prompt is empty. */ + promptEmpty: string; + /** Validator object property on `PromptState`. */ + validator: string; + /** Method on the validator object that returns the disabled submit reason. */ + validatorReason: string; + /** `flow-base-prompt-box` query returning `flow-rich-text-editor`. */ + richEditor: string; + /** ProseMirror `EditorView` property on `flow-rich-text-editor`. */ + editorView: string; + /** ProseMirror transaction getter on `EditorState`. */ + pmTransaction: string; + /** ProseMirror dispatch method on `EditorView`. */ + pmDispatch: string; + /** Submit method on `flow-base-prompt-box`. */ + submit: string; + /** Readiness signal on `flow-base-prompt-box`. */ + canSubmit: string; + /** Settings overlay writable signal on `flow-base-prompt-box`. */ + settingsOverlay: string; + /** Disabled submit reason signal on `flow-base-prompt-box`. */ + disabledReason: string; + /** Output count setter on `flow-prompt-box-settings`. */ + settingsSetCount: string; + /** `flow-project-page` query returning `flow-prompt-box`. */ + pagePromptHost: string; + /** Agent mode toggle method on `flow-prompt-box`. */ + hostToggleAgent: string; + /** Agent mode check method on `flow-prompt-box`. */ + hostIsAgent: string; + /** `flow-prompt-box` query returning the manual `flow-base-prompt-box`. */ + hostManualBox: string; +} + +/** Prompt composer format of earlier builds. */ +const LEGACY_PROMPT_COMPOSER: PromptComposerFormat = { + promptState: "Qa", applyPrompt: "Wn", segments: "Oe", promptEmpty: "Le", validator: "lf", + validatorReason: "jYa", richEditor: "CQ", editorView: "th", pmTransaction: "Fi", pmDispatch: "Qd", + submit: "Wn", canSubmit: "qf", settingsOverlay: "VJ", disabledReason: "sL", settingsSetCount: "Ula", + pagePromptHost: "jQ", hostToggleAgent: "Tx", hostIsAgent: "Sk", hostManualBox: "mt", +}; + +/** Prompt composer format of build 20261120.00. */ +const NOVEMBER_20_PROMPT_COMPOSER: PromptComposerFormat = { + promptState: "Qa", applyPrompt: "Gp", segments: "Te", promptEmpty: "Ke", validator: "Ff", + validatorReason: "N7a", richEditor: "IU", editorView: "Tb", pmTransaction: "uj", pmDispatch: "Td", + submit: "Gp", canSubmit: "wf", settingsOverlay: "rN", disabledReason: "vV", settingsSetCount: "Osa", + pagePromptHost: "NF", hostToggleAgent: "Xu", hostIsAgent: "Nl", hostManualBox: "zr", +}; + /** Request formats by exact build label. Include only verified operations. */ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261117.10_p0", { @@ -900,12 +941,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map = new Map typeof v === "number" && Number.isFinite(v) && v > 0); +} -/** Navigates to `/edit/` using Angular Router or triggers an inline tile edit action. */ +/** Navigates to `/edit/` via Angular Router or triggers an inline tile edit control. */ export async function openEditAsset( assetId: string, mediaUrl: string | null, primaryMediaId: string | null, ): Promise { const idStr = String(assetId || "").trim(); - const candidateIds = Array.from( - new Set([idStr, String(primaryMediaId || "").trim()].filter(Boolean)), - ); + const primaryStr = String(primaryMediaId || "").trim(); + const candidateIds = Array.from(new Set([idStr, primaryStr].filter(Boolean))); - function findVisibleTextbox(): Element | null { - const candidates = Array.from( - document.querySelectorAll( - '.ProseMirror[contenteditable="true"], [role="textbox"][contenteditable="true"], textarea', - ), - ); - return ( - candidates.find( - (el) => el.getClientRects().length > 0 && !isDisabledProp(el), - ) || null - ); + const tileMap = runtimeState.store?.getTileMap?.(); + if (tileMap instanceof Map && idStr) { + const directTile = tileMap.get(idStr); + if (directTile) { + const rawType = String(directTile.type || "").toUpperCase(); + if (rawType === "SCENE" && !hasTileDuration(directTile)) { + return { + opened: false, + error: "unsupported_asset_kind", + kind: "scene", + alert: `Cannot edit scene '${idStr}' without a duration; pass a video asset ID to flow_edit.`, + has_textbox: false, + }; + } + if (rawType === "CHARACTER") { + return { + opened: false, + error: "unsupported_asset_kind", + kind: "character", + alert: `Cannot edit character '${idStr}' with flow_edit. Use flow_character_edit instead.`, + has_textbox: false, + }; + } + if ( + rawType === "AUDIO" || + rawType === "MUSIC" || + rawType === "VOICE" || + rawType === "COLLECTION" + ) { + return { + opened: false, + error: "unsupported_asset_kind", + kind: rawType.toLowerCase(), + alert: `Cannot edit ${rawType.toLowerCase()} asset '${idStr}' with flow_edit.`, + has_textbox: false, + }; + } + } } const pm = /\/project\/([^/?#]+)/.exec(location.pathname || ""); - const pid = pm ? pm[1] : null; - const router = pid && candidateIds.length > 0 ? findRouter() : null; - if (router && pid && candidateIds.length > 0) { - let viewKind: string | null = null; - for (const candId of candidateIds) { - await navigateSpa(router, ["/project", pid, "edit", candId]); - for (let i = 0; i < 60; i += 1) { + const pid = pm ? pm[1] : runtimeState.store?.projectId || null; + const router = pid ? findRouter() : null; + const alreadyOnEditRoute = (location.pathname || "").includes("/edit/"); + + if (pid && candidateIds.length > 0 && (router || alreadyOnEditRoute)) { + let lastEmptyView: string | null = null; + const idsToTry = router ? candidateIds : [idStr || candidateIds[0]]; + for (const candId of idsToTry) { + if ( + router && + !( + (location.pathname || "").includes(`/edit/${candId}`) && + (document.querySelector("flow-editor-page") || + document.querySelector("flow-scene-builder")) + ) + ) { + await withLViewMapCapture(async () => { + await navigateSpa(router, ["/project", pid, "edit", candId]); + }); + } + let viewKind: string | null = null; + const waitTicks = router ? 60 : 30; + for (let i = 0; i < waitTicks; i += 1) { const onRoute = (location.pathname || "").includes("/edit/"); const edPage = document.querySelector("flow-editor-page"); const sbPage = document.querySelector("flow-scene-builder"); @@ -54,28 +123,26 @@ export async function openEditAsset( } await delay(100); } - if (viewKind) break; - } + if (!viewKind) continue; - if (viewKind) { for (let i = 0; i < 25; i += 1) { - if (findVisibleTextbox()) break; + if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } - if (viewKind === "scene_builder" && !findVisibleTextbox()) { + if (viewKind === "scene_builder" && !findTextbox(true)) { const sb = document.querySelector("flow-scene-builder") || document; - const clip = sb.querySelector( - '[class*="clip"], [data-testid*="clip"], video', - ); - if (clip instanceof HTMLElement) { + const clip = Array.from( + sb.querySelectorAll(".timeline-contents > .clip, video"), + ).find((el): el is HTMLElement => el instanceof HTMLElement && !el.closest(NON_COMPOSER_PANELS)); + if (clip) { clip.click(); await delay(200); } - if (!findVisibleTextbox()) { + if (!findTextbox(true)) { const editTrigger = Array.from( sb.querySelectorAll('button, [role="button"], [role="tab"]'), ).find((b): b is HTMLElement => { - if (!isVisibleEnabled(b)) return false; + if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) return false; const lbl = ( b.getAttribute("aria-label") || elText(b) || @@ -90,17 +157,44 @@ export async function openEditAsset( await delay(300); } } + for (let i = 0; i < 20; i += 1) { + if (readComposerAlert(false) || findTextbox(true)) break; + await delay(100); + } } - for (let i = 0; i < 20; i += 1) { - if (findVisibleTextbox()) break; - await delay(100); + + const hasTextbox = Boolean(findTextbox(true)); + const alert = readComposerAlert(!hasTextbox); + if (alert) { + clearStore(); + return { + opened: false, + error: "edit_alert", + alert, + method: "spa_router", + view: viewKind, + has_textbox: false, + }; + } + if (hasTextbox) { + clearStore(); + return { + opened: true, + method: "spa_router", + view: viewKind, + has_textbox: true, + }; } + lastEmptyView = viewKind; + } + if (lastEmptyView) { clearStore(); return { - opened: true, + opened: false, + error: "editor_textbox_not_found", method: "spa_router", - view: viewKind, - has_textbox: Boolean(findVisibleTextbox()), + view: lastEmptyView, + has_textbox: false, }; } } @@ -167,7 +261,9 @@ export async function openEditAsset( scope.querySelectorAll('button, a, [role="button"], [role="menuitem"]'), ); const editBtn = btns.find((el): el is HTMLElement => { - if (!isVisibleEnabled(el)) return false; + if (!isVisibleEnabled(el) || el.closest(NON_COMPOSER_PANELS)) { + return false; + } const txt = ( el.getAttribute("aria-label") || elText(el) || @@ -178,18 +274,40 @@ export async function openEditAsset( }); if (editBtn) { editBtn.click(); - await delay(300); - return { opened: true, method: "ui_edit" }; + for (let i = 0; i < 30; i += 1) { + if (readComposerAlert(false) || findTextbox(true)) break; + await delay(100); + } + const hasTextbox = Boolean(findTextbox(true)); + const alert = readComposerAlert(!hasTextbox); + if (alert) { + clearStore(); + return { + opened: false, + error: "edit_alert", + alert, + method: "ui_edit", + has_textbox: false, + }; + } + if (hasTextbox) { + clearStore(); + return { + opened: true, + method: "ui_edit", + has_textbox: true, + }; + } } } } - if (pid && idStr) { + if (pid && idStr && !alreadyOnEditRoute) { return { opened: false, edit_url: buildProjectUrl(pid, ["edit", idStr]), method: "route_fallback_needed", }; } - return { opened: false, method: "none" }; + return { opened: false, has_textbox: false, method: "none" }; } diff --git a/ts/prompt_writer.ts b/ts/prompt_writer.ts index 2f3e320..db83153 100644 --- a/ts/prompt_writer.ts +++ b/ts/prompt_writer.ts @@ -5,9 +5,11 @@ import { readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe, isVisibleEnabled, setNativeValue } from "./dom"; +import { promptComposerFormat } from "./frontend_builds"; import { runtimeState } from "./state"; import type { NgLView, + PromptDocumentPayload, PromptStateController, ProseMirrorState, ProseMirrorTransaction, @@ -36,10 +38,8 @@ function findPmTransaction(state: unknown): ProseMirrorTransaction | null { if (!state || typeof state !== "object") return null; const trProp = readOwn(state, "tr"); if (isPmTransaction(trProp)) return trProp; - const ujProp = readOwn(state, "uj"); - if (isPmTransaction(ujProp)) return ujProp; - const fiProp = readOwn(state, "Fi"); - if (isPmTransaction(fiProp)) return fiProp; + const fmtProp = readOwn(state, promptComposerFormat().pmTransaction); + if (isPmTransaction(fmtProp)) return fmtProp; const seen = new Set(); let cur: object | null = state; for (let d = 0; cur && cur !== Object.prototype && d < 3; d++) { @@ -84,10 +84,9 @@ function isPmViewStruct(cand: unknown): cand is ProseMirrorView { function findPmViewInRichEditor(cand: unknown): ProseMirrorView | null { if (!cand || typeof cand !== "object" || cand instanceof Node) return null; if (isPmViewStruct(cand)) return cand; - const tbVal = readOwn(cand, "Tb"); - if (isPmViewStruct(tbVal)) return tbVal; - const thVal = readOwn(cand, "th"); - if (isPmViewStruct(thVal)) return thVal; + const editorViewKey = promptComposerFormat().editorView; + const directView = readOwn(cand, editorViewKey); + if (isPmViewStruct(directView)) return directView; let fallback: ProseMirrorView | null = null; for (const k of Object.keys(cand)) { @@ -100,10 +99,8 @@ function findPmViewInRichEditor(cand: unknown): ProseMirrorView | null { typeof slotVal === "object" && !(slotVal instanceof Node) ) { - const subTb = readOwn(slotVal, "Tb"); - if (isPmViewStruct(subTb)) return subTb; - const subTh = readOwn(slotVal, "th"); - if (isPmViewStruct(subTh)) return subTh; + const subView = readOwn(slotVal, editorViewKey); + if (isPmViewStruct(subView)) return subView; } } return fallback; @@ -152,13 +149,14 @@ export async function writePromptBox( const dispatchFns: Array<(t: ProseMirrorTransaction) => void> = []; const dispatchTxFns: Array<(t: ProseMirrorTransaction) => void> = []; const updateStateFns: Array<(t: ProseMirrorTransaction) => void> = []; + const fmt = promptComposerFormat(); if (typeof pmView.dispatch === "function") { const dispatch = pmView.dispatch; dispatchFns.push((t) => dispatch(t)); } - if (typeof pmView.Qd === "function") { - const qd = pmView.Qd; - dispatchFns.push((t) => qd(t)); + const fmtDispatch = readOwn(pmView, fmt.pmDispatch); + if (typeof fmtDispatch === "function") { + dispatchFns.push((t) => fmtDispatch.call(pmView, t)); } let cur: object | null = pmView; for (let d = 0; cur && cur !== Object.prototype && d < 3; d++) { @@ -169,7 +167,7 @@ export async function writePromptBox( break; } for (const k of names) { - if (k === "constructor" || k === "dispatch" || k === "Qd") { + if (k === "constructor" || k === "dispatch" || k === fmt.pmDispatch) { continue; } const fn = readOwn(cur, k); @@ -190,10 +188,6 @@ export async function writePromptBox( cur = Object.getPrototypeOf(cur); } dispatchFns.push(...dispatchTxFns, ...updateStateFns); - if (typeof pmView.Td === "function") { - const td = pmView.Td; - dispatchFns.push((t) => td.call(pmView, t)); - } const prevState = pmView.state; for (const callDispatch of dispatchFns) { try { @@ -220,22 +214,18 @@ export async function writePromptBox( let pmViewFound: ProseMirrorView | null = null; let promptState: PromptStateController | null = null; + const fmt = promptComposerFormat(); if (opts.liveUx) { - if ( - opts.liveUx.Qa && - (typeof opts.liveUx.Qa.Gp === "function" || - typeof opts.liveUx.Qa.Wn === "function") - ) { - promptState = opts.liveUx.Qa; + const liveState = readOwn(opts.liveUx, fmt.promptState) as PromptStateController | undefined; + if (liveState && typeof readOwn(liveState, fmt.applyPrompt) === "function") { + promptState = liveState; } try { - const getEditor = - typeof opts.liveUx.IU === "function" - ? opts.liveUx.IU - : typeof opts.liveUx.CQ === "function" - ? opts.liveUx.CQ - : null; - const re = getEditor ? getEditor.call(opts.liveUx) : null; + const getEditor = readOwn(opts.liveUx, fmt.richEditor); + const re = + typeof getEditor === "function" + ? (getEditor.call(opts.liveUx) as RichTextEditorInstance | null | undefined) + : null; const view = findPmViewInRichEditor(re); if (re && view) { richEditor = re; @@ -259,7 +249,7 @@ export async function writePromptBox( continue; } try { - const editorGetter = readOwn(cand, "IU") ?? readOwn(cand, "CQ"); + const editorGetter = readOwn(cand, fmt.richEditor); if (!pmViewFound && typeof editorGetter === "function") { const re = editorGetter.call(cand) as | RichTextEditorInstance @@ -287,16 +277,13 @@ export async function writePromptBox( } try { if (!promptState) { - const qaVal = readOwn(cand, "Qa") as PromptStateController | undefined; - const ownApply = readOwn(cand, "Gp") ?? readOwn(cand, "Wn"); - const ownValidator = (readOwn(cand, "Ff") ?? readOwn(cand, "lf")) as + const stateVal = readOwn(cand, fmt.promptState) as PromptStateController | undefined; + const ownApply = readOwn(cand, fmt.applyPrompt); + const ownValidator = readOwn(cand, fmt.validator) as | { isValid?: unknown } | undefined; - if ( - qaVal && - (typeof qaVal.Gp === "function" || typeof qaVal.Wn === "function") - ) { - promptState = qaVal; + if (stateVal && typeof readOwn(stateVal, fmt.applyPrompt) === "function") { + promptState = stateVal; } else if ( typeof ownApply === "function" && ownValidator && @@ -312,9 +299,13 @@ export async function writePromptBox( } }; + const isExcluded = (el: Element | null | undefined): boolean => + Boolean(opts.excludeSelector && el?.closest(opts.excludeSelector)); + const scanResolvedTree = (): void => { const defaultSeeds = [ document.querySelector("flow-rich-text-editor"), + document.querySelector("flow-edit-image-prompt-box"), document.querySelector("flow-edit-video-prompt-box"), document.querySelector("flow-base-prompt-box"), ]; @@ -323,6 +314,7 @@ export async function writePromptBox( rootEl, rootEl.closest("flow-rich-text-editor"), rootEl.closest("flow-base-prompt-box"), + rootEl.closest("flow-edit-image-prompt-box"), rootEl.closest("flow-edit-video-prompt-box"), rootEl.closest("flow-creative-agent-prompt-box"), rootEl.closest("flow-applet-prompt-box"), @@ -330,10 +322,11 @@ export async function writePromptBox( rootEl.closest("flow-character-prompt-box"), rootEl.closest("flow-edit-character-footer"), ...extraSeeds, - ].filter((el): el is Element => Boolean(el)); + ].filter((el): el is Element => Boolean(el && !isExcluded(el))); for (const seed of startSeeds) { let cur: Element | null = seed; for (let depth = 0; depth < 8 && cur; depth++) { + if (isExcluded(cur)) break; let p: NgLView | null = resolveLView(cur); for (let pDepth = 0; pDepth < 6 && Array.isArray(p); pDepth++) { extractFromLView(p); @@ -357,7 +350,9 @@ export async function writePromptBox( ) { const sBtn = opts.trySettingsClick !== false - ? document.querySelector('button[aria-label="Settings trigger"]') + ? Array.from( + document.querySelectorAll('button[aria-label="Settings trigger"]'), + ).find((el) => !isExcluded(el)) ?? null : null; if (isVisibleEnabled(sBtn)) { await withLViewMapCapture(async () => { @@ -395,7 +390,9 @@ export async function writePromptBox( : null) || document; const tipEls = Array.from( scope.querySelectorAll("[mattooltip], button[aria-label]"), - ).slice(0, 6); + ) + .filter((el) => !isExcluded(el)) + .slice(0, 6); await withLViewMapCapture(async () => { await hoverProbe(tipEls, 80); }); @@ -423,37 +420,31 @@ export async function writePromptBox( return { richEditor, pmViewFound, promptState }; } + const fmt = promptComposerFormat(); const { richEditor, pmViewFound, promptState } = await capturePromptControllers(tb); runtimeState.promptState = promptState || null; const readPromptEmpty = (): boolean | null => { - if (typeof promptState?.prompt?.Ke === "function") { - return Boolean(promptState.prompt.Ke()); - } - if (typeof promptState?.prompt?.Le === "function") { - return Boolean(promptState.prompt.Le()); - } - return null; + const emptyFn = readOwn(promptState?.prompt, fmt.promptEmpty); + return typeof emptyFn === "function" ? Boolean(emptyFn.call(promptState?.prompt)) : null; + }; + const readValidator = (): { isValid?: () => boolean } | null => { + const validator = readOwn(promptState, fmt.validator) as + | { isValid?: () => boolean } + | undefined; + return validator && typeof validator.isValid === "function" ? validator : null; }; - const hasValidator = (): boolean => - typeof promptState?.Ff?.isValid === "function" || - typeof promptState?.lf?.isValid === "function"; - const isPromptValid = (): boolean => - typeof promptState?.Ff?.isValid === "function" - ? promptState.Ff.isValid() === true - : typeof promptState?.lf?.isValid === "function" - ? promptState.lf.isValid() === true - : false; + const hasValidator = (): boolean => readValidator() !== null; + const isPromptValid = (): boolean => readValidator()?.isValid?.() === true; + const canApplyPromptState = (): boolean => + Boolean(promptState && typeof readOwn(promptState, fmt.applyPrompt) === "function"); const applyPromptStateText = (content: string): boolean => { - const applyFn = - typeof promptState?.Gp === "function" - ? promptState.Gp - : typeof promptState?.Wn === "function" - ? promptState.Wn - : null; - if (!promptState || !applyFn) return false; - const segments = [{ type: "text", content }]; - applyFn.call(promptState, { Oe: segments, Te: segments }); + const applyFn = readOwn(promptState, fmt.applyPrompt); + if (!promptState || typeof applyFn !== "function") return false; + const payload: PromptDocumentPayload = { + [fmt.segments]: [{ type: "text", content }], + }; + applyFn.call(promptState, payload); return true; }; const isPromptPopulated = (): boolean => { @@ -466,7 +457,7 @@ export async function writePromptBox( ? isPromptPopulated() : true; const activePmTarget: unknown = - pmViewFound || richEditor?.Tb || richEditor?.th; + pmViewFound || readOwn(richEditor, fmt.editorView); if (opts.strictSync) { if (activePmTarget) { @@ -479,12 +470,7 @@ export async function writePromptBox( } else if (activePmTarget || promptState) { applyToPmView(activePmTarget, text); await delay(100); - if ( - promptState && - (typeof promptState.Gp === "function" || - typeof promptState.Wn === "function") && - !isPromptPopulated() - ) { + if (canApplyPromptState() && !isPromptPopulated()) { try { applyPromptStateText(text); } catch { @@ -590,13 +576,7 @@ export async function writePromptBox( // Fall through to strictSync promptState tier. } - if ( - opts.strictSync && - promptState && - (typeof promptState.Gp === "function" || - typeof promptState.Wn === "function") && - !isPromptPopulated() - ) { + if (opts.strictSync && canApplyPromptState() && !isPromptPopulated()) { try { applyPromptStateText(text); await delay(120); diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..cd723fd 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -3,7 +3,7 @@ // Configure Google Flow generation mode, settings, model, aspect ratio, and count. -import { resolveLView, withLViewMapCapture } from "./angular"; +import { readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { closeModelMenu, closeSettingsAndMenus, @@ -11,11 +11,14 @@ import { findLiveBasePromptBox, findProjectPageInstance, findPromptBoxHost, + isEditOrSceneRoute, + NON_COMPOSER_PANELS, settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { promptComposerFormat } from "./frontend_builds"; import { runtimeState } from "./state"; -import type { GenerationConfig, NgLView } from "./types"; +import type { GenerationConfig, NgLView, PromptStateController } from "./types"; /** Escapes regular expression metacharacters in literal labels. */ function escapeRegex(s: unknown): string { @@ -216,9 +219,12 @@ async function ensureLViewCapture(allowSettingsClick = false): Promise { return; } if (allowSettingsClick) { - const sBtn = document.querySelector( - 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', - ); + const sBtn = + Array.from( + document.querySelectorAll( + 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', + ), + ).find((el) => !el.closest(NON_COMPOSER_PANELS)) ?? null; if (isVisibleEnabled(sBtn) && !settingsOpen()) { await withLViewMapCapture(async () => { sBtn.click(); @@ -232,16 +238,19 @@ 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 = isEditOrSceneRoute(); if (!onEditPage) { const textbox = await ensureManualComposer(); if (!textbox) return { ok: false, error: "manual_prompt_not_ready" }; await ensureLViewCapture(true); - const settingsBtn = document.querySelector( - 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', - ); + const settingsBtn = + Array.from( + document.querySelectorAll( + 'flow-prompt-box button[aria-label="Settings trigger"], button[aria-label="Settings trigger"]', + ), + ).find((el) => !el.closest(NON_COMPOSER_PANELS)) ?? null; const scope = findComposerRoot(textbox); if (isVisibleEnabled(settingsBtn) && !settingsOpen()) { @@ -414,11 +423,13 @@ export async function setupGeneration( } try { + const fmt = promptComposerFormat(); const liveUx = findLiveBasePromptBox( false, findPromptBoxHost(findProjectPageInstance()), ); - const curMode = String(liveUx?.Qa?.config?.mode?.() || ""); + const liveState = readOwn(liveUx, fmt.promptState) as PromptStateController | undefined; + const curMode = String(liveState?.config?.mode?.() || ""); const wantImageMode = mode === "image" || mode === "character" || mode === "scene"; if (wantImageMode && curMode && curMode !== "IMAGE") { @@ -439,37 +450,25 @@ export async function setupGeneration( } if ( cfg.count != null && - typeof liveUx?.Qa?.config?.outputCount === "function" && - Number(liveUx.Qa.config.outputCount()) !== Number(cfg.count) + typeof liveState?.config?.outputCount === "function" && + Number(liveState.config.outputCount()) !== Number(cfg.count) ) { const settingsEl = document.querySelector("flow-prompt-box-settings"); if (settingsEl) { let lv: NgLView | null = resolveLView(settingsEl); for (let d = 0; d < 4 && Array.isArray(lv); d += 1) { - const iw = lv.find( - ( - c, - ): c is { - Osa?: (count: number) => void; - Ula?: (count: number) => void; - } => - Boolean( - c && - typeof c === "object" && - !(c instanceof Node) && - (typeof (c as { Osa?: unknown }).Osa === "function" || - typeof (c as { Ula?: unknown }).Ula === "function"), - ), - ); - if (iw) { - if (typeof iw.Osa === "function") { - iw.Osa(Number(cfg.count)); - } else if (typeof iw.Ula === "function") { - iw.Ula(Number(cfg.count)); + let applied = false; + for (const c of lv) { + if (!c || typeof c !== "object" || c instanceof Node) continue; + const setCount = readOwn(c, fmt.settingsSetCount); + if (typeof setCount === "function") { + setCount.call(c, Number(cfg.count)); + await delay(100); + applied = true; + break; } - await delay(100); - break; } + if (applied) break; lv = Array.isArray(lv[3]) ? lv[3] : Array.isArray(lv[15]) diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..d687746 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -4,8 +4,14 @@ // Locate the enabled Flow generation submit button and compute its viewport click point. import { readAngularTooltip, readOwn, resolveLView } from "./angular"; -import { findComposerWarning } from "./composer"; +import { + findComposerWarning, + isEditOrSceneRoute, + NON_COMPOSER_PANELS, + readPromptStateReason, +} from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; +import { promptComposerFormat } from "./frontend_builds"; import { runtimeState } from "./state"; import type { NgLView } from "./types"; @@ -13,29 +19,17 @@ import type { NgLView } from "./types"; function readCandidateValidatorReason(cand: unknown): string { if (!cand || typeof cand !== "object" || cand instanceof Node) return ""; try { - const vVFn = readOwn(cand, "vV"); - if (typeof vVFn === "function") { - const msg = String(vVFn.call(cand) || "").trim(); + const fmt = promptComposerFormat(); + const disabledFn = readOwn(cand, fmt.disabledReason); + if (typeof disabledFn === "function") { + const msg = String(disabledFn.call(cand) || "").trim(); if (msg) return msg; } - const sLFn = readOwn(cand, "sL"); - if (typeof sLFn === "function") { - const msg = String(sLFn.call(cand) || "").trim(); - if (msg) return msg; - } - const qa = readOwn(cand, "Qa"); - const qaFf = readOwn(qa, "Ff") as { N7a?: () => string } | undefined; - const qaLf = readOwn(qa, "lf") as { jYa?: () => string } | undefined; - const qaMsg = String(qaFf?.N7a?.() || qaLf?.jYa?.() || "").trim(); - if (qaMsg) return qaMsg; + const nestedMsg = readPromptStateReason(readOwn(cand, fmt.promptState)); + if (nestedMsg) return nestedMsg; - const applyFn = readOwn(cand, "Gp") ?? readOwn(cand, "Wn"); - if (typeof applyFn === "function") { - const directFf = readOwn(cand, "Ff") as { N7a?: () => string } | undefined; - const directLf = readOwn(cand, "lf") as { jYa?: () => string } | undefined; - const directMsg = String( - directFf?.N7a?.() || directLf?.jYa?.() || "", - ).trim(); + if (typeof readOwn(cand, fmt.applyPrompt) === "function") { + const directMsg = readPromptStateReason(cand); if (directMsg) return directMsg; } } catch { @@ -102,11 +96,10 @@ 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 onEditPage = isEditOrSceneRoute(); const scopedSelectors = onEditPage ? [ + 'flow-edit-image-prompt-box button[aria-label="Start generation"]', 'flow-edit-video-prompt-box button[aria-label="Start generation"]', 'flow-editor-page button[aria-label="Start generation"]', 'flow-scene-builder button[aria-label="Start generation"]', @@ -120,6 +113,7 @@ export async function submitGeneration(): Promise { const roots: ParentNode[] = ( onEditPage ? [ + document.querySelector("flow-edit-image-prompt-box"), document.querySelector("flow-edit-video-prompt-box"), document.querySelector("flow-editor-page"), document.querySelector("flow-scene-builder"), @@ -128,12 +122,12 @@ export async function submitGeneration(): Promise { document.querySelector("flow-prompt-box flow-base-prompt-box"), document.querySelector("flow-prompt-box"), ] - ).filter((el): el is Element => Boolean(el)); + ).filter((el): el is Element => Boolean(el && !el.closest(NON_COMPOSER_PANELS))); roots.push(document); return roots; }; const checkWarning = (): { ok: false; error: string; detail: string } | null => { - const w = findComposerWarning(warningRoots(), !onEditPage); + const w = findComposerWarning(warningRoots(), true); if (!w) return null; return { ok: false, @@ -144,25 +138,15 @@ export async function submitGeneration(): Promise { const findStartButton = (): HTMLElement | null => { for (const sel of scopedSelectors) { const match = Array.from(document.querySelectorAll(sel)).find( - (b): b is HTMLElement => { - if (!isVisible(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { - return false; - } - return true; - }, + (b): b is HTMLElement => isVisible(b) && !b.closest(NON_COMPOSER_PANELS), ); if (match) return match; } const fallback = Array.from( document.querySelectorAll('button[aria-label="Start generation"]'), - ).find((b): b is HTMLElement => { - if (!isVisible(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { - return false; - } - return true; - }); + ).find( + (b): b is HTMLElement => isVisible(b) && !b.closest(NON_COMPOSER_PANELS), + ); return fallback ?? null; }; @@ -184,14 +168,13 @@ export async function submitGeneration(): Promise { if (warningAfter) return warningAfter; const exactAfter = findStartButton(); + const disabledBtn: Element | null = exactAfter; if (exactAfter && isVisible(exactAfter) && !isVisibleEnabled(exactAfter)) { - let reason = - runtimeState.promptState?.Ff?.N7a?.() || - runtimeState.promptState?.lf?.jYa?.() || - ""; + let reason = readPromptStateReason(runtimeState.promptState); if (!reason) { - let cur: Element | null = exactAfter; + let cur: Element | null = disabledBtn; for (let depth = 0; depth < 6 && cur && !reason; depth += 1) { + if (cur.closest(NON_COMPOSER_PANELS)) break; let lv: NgLView | null = resolveLView(cur); for (let pDepth = 0; pDepth < 6 && Array.isArray(lv) && !reason; pDepth += 1) { for (const cand of lv) { @@ -210,11 +193,7 @@ export async function submitGeneration(): Promise { for (const lv of runtimeState.ngLViewMap.values()) { if (!Array.isArray(lv)) continue; if (lv[0] instanceof Node && !lv[0].isConnected) continue; - if ( - !onEditPage && - lv[0] instanceof Element && - lv[0].closest(agentSelector) - ) { + if (lv[0] instanceof Element && lv[0].closest(NON_COMPOSER_PANELS)) { continue; } for (const cand of lv) { @@ -231,14 +210,11 @@ 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 && !el.closest(NON_COMPOSER_PANELS), ); const detail = [ reason, - ((visiblePm || document.querySelector(".ProseMirror"))?.textContent || "").slice( - 0, - 40, - ), + (visiblePm?.textContent || "").slice(0, 40), ] .filter(Boolean) .join(" | "); @@ -248,7 +224,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 (b.closest(NON_COMPOSER_PANELS)) { return false; } if ( diff --git a/ts/types.ts b/ts/types.ts index e213a9d..f580335 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -298,31 +298,13 @@ export interface PromptTextSegment { content: string; } -/** Serialized prompt document accepted by `PromptStateController`. */ -export interface PromptDocumentPayload { - /** Prompt segments in earlier builds. */ - Oe?: PromptTextSegment[]; - /** Prompt segments in build 20261120.00. */ - Te?: PromptTextSegment[]; -} +/** Serialized prompt document accepted by `PromptStateController`, keyed by build segment field. */ +export type PromptDocumentPayload = Readonly>; /** 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; - /** Prompt text helper object. */ - prompt?: { - /** Returns true when the prompt is empty in earlier builds. */ - Le?: () => boolean; - /** Returns true when the prompt is empty in build 20261120.00. */ - Ke?: () => boolean; - }; - /** Validator status object in earlier builds. */ - lf?: { isValid?: () => boolean; jYa?: () => string }; - /** Validator status object in build 20261120.00. */ - Ff?: { isValid?: () => boolean; N7a?: () => string }; + /** Prompt text helper object keyed by build empty-check method. */ + prompt?: Record boolean) | undefined>; /** Mode, output count, and model config signals. */ config?: { mode?: () => string; @@ -337,12 +319,7 @@ export interface PromptStateController { } /** Rich text editor component wrapper that holds a ProseMirror view. */ -export interface RichTextEditorInstance { - /** ProseMirror editor view in earlier builds. */ - th?: unknown; - /** ProseMirror editor view in build 20261120.00. */ - Tb?: unknown; -} +export type RichTextEditorInstance = Record; /** Writable signal subset that controls an open state boolean. */ export type BooleanOverlaySignal = @@ -351,47 +328,14 @@ export type BooleanOverlaySignal = /** Angular component controller for a base prompt box. */ export interface BasePromptBoxInstance { - /** Prompt state signal container. */ + /** Prompt state signal container in earlier builds and build 20261120.00. */ Qa?: PromptStateController; - /** Prompt state in build 20261129.06. */ + /** Prompt state signal container from build 20261129.06 on. */ Oa?: PromptStateController; - /** Returns the rich editor wrapper in earlier builds. */ - CQ?: () => RichTextEditorInstance | null | undefined; - /** Returns the rich editor wrapper in build 20261120.00. */ - IU?: () => RichTextEditorInstance | null | undefined; - /** Submits or prepares prompt state in earlier builds. */ - Wn?: (...args: unknown[]) => unknown; - /** Submits or prepares prompt state in build 20261120.00. */ - Gp?: (...args: unknown[]) => unknown; - /** Returns true when the prompt box can submit in earlier builds. */ - qf?: () => boolean; - /** Returns true when the prompt box can submit in build 20261120.00. */ - wf?: () => boolean; - /** Controls settings overlay visibility in earlier builds. */ - VJ?: BooleanOverlaySignal; - /** Controls settings overlay visibility in build 20261120.00. */ - rN?: BooleanOverlaySignal; - /** Returns the disabled submit reason in earlier builds. */ - sL?: () => string; - /** Returns the disabled submit reason in build 20261120.00. */ - vV?: () => string; } /** Host container managing manual and agent prompt boxes. */ -export interface PromptBoxHost { - /** Toggles between manual and agent composer modes in earlier builds. */ - Tx?: () => void; - /** Toggles between manual and agent composer modes in build 20261120.00. */ - Xu?: () => void; - /** Returns true while agent mode is active in earlier builds. */ - Sk?: () => boolean; - /** Returns true while agent mode is active in build 20261120.00. */ - Nl?: () => boolean; - /** Returns the active manual base prompt box instance in earlier builds. */ - mt?: () => BasePromptBoxInstance | null | undefined; - /** Returns the active manual base prompt box instance in build 20261120.00. */ - zr?: () => BasePromptBoxInstance | null | undefined; -} +export type PromptBoxHost = Record; /** Angular project page component instance. */ export interface ProjectPageInstance { @@ -399,7 +343,7 @@ export interface ProjectPageInstance { Ph?: (tile: FlowTile) => void; /** Prompt state and attached item signal container. */ Qa?: PromptStateController; - /** Prompt state in build 20261129.06. */ + /** Prompt state signal container from build 20261129.06 on. */ Oa?: PromptStateController; /** Store or mode mutation signal container. */ ub?: { mutate?: (value: unknown) => unknown }; @@ -409,10 +353,6 @@ export interface ProjectPageInstance { oc?: { all?: () => Array> }; /** Secondary agent state signal container. */ Ta?: { mutate?: (value: unknown) => void }; - /** Returns the prompt box host component in earlier builds. */ - jQ?: () => PromptBoxHost | null | undefined; - /** Returns the prompt box host component in build 20261120.00. */ - NF?: () => PromptBoxHost | null | undefined; } /** ProseMirror editor transaction builder subset. */ @@ -436,10 +376,6 @@ export interface ProseMirrorState { doc: { content: { size: number } }; /** Default transaction builder. */ tr?: ProseMirrorTransaction; - /** Minified transaction builder alias in earlier builds. */ - Fi?: ProseMirrorTransaction; - /** Minified transaction builder alias in build 20261120.00. */ - uj?: ProseMirrorTransaction; } /** ProseMirror editor view subset. */ @@ -450,10 +386,6 @@ export interface ProseMirrorView { dom?: Element; /** Standard transaction dispatch function. */ dispatch?: (tr: ProseMirrorTransaction) => void; - /** Minified transaction dispatch alias in earlier builds. */ - Qd?: (tr: ProseMirrorTransaction) => void; - /** Minified transaction dispatch alias in build 20261120.00. */ - Td?: (tr: ProseMirrorTransaction) => void; } /** Options accepted by `writePromptBox`. */ @@ -852,7 +784,11 @@ export interface FlowMcpRuntime { /** Clicks the upload trigger button or accepts upload consent dialogs. */ uploadUiAction: (action: string) => boolean; /** Opens the asset editor via Angular Router or grid tile UI controls. */ - openEditAsset: (assetId: string, mediaUrl: string | null, primaryMediaId: string | null) => Promise; + openEditAsset: ( + assetId: string, + mediaUrl: string | null, + primaryMediaId: string | null, + ) => Promise; /** Locates the enabled generation submit button and returns its viewport click point. */ submitGeneration: () => Promise; /** Creates Flow scenes and adds clips. */ diff --git a/ts/video_ops.ts b/ts/video_ops.ts index 0cc0e8c..3543893 100644 --- a/ts/video_ops.ts +++ b/ts/video_ops.ts @@ -4,7 +4,7 @@ // Trim Flow videos and drive the scene builder extend workflow. import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, withLViewMapCapture } from "./angular"; -import { findComposerWarning } from "./composer"; +import { findComposerWarning, NON_COMPOSER_PANELS, readPromptStateReason } from "./composer"; import { delay, elText, hoverProbe, isDisabledProp, isVisibleEnabled, legacyTile, videoTrimBounds } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; @@ -357,6 +357,7 @@ export async function videoOp(req: VideoOpRequest): Promise { if (!prompt) return { ok: false, error: "extend_prompt_required" }; const written = await writePromptBox(tb, prompt, { seeds: [composer.querySelector("flow-rich-text-editor"), composer], + excludeSelector: NON_COMPOSER_PANELS, strictSync: true, trySettingsClick: false, hoverScopeSelector: "flow-scene-builder", @@ -407,8 +408,7 @@ export async function videoOp(req: VideoOpRequest): Promise { !isVisibleEnabled(exactAfter) ) { const validatorDetail = - runtimeState.promptState?.Ff?.N7a?.() || - runtimeState.promptState?.lf?.jYa?.() || + readPromptStateReason(runtimeState.promptState) || readAngularTooltip(exactAfter) || ""; return validatorDetail