From ed9d98cfe70b29a2a8c9bd135e7b6fcb2ff3f47b Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:39:09 +0000 Subject: [PATCH] fix(flow): bind edit controllers with scene delegation - Verify ZX, su, QI, and kf descriptors in edit_builds and probeStore - Bind edit image and video prompt boxes on /edit/ and /scene/ routes - Exclude Agent, side, and history panels from composer discovery - Build PromptState.Gp payloads via _.QI with { kf, Te, Oe } fallback - Delegate one-clip scenes to /scene/ and select timeline clips - Fail fast on empty or multi-clip scenes and blocked editor alerts - Poll variant history to abort failed edits and save new variants --- src/assets.rs | 30 ++- src/characters.rs | 14 +- src/edit.rs | 341 ++++++++++++++++++++++++++++ src/generation.rs | 241 ++++++-------------- src/main.rs | 1 + src/mcp.rs | 3 +- src/queue.rs | 3 + src/service.rs | 7 +- ts/attach_ingredients.ts | 70 +++--- ts/composer.ts | 55 +++-- ts/edit_builds.ts | 212 ++++++++++++++++++ ts/edit_composer.ts | 419 +++++++++++++++++++++++++++++++++++ ts/frontend_compatibility.ts | 2 + ts/open_edit_asset.ts | 314 ++++++++++++++++++++------ ts/prompt_writer.ts | 29 ++- ts/read_store_snapshot.ts | 83 ++++++- ts/scene_tiles.ts | 21 +- ts/setup_generation.ts | 3 +- ts/submit_generation.ts | 80 ++++--- ts/types.ts | 37 +++- 20 files changed, 1621 insertions(+), 344 deletions(-) create mode 100644 src/edit.rs create mode 100644 ts/edit_builds.ts create mode 100644 ts/edit_composer.ts diff --git a/src/assets.rs b/src/assets.rs index c3c8975..5c06960 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -27,8 +27,27 @@ const MEDIA_URL_LOOKUPS: usize = 4; /// Time to resolve missing URLs in one asset list response. const ASSET_LIST_URL_BUDGET: Duration = Duration::from_secs(10); +/// Normalized media variant entry from tile or scene clip history. +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct FlowAssetVariant { + /// Variant media ID. + pub(crate) id: String, + /// Lowercase variant generation status (`"pending"`, `"scheduled"`, `"success"`, `"failed"`, or `"canceled"`). + #[serde(default)] + pub(crate) status: Option, + /// Failure description when variant generation failed or canceled. + #[serde(default)] + pub(crate) error: Option, + /// Resolved media URL when the variant completed. + #[serde(default)] + pub(crate) url: Option, + /// Generation prompt text for the variant when present. + #[serde(default)] + pub(crate) prompt: Option, +} + /// Media asset or scene item inside a Google Flow project. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub(crate) struct FlowAsset { /// Flow asset or tile ID. pub(crate) id: String, @@ -60,6 +79,15 @@ pub(crate) struct FlowAsset { /// Primary media ID for video trim and edit operations. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) primary_media_id: Option, + /// Parent scene ID when this video clip belongs to a scene. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) scene_id: Option, + /// Ordered clip workflow IDs when this asset is a scene tile. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) clip_ids: Option>, + /// Internal normalized variant history used to detect edit completions and failures. + #[serde(default, skip_serializing)] + pub(crate) variants: Vec, /// Character personality notes or introduction text. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) personality_notes: Option, diff --git a/src/characters.rs b/src/characters.rs index 12c6de2..d1ec45b 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -761,21 +761,9 @@ pub(crate) async fn create_or_update_character_job( id: media_id.clone().unwrap_or_else(|| char_id.clone()), name: persisted_name.clone(), kind: "image".to_string(), - prompt: None, url: src, - collection_id: None, - collection_name: None, - width: None, - height: None, - duration: None, primary_media_id: media_id, - personality_notes: None, - voice: None, - trim_start_seconds: None, - trim_end_seconds: None, - media_status: None, - media_error: None, - created_at: None, + ..FlowAsset::default() }; if let Ok(rec) = download_resolved_asset( engine, diff --git a/src/edit.rs b/src/edit.rs new file mode 100644 index 0000000..0c5bc74 --- /dev/null +++ b/src/edit.rs @@ -0,0 +1,341 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Google Flow asset editing and single-clip scene delegation. +//! +//! Opens image and video editors or delegates single-clip scenes and scene clips to the scene +//! builder, enforces fast-fail checks on blocked editors, and polls variant history. + +use anyhow::{Context, Result}; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::collections::HashSet; +use tokio::time::Duration; + +use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; +use crate::db::FlowDb; +use crate::download::eval_resolve_media_url; +use crate::engine::ChromeEngine; +use crate::generation::{ + AssetWaitSpec, 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, +} + +/// Fails immediately when any new variant on watched or created assets enters a failed state. +pub(crate) fn check_failed_new_variants( + assets: &[FlowAsset], + before_ids: &HashSet, + before_variants: &HashSet, + watch_id: Option<&str>, +) -> Result<()> { + for asset in assets { + if let Some(tid) = watch_id + && asset.id != tid + && before_ids.contains(&asset.id) + { + continue; + } + for variant in &asset.variants { + if before_variants.contains(&variant.id) { + continue; + } + if matches!( + variant.status.as_deref(), + Some("failed" | "canceled" | "error") + ) || variant.error.is_some() + { + let reason = variant + .error + .as_deref() + .or(variant.status.as_deref()) + .unwrap_or("failed"); + anyhow::bail!("Flow edit failed on {}: {}", asset.id, reason); + } + } + } + Ok(()) +} + +/// Resolves a newly completed variant on `asset` when `hx: false` leaves primary media unchanged. +pub(crate) async fn resolve_new_completed_variant( + engine: &ChromeEngine, + asset: &FlowAsset, + before_variants: &HashSet, +) -> Option { + for variant in asset.variants.iter().rev() { + if before_variants.contains(&variant.id) || variant.error.is_some() { + continue; + } + if matches!( + variant.status.as_deref(), + Some("pending" | "scheduled" | "failed" | "canceled" | "error") + ) { + continue; + } + let resolved_url = match variant.url.clone() { + Some(url) => Some(url), + None if variant.status.as_deref() == Some("success") => { + eval_resolve_media_url(engine, &variant.id, Some(6000)) + .await + .and_then(|val| { + val.get("download_url") + .or_else(|| val.get("url")) + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|u| u.starts_with("http")) + .map(str::to_string) + }) + } + None => None, + }; + if let Some(url) = resolved_url { + let mut out = asset.clone(); + out.primary_media_id = Some(variant.id.clone()); + out.url = Some(url); + if variant.prompt.is_some() { + out.prompt.clone_from(&variant.prompt); + } + out.media_status.clone_from(&variant.status); + return Some(out); + } + } + None +} + +/// Collects all media and variant IDs present across `assets` before submitting an edit. +fn collect_baseline_variant_ids(assets: &[FlowAsset]) -> HashSet { + let mut ids = HashSet::new(); + for asset in assets { + if let Some(ref primary_id) = asset.primary_media_id + && !primary_id.is_empty() + { + ids.insert(primary_id.clone()); + } + for variant in &asset.variants { + if !variant.id.is_empty() { + ids.insert(variant.id.clone()); + } + } + } + ids +} + +/// Resolves the target asset and optional parent scene ID, rejecting empty or multi-clip scenes. +fn resolve_edit_target( + matched: FlowAsset, + all_assets: &[FlowAsset], + label: &str, +) -> Result<(FlowAsset, Option)> { + if matched.kind != "scene" { + let parent_scene = matched.scene_id.clone(); + return Ok((matched, parent_scene)); + } + + let clips = matched.clip_ids.clone().unwrap_or_default(); + if clips.is_empty() { + anyhow::bail!( + "Cannot edit scene '{}' ({}): scene has no clips", + label, + matched.id + ); + } + if clips.len() > 1 { + anyhow::bail!( + "Cannot edit multi-clip scene '{}' ({}); specify one clip ID: {}", + label, + matched.id, + clips.join(", ") + ); + } + + let clip_id = &clips[0]; + let scene_id = matched.id.clone(); + let clip_asset = all_assets + .iter() + .find(|asset| asset.id == *clip_id) + .cloned() + .unwrap_or(FlowAsset { + id: clip_id.clone(), + name: matched.name, + kind: "video".to_string(), + collection_id: matched.collection_id, + collection_name: matched.collection_name, + width: matched.width, + height: matched.height, + duration: matched.duration, + scene_id: Some(scene_id.clone()), + created_at: matched.created_at, + ..FlowAsset::default() + }); + Ok((clip_asset, Some(scene_id))) +} + +/// Fails immediately when `openEditAsset` reports a blocked editor or duration/region alert. +fn check_open_edit_blocked(label: &str, open_res: &Value) -> Result<()> { + let blocked = open_res + .get("blocked") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let alert = open_res + .get("alert") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()); + let detail = open_res + .get("detail") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()); + let err_code = open_res + .get("error") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()); + + if blocked || alert.is_some() || err_code.is_some() { + let message = alert.or(detail).or(err_code).unwrap_or("editor is blocked"); + anyhow::bail!("Cannot edit '{}': {}", label, message); + } + Ok(()) +} + +/// Opens an edit flow for an asset matching `match_str`, submits `prompt`, and saves 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 matched = match_asset(&snap.assets, match_str, true) + .cloned() + .with_context(|| format!("No asset matches '{}' for edit", match_str))?; + + let before_ids: HashSet = snap.assets.iter().map(|a| a.id.clone()).collect(); + let before_variants = collect_baseline_variant_ids(&snap.assets); + + let label = if matched.name.is_empty() { + matched.id.clone() + } else { + matched.name.clone() + }; + let (target, delegated_scene_id) = resolve_edit_target(matched, &snap.assets, &label)?; + on_progress(format!("preparing edit for {}", label)); + + let edit_mode = if target.kind == "video" || delegated_scene_id.is_some() { + "video" + } else { + "image" + }; + + let mut open_res = engine + .call_flow_async( + "openEditAsset", + json!([ + target.id, + target.url, + target.primary_media_id, + delegated_scene_id + ]), + ) + .await + .unwrap_or_default(); + check_open_edit_blocked(&label, &open_res)?; + + let mut opened_in_ui = open_res + .get("opened") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + + 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; + ensure_flow_store(engine).await?; + open_res = engine + .call_flow_async( + "openEditAsset", + json!([ + target.id, + target.url, + target.primary_media_id, + delegated_scene_id + ]), + ) + .await + .unwrap_or_default(); + check_open_edit_blocked(&label, &open_res)?; + opened_in_ui = open_res + .get("opened") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + } else if opened_in_ui { + let _ = ensure_flow_store(engine).await; + } + + if !opened_in_ui { + anyhow::bail!( + "Could not open the Flow editor for {} asset '{}'", + edit_mode, + label + ); + } + + on_progress(format!("submitting edit for {}", label)); + let scene = SceneParams { + prompt: prompt.to_string(), + mode: Some(edit_mode.to_string()), + count: Some(1), + edit: Some(true), + ..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_ids, + before_variant_ids: Some(&before_variants), + 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?; + let out = collect_created_assets( + engine, + db, + created, + project_id, + project_title, + true, + &on_progress, + ) + .await; + ensure_project_workspace_root(engine).await?; + Ok(out) +} diff --git a/src/generation.rs b/src/generation.rs index b9f3f55..e1de01f 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -1,7 +1,7 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Google Flow media generation and asset editing. +//! Google Flow media generation and asset polling. //! //! Drives the Flow generation form through the browser TypeScript runtime and defines MCP //! request parameter structs for [`crate::queue::JobQueue`] tasks. @@ -14,9 +14,10 @@ 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::edit::{check_failed_new_variants, resolve_new_completed_variant}; use crate::engine::{ChromeEngine, NetworkResponseEvent, validate_local_files}; use crate::project::{ensure_flow_store, ensure_project_workspace_root}; use crate::queue::{ProgressCallback, SceneParams}; @@ -63,32 +64,24 @@ 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, -} - /// 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, + pub(crate) before_ids: &'a HashSet, + /// Variant and media IDs already present before edit submission. + pub(crate) before_variant_ids: Option<&'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) watch_updated: Option<(&'a str, Option<&'a str>, Option<&'a str>)>, /// 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 { @@ -118,6 +111,7 @@ async fn apply_generation_controls( "video_type": scene.video_type, "duration": scene.duration, "resolution": scene.resolution, + "edit": scene.edit, }); let setup_res = engine @@ -195,7 +189,7 @@ async fn apply_generation_controls( } let mut submit_res = engine - .call_flow_async("submitGeneration", json!([])) + .call_flow_async("submitGeneration", json!([scene.edit])) .await?; if submit_res.get("ok").and_then(|v| v.as_bool()) != Some(true) { let err = submit_res @@ -226,7 +220,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 +317,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, @@ -356,28 +350,35 @@ async fn wait_for_new_assets( } }; - let new_ones: Vec = snap - .assets - .iter() - .filter(|a| { - 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 - && a.url.is_some() + if let Some(before_variants) = spec.before_variant_ids { + let watch_id = spec.watch_updated.map(|(tid, _, _)| tid); + check_failed_new_variants(&snap.assets, spec.before_ids, before_variants, watch_id)?; + } + + let mut new_ones: Vec = Vec::new(); + for a in &snap.assets { + if !spec.before_ids.contains(&a.id) && a.url.is_some() { + new_ones.push(a.clone()); + continue; + } + if let Some((tid, prev_pmid, prev_url)) = spec.watch_updated + && a.id == tid + { + 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; + if a.url.is_some() && (pmid_changed || url_changed) { + new_ones.push(a.clone()); + } else if let Some(before_variants) = spec.before_variant_ids + && let Some(variant_asset) = + resolve_new_completed_variant(engine, a, before_variants).await { - 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; - return pmid_changed || url_changed; + new_ones.push(variant_asset); } - false - }) - .cloned() - .collect(); + } + } if new_ones.is_empty() { let new_tiles: Vec<&FlowAsset> = snap @@ -392,7 +393,29 @@ async fn wait_for_new_assets( .iter() .find(|a| a.id == tid) .map(|a| { - format!("{}:{}", a.id, a.media_status.as_deref().unwrap_or("none")) + let new_pending: Vec = spec + .before_variant_ids + .map(|bv| { + a.variants + .iter() + .filter(|v| !bv.contains(&v.id)) + .map(|v| { + format!( + "{}:{}:{}", + a.id, + v.id, + v.status.as_deref().unwrap_or("pending") + ) + }) + .collect() + }) + .unwrap_or_default(); + if !new_pending.is_empty() { + last_pending_count = new_pending.len(); + new_pending.join(",") + } else { + format!("{}:{}", a.id, a.media_status.as_deref().unwrap_or("none")) + } }) .unwrap_or_else(|| "none".to_string()) } else { @@ -573,6 +596,7 @@ pub(crate) async fn run_generation( engine, AssetWaitSpec { before_ids: &before, + before_variant_ids: None, watch_updated: None, expected_count, timeout_secs: 420, @@ -594,134 +618,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/queue.rs b/src/queue.rs index 0ba3b2e..a4939c2 100644 --- a/src/queue.rs +++ b/src/queue.rs @@ -112,6 +112,9 @@ pub(crate) struct SceneParams { /// Source asset match string for edit jobs. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) edit_from: Option, + /// Explicit flag marking an asset or scene clip edit context. + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) edit: Option, /// Character role key in `character_looks` whose saved look `flow_generate` appends to prompt. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) character_role: Option, diff --git a/src/service.rs b/src/service.rs index 4b8223b..7517c19 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( @@ -199,6 +199,7 @@ impl FlowService { let scene = SceneParams { prompt: req.prompt, edit_from: Some(req.r#match), + edit: Some(true), ..Default::default() }; Ok(self.queue.enqueue(scene).await) diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 10bef6d..a59e040 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -21,6 +21,12 @@ import { findTextbox, settingsOpen, } from "./composer"; +import { + EDIT_PROMPT_BOX_SELECTOR, + EXCLUDED_COMPOSER_SELECTOR, + isEditContext, + isExcludedComposerNode, +} from "./edit_composer"; import { characterLooksOf, cleanMediaId, @@ -91,7 +97,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 = isEditContext(cfg.edit); const ingredientTargets: IngredientTarget[] = []; const tileMap = runtimeState.store?.getTileMap?.(); @@ -250,9 +256,11 @@ export async function attachIngredients(cfg: GenerationConfig): Promise }); } - const promptBoxEl = !onEditPage - ? document.querySelector("flow-prompt-box") - : null; + const promptBoxEl = onEditPage + ? Array.from(document.querySelectorAll(EDIT_PROMPT_BOX_SELECTOR)).find( + (el) => !isExcludedComposerNode(el), + ) ?? null + : document.querySelector("flow-prompt-box"); const ingSearchRoots: ParentNode[] = [ ...(promptBoxEl ? [promptBoxEl] : []), ...(scope && scope !== document && scope !== promptBoxEl ? [scope] : []), @@ -269,6 +277,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise Array.from(root.querySelectorAll('button, [role="button"]')).some( (el) => isVisibleEnabled(el) && + !isExcludedComposerNode(el) && /add ingredients to the prompt box|\bingredients\b/i.test( ( el.getAttribute("aria-label") || @@ -283,6 +292,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise Array.from(root.querySelectorAll('button, [role="button"]')).some( (el) => isVisibleEnabled(el) && + !isExcludedComposerNode(el) && /^(?:start|end)$/i.test( (el.getAttribute("aria-label") || elText(el)).trim(), ), @@ -335,7 +345,7 @@ 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) || isExcludedComposerNode(el)) return false; const label = ( el.getAttribute("aria-label") || elText(el) || @@ -352,7 +362,7 @@ 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) || isExcludedComposerNode(el)) return false; const label = ( el.getAttribute("aria-label") || elText(el) || @@ -593,27 +603,29 @@ 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-edit-image-prompt-box flow-rich-text-editor"), + document.querySelector("flow-edit-video-prompt-box flow-rich-text-editor"), + 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) => !isExcludedComposerNode(el)); 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: EXCLUDED_COMPOSER_SELECTOR, strictSync: true, onCloseSettings: closeSettingsAndMenus, }); @@ -631,11 +643,11 @@ 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()), diff --git a/ts/composer.ts b/ts/composer.ts index 9f86053..b97f4ca 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -5,6 +5,13 @@ import { isLiveLView, readAngularTooltip, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; +import { + EDIT_PROMPT_BOX_SELECTOR, + EDIT_SCOPE_SELECTOR, + EXCLUDED_COMPOSER_SELECTOR, + isExcludedComposerNode, + resolveEditBasePromptBox, +} from "./edit_composer"; import { runtimeState } from "./state"; import type { BasePromptBoxInstance, @@ -17,9 +24,6 @@ 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"; - /** Detected quota or high-demand warning button inside a Flow composer. */ export interface ComposerWarning { /** Warning category (`"credit"` or `"high_demand"`). */ @@ -28,22 +32,35 @@ 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 excluded 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) && + !isExcludedComposerNode(el), ) ?? 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); + if (editFlag) { + for (const sel of [EDIT_PROMPT_BOX_SELECTOR, EDIT_SCOPE_SELECTOR]) { + const scopes = Array.from(document.querySelectorAll(sel)).filter( + (el) => !isExcludedComposerNode(el), + ); + for (const scope of scopes) { + const hit = composerTextbox(scope); + if (hit) return hit; + } + } + return composerTextbox(document); + } + const manualScope = document.querySelector( + "flow-prompt-box flow-base-prompt-box, flow-prompt-box", + ); + return composerTextbox(manualScope) || composerTextbox(document); } /** Closes the active Agent panel and waits for the manual prompt to become editable. */ @@ -52,7 +69,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"); @@ -227,11 +244,13 @@ 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 || isExcludedComposerNode(startEl)) return null; let cur: Element | null = startEl; for (let depth = 0; depth < 6 && cur; depth += 1) { + if (isExcludedComposerNode(cur)) return null; let lv: NgLView | null = resolveLView(cur); for (let pDepth = 0; pDepth < 6 && Array.isArray(lv); pDepth += 1) { + if (lv[0] instanceof Node && isExcludedComposerNode(lv[0])) break; for (const cand of lv) { if (isBasePromptBoxInst(cand)) return cand; } @@ -268,18 +287,14 @@ export function findLiveBasePromptBox( document.querySelector("flow-prompt-box flow-base-prompt-box"), ); } - return scanElementForBasePromptBox( - document.querySelector( - "flow-edit-video-prompt-box flow-base-prompt-box, flow-edit-video-prompt-box", - ), - ); + return resolveEditBasePromptBox(scanElementForBasePromptBox); } /** Returns true when a custom warning element or one of its children is visible on screen. */ function isWarningElementVisible(el: Element, excludeAgent: boolean): boolean { if (!(el instanceof HTMLElement) || !el.isConnected) return false; if (el.closest('[hidden], [aria-hidden="true"]')) return false; - if (excludeAgent && el.closest(AGENT_COMPOSER)) return false; + if (excludeAgent && el.closest(EXCLUDED_COMPOSER_SELECTOR)) return false; const style = window.getComputedStyle(el); if (style.display === "none" || style.visibility === "hidden") return false; if (el.getClientRects().length > 0) return true; diff --git a/ts/edit_builds.ts b/ts/edit_builds.ts new file mode 100644 index 0000000..518e964 --- /dev/null +++ b/ts/edit_builds.ts @@ -0,0 +1,212 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Verified Angular edit controller descriptors and prompt payload builders by build. + +import { readOwn } from "./angular"; +import { readBuildLabel } from "./frontend_builds"; +import type { + PromptDocumentPayload, + PromptTextSegment, + StoreProbeCheck, +} from "./types"; + +/** Exported symbols and controller members verified for asset editing in one Flow build. */ +export interface EditBuildFormat { + /** Exported `flow-edit-image-prompt-box` class on `default_AiSandboxAngularFrontend`. */ + imagePromptBox: string; + /** Exported `flow-scene-builder` class on `default_AiSandboxAngularFrontend`. */ + sceneBuilder: string; + /** Exported `flow-editor-dispatcher` class on `default_AiSandboxAngularFrontend`. */ + editorDispatcher: string; + /** Exported `flow-base-prompt-box` class on `default_AiSandboxAngularFrontend`. */ + basePromptBox: string; + /** Exported `flow-editor-side-panel` class on `default_AiSandboxAngularFrontend`. */ + sidePanel: string; + /** Exported function that wraps plain text into a prompt segment document. */ + promptBuilder: string; + /** Property key holding text segments in the serialized prompt document. */ + promptSegmentsKey: "kf" | "Te" | "Oe"; + /** Child `flow-base-prompt-box` query signal on `flow-edit-image-prompt-box`. */ + imageBoxChild: string; + /** Shared `PromptStateController` field on edit prompt boxes. */ + promptState: string; + /** Signal reporting whether submission is disabled on edit prompt boxes. */ + submitDisabled: string; + /** Signal reporting the disabled reason on `flow-edit-video-prompt-box`. */ + submitDisabledReason: string; + /** Input signal holding the selected timeline clip on `flow-edit-video-prompt-box`. */ + selectedClip: string; + /** Input signal reporting region restriction on `flow-edit-video-prompt-box`. */ + regionBlockedInput: string; + /** Computed signal reporting active region block on `flow-edit-video-prompt-box`. */ + regionBlocked: string; + /** Computed signal returning region restriction text on `flow-edit-video-prompt-box`. */ + regionBlockedMessage: string; + /** Computed signal reporting excessive clip duration on `flow-edit-video-prompt-box`. */ + tooLong: string; + /** Computed signal returning maximum duration alert text on `flow-edit-video-prompt-box`. */ + tooLongMessage: string; + /** Computed signal reporting insufficient clip duration on `flow-edit-video-prompt-box`. */ + tooShort: string; + /** Computed signal returning minimum duration alert text on `flow-edit-video-prompt-box`. */ + tooShortMessage: string; + /** Computed signal reporting unsupported clip resolution on `flow-edit-video-prompt-box`. */ + resolutionBlocked: string; + /** String field returning unsupported resolution alert text on `flow-edit-video-prompt-box`. */ + resolutionBlockedMessage: string; + /** Input signal reporting whether the selected clip is still loading. */ + clipLoading: string; + /** Input signal listing timeline clips on `flow-scene-timeline`. */ + timelineClips: string; + /** Timeline selection service field on `flow-scene-timeline`. */ + timelineService: string; + /** Writable signal holding the selected clip workflow ID on the timeline service. */ + timelineSelectedSignal: string; + /** Read signal returning the selected clip workflow ID on the timeline service. */ + timelineSelectedRead: string; + /** Output emitter firing when a clip is selected on `flow-scene-timeline`. */ + timelineSelectOutput: string; +} + +/** Verified edit descriptors for `boq_labs-ai-sandbox-frontend_20261120.00_p0`. */ +const NOVEMBER_20_EDIT_BUILD: EditBuildFormat = { + imagePromptBox: "ZX", + sceneBuilder: "su", + editorDispatcher: "ru", + basePromptBox: "UX", + sidePanel: "H6", + promptBuilder: "QI", + promptSegmentsKey: "kf", + imageBoxChild: "zr", + promptState: "Qa", + submitDisabled: "wf", + submitDisabledReason: "UO", + selectedClip: "Rn", + regionBlockedInput: "eJa", + regionBlocked: "lT", + regionBlockedMessage: "iPa", + tooLong: "ina", + tooLongMessage: "dpb", + tooShort: "AKa", + tooShortMessage: "epb", + resolutionBlocked: "nna", + resolutionBlockedMessage: "sXa", + clipLoading: "H_", + timelineClips: "zh", + timelineService: "Ef", + timelineSelectedSignal: "la", + timelineSelectedRead: "Ca", + timelineSelectOutput: "WBa", +}; + +/** Verified edit controller formats indexed by exact Flow front-end build label. */ +const VERIFIED_EDIT_BUILDS: ReadonlyMap = new Map([ + ["boq_labs-ai-sandbox-frontend_20261120.00_p0", NOVEMBER_20_EDIT_BUILD], +]); + +/** Returns the verified edit controller format for `label`, or `undefined`. */ +export function editBuild(label: string | null): EditBuildFormat | undefined { + return label === null ? undefined : VERIFIED_EDIT_BUILDS.get(label); +} + +/** Returns the verified edit controller format of the active page, or `undefined`. */ +export function activeEditBuild(): EditBuildFormat | undefined { + return editBuild(readBuildLabel()); +} + +/** Calls the verified prompt builder and checks that it returns a segment list under `key`. */ +function callVerifiedPromptBuilder( + namespace: unknown, + builderKey: string, + segmentsKey: string, + sample: string, +): PromptDocumentPayload | null { + const fn = readOwn(namespace, builderKey); + if (typeof fn !== "function") return null; + try { + const built: unknown = (fn as (text: string) => unknown).call(namespace, sample); + if (!built || typeof built !== "object") return null; + const segments = readOwn(built, segmentsKey); + if (!Array.isArray(segments) || segments.length === 0) return null; + const first = segments[0]; + if ( + !first || + typeof first !== "object" || + readOwn(first, "type") !== "text" || + readOwn(first, "content") !== sample + ) { + return null; + } + return built as PromptDocumentPayload; + } catch { + return null; + } +} + +/** Builds a serialized prompt payload through `_.QI` with `{ kf, Te, Oe }` fallback. */ +export function buildPromptPayload(content: string): PromptDocumentPayload { + const format = activeEditBuild(); + if (format) { + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const built = callVerifiedPromptBuilder( + namespace, + format.promptBuilder, + format.promptSegmentsKey, + content, + ); + if (built) return built; + } + const segments: PromptTextSegment[] = [{ type: "text", content }]; + return { kf: segments, Te: segments, Oe: segments }; +} + +/** Validates edit controller and prompt builder descriptors for builds in `VERIFIED_EDIT_BUILDS`. */ +export function editBuildChecks(build: string | null): StoreProbeCheck[] { + const format = editBuild(build); + if (!format) return []; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const imageCtor = readOwn(namespace, format.imagePromptBox); + const sceneCtor = readOwn(namespace, format.sceneBuilder); + const promptFn = readOwn(namespace, format.promptBuilder); + const probePayload = callVerifiedPromptBuilder( + namespace, + format.promptBuilder, + format.promptSegmentsKey, + "probe", + ); + return [ + { + name: "edit_image_controller", + ok: typeof imageCtor === "function", + detail: + typeof imageCtor === "function" + ? `${format.imagePromptBox} present` + : `missing ${format.imagePromptBox}`, + }, + { + name: "edit_scene_controller", + ok: typeof sceneCtor === "function", + detail: + typeof sceneCtor === "function" + ? `${format.sceneBuilder} present` + : `missing ${format.sceneBuilder}`, + }, + { + name: "edit_prompt_builder", + ok: typeof promptFn === "function", + detail: + typeof promptFn === "function" + ? `${format.promptBuilder} present` + : `missing ${format.promptBuilder}`, + }, + { + name: "edit_prompt_segments", + ok: probePayload !== null, + detail: + probePayload !== null + ? `${format.promptSegmentsKey} verified` + : `missing ${format.promptSegmentsKey} segments`, + }, + ]; +} diff --git a/ts/edit_composer.ts b/ts/edit_composer.ts new file mode 100644 index 0000000..9951b28 --- /dev/null +++ b/ts/edit_composer.ts @@ -0,0 +1,419 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Bind Angular image/video edit prompt controllers, select scene timeline clips, and read alerts. + +import { isLiveLView, readOwn, resolveLView } from "./angular"; +import { delay, elText } from "./dom"; +import { activeEditBuild } from "./edit_builds"; +import { runtimeState } from "./state"; +import type { BasePromptBoxInstance, NgLView, PromptStateController } from "./types"; + +/** Containers that belong to the Agent composer and must never be targeted by manual or edit flows. */ +export const AGENT_COMPOSER_SELECTOR = + "flow-agent-panel, .agent-panel-wrapper, flow-creative-agent-prompt-box"; + +/** Editor side and history panels that must never be targeted as edit composers or submit controls. */ +export const EDITOR_SIDE_PANEL_SELECTOR = + "flow-editor-side-panel, flow-editor-history-panel, flow-editor-side-panel-switcher"; + +/** Combined selector of Agent and side-panel containers excluded on all routes. */ +export const EXCLUDED_COMPOSER_SELECTOR = `${AGENT_COMPOSER_SELECTOR}, ${EDITOR_SIDE_PANEL_SELECTOR}`; + +/** Direct selector for Flow image and video edit prompt boxes. */ +export const EDIT_PROMPT_BOX_SELECTOR = + "flow-edit-image-prompt-box, flow-edit-video-prompt-box"; + +/** Scoped container selector for edit prompt discovery across editor and scene builder views. */ +export const EDIT_SCOPE_SELECTOR = + "flow-edit-image-prompt-box, flow-edit-video-prompt-box, flow-editor-page, flow-scene-builder"; + +/** Live Angular controller interface for `flow-edit-image-prompt-box` (`_.ZX`). */ +export interface EditImagePromptBoxInstance { + /** Shared `PromptStateController` instance. */ + Qa?: PromptStateController; + /** Child `flow-base-prompt-box` signal query. */ + zr?: () => BasePromptBoxInstance | undefined; + /** Signal reporting whether submission is disabled. */ + wf?: () => boolean; +} + +/** Live Angular controller interface for `flow-edit-video-prompt-box` (`l6`). */ +export interface EditVideoPromptBoxInstance { + /** Shared `PromptStateController` instance. */ + Qa?: PromptStateController; + /** Selected timeline clip signal. */ + Rn?: () => unknown; + /** Clip loading input signal. */ + H_?: () => boolean; + /** Region restriction input signal. */ + eJa?: () => boolean; + /** Computed region restriction signal. */ + lT?: () => boolean; + /** Computed region restriction message signal. */ + iPa?: () => string; + /** Computed too-long clip signal. */ + ina?: () => boolean; + /** Computed too-long clip message signal. */ + dpb?: () => string; + /** Computed too-short clip signal. */ + AKa?: () => boolean; + /** Computed too-short clip message signal. */ + epb?: () => string; + /** Computed unsupported-resolution signal. */ + nna?: () => boolean; + /** Unsupported-resolution static text. */ + sXa?: string; + /** Computed submit disabled signal. */ + wf?: () => boolean; + /** Computed submit disabled reason signal. */ + UO?: () => string | undefined; +} + +/** Returns true when `pathname` is an asset editor (`/edit/`) or scene builder (`/scene/`) route. */ +export function isEditRoute(pathname = location.pathname || ""): boolean { + return /\/(?:edit|scene)\//.test(pathname); +} + +/** Resolves whether edit mode is active from an explicit flag or the current browser route. */ +export function isEditContext(explicitEdit?: boolean | null): boolean { + return typeof explicitEdit === "boolean" ? explicitEdit : isEditRoute(); +} + +/** Returns true when `node` lies inside an excluded Agent or editor side/history panel. */ +export function isExcludedComposerNode(node: Node | null | undefined): boolean { + if (!node) return false; + const el = node instanceof Element ? node : node.parentElement; + return Boolean(el?.closest(EXCLUDED_COMPOSER_SELECTOR)); +} + +/** Calls a zero-argument signal or getter method on `target` when present. */ +function callSignal(target: unknown, key: string): unknown { + const fn = readOwn(target, key); + if (typeof fn !== "function") return undefined; + try { + return (fn as () => unknown).call(target); + } catch { + return undefined; + } +} + +/** Scans Angular LViews anchored at `elements` (and `ngLViewMap`) for an instance matching `pred`. */ +function findControllerInViews( + elements: Element[], + pred: (cand: unknown) => cand is T, +): T | null { + for (const startEl of elements) { + if (isExcludedComposerNode(startEl)) continue; + const probes = [startEl, startEl.firstElementChild].filter( + (n): n is Element => Boolean(n && !isExcludedComposerNode(n)), + ); + for (const node of probes) { + let lv: NgLView | null = resolveLView(node); + for (let d = 0; d < 6 && Array.isArray(lv); d += 1) { + if (lv[0] instanceof Node && isExcludedComposerNode(lv[0])) break; + for (const cand of lv) { + if (pred(cand)) return cand; + } + lv = Array.isArray(lv[3]) ? lv[3] : Array.isArray(lv[15]) ? lv[15] : null; + } + } + } + if (runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if (!isLiveLView(lv)) continue; + if (lv[0] instanceof Node && isExcludedComposerNode(lv[0])) continue; + for (const cand of lv) { + if (pred(cand)) return cand; + } + } + } + return null; +} + +/** Binds the live `flow-edit-image-prompt-box` (`_.ZX`) Angular controller when mounted. */ +export function findEditImagePromptBox(): EditImagePromptBoxInstance | null { + const format = activeEditBuild(); + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const ctor = format ? readOwn(namespace, format.imagePromptBox) : undefined; + const childKey = format?.imageBoxChild ?? "zr"; + const qaKey = format?.promptState ?? "Qa"; + const isImageBox = (cand: unknown): cand is EditImagePromptBoxInstance => { + if (!cand || typeof cand !== "object" || cand instanceof Node) return false; + if (typeof ctor === "function" && cand instanceof ctor) return true; + return ( + Boolean(readOwn(cand, qaKey)) && + typeof readOwn(cand, childKey) === "function" && + (typeof readOwn(cand, "yx") === "function" || + typeof readOwn(cand, "bia") === "function" || + typeof readOwn(cand, "VHa") === "function") + ); + }; + const hosts = Array.from( + document.querySelectorAll("flow-edit-image-prompt-box"), + ).filter((el) => !isExcludedComposerNode(el)); + return findControllerInViews(hosts, isImageBox); +} + +/** Binds the live `flow-edit-video-prompt-box` (`l6`) Angular controller when mounted. */ +export function findEditVideoPromptBox(): EditVideoPromptBoxInstance | null { + const format = activeEditBuild(); + const qaKey = format?.promptState ?? "Qa"; + const clipKey = format?.selectedClip ?? "Rn"; + const disabledKey = format?.submitDisabled ?? "wf"; + const reasonKey = format?.submitDisabledReason ?? "UO"; + const tooLongKey = format?.tooLong ?? "ina"; + const regionKey = format?.regionBlockedInput ?? "eJa"; + const regionComputedKey = format?.regionBlocked ?? "lT"; + const loadingKey = format?.clipLoading ?? "H_"; + const isVideoBox = (cand: unknown): cand is EditVideoPromptBoxInstance => { + if (!cand || typeof cand !== "object" || cand instanceof Node) return false; + return ( + Boolean(readOwn(cand, qaKey)) && + typeof readOwn(cand, clipKey) === "function" && + typeof readOwn(cand, disabledKey) === "function" && + (typeof readOwn(cand, reasonKey) === "function" || + typeof readOwn(cand, tooLongKey) === "function" || + typeof readOwn(cand, regionKey) === "function" || + typeof readOwn(cand, regionComputedKey) === "function" || + typeof readOwn(cand, loadingKey) === "function") + ); + }; + const hosts = Array.from( + document.querySelectorAll("flow-edit-video-prompt-box"), + ).filter((el) => !isExcludedComposerNode(el)); + return findControllerInViews(hosts, isVideoBox); +} + +/** Resolves the active `BasePromptBoxInstance` inside image or video edit prompt boxes. */ +export function resolveEditBasePromptBox( + scanElement: (el: Element | null) => BasePromptBoxInstance | null, +): BasePromptBoxInstance | null { + const format = activeEditBuild(); + const childKey = format?.imageBoxChild ?? "zr"; + const imageBox = findEditImagePromptBox(); + if (imageBox) { + const child = callSignal(imageBox, childKey); + if (child && typeof child === "object" && !(child instanceof Node)) { + return child as BasePromptBoxInstance; + } + } + const candidates = Array.from( + document.querySelectorAll( + "flow-edit-image-prompt-box flow-base-prompt-box, flow-edit-image-prompt-box, flow-edit-video-prompt-box flow-base-prompt-box, flow-edit-video-prompt-box", + ), + ).filter((el) => !isExcludedComposerNode(el)); + for (const el of candidates) { + const found = scanElement(el); + if (found) return found; + } + return null; +} + +/** Cleans Material icon ligatures and action button labels from an editor alert element. */ +function cleanAlertElementText(el: Element): string { + const dedicated = el.querySelector(".too-long-text"); + if (dedicated) { + const txt = elText(dedicated).trim(); + if (txt) return txt; + } + const clone = el.cloneNode(true); + if (clone instanceof Element) { + for (const extra of clone.querySelectorAll("button, mat-icon, .too-long-icon")) { + extra.remove(); + } + const stripped = (clone.textContent || "").replace(/\s+/g, " ").trim(); + if (stripped) return stripped; + } + return elText(el) + .split(/\r?\n/) + .map((line) => line.trim()) + .filter( + (line) => + line.length > 0 && + !/^(?:warning|error|info|bolt|content_cut|trim automatically|exit extend mode)$/i.test( + line, + ), + ) + .join(" ") + .trim(); +} + +/** Returns true when `el` is rendered and visible outside excluded panels. */ +function isVisibleAlertElement(el: Element): boolean { + if (!(el instanceof HTMLElement) || !el.isConnected) return false; + if (isExcludedComposerNode(el)) return false; + if (el.closest('[hidden], [aria-hidden="true"]')) return false; + const style = window.getComputedStyle(el); + if (style.display === "none" || style.visibility === "hidden") return false; + return el.getClientRects().length > 0 || el.textContent?.trim() !== ""; +} + +/** Reads any active `.too-long-overlay` `[role="alert"]` or `l6` controller block reason. */ +export function readEditBlockReason(): string | null { + const alertEls = Array.from( + document.querySelectorAll( + '.too-long-overlay, flow-edit-video-prompt-box [role="alert"], flow-edit-image-prompt-box [role="alert"], flow-scene-builder .too-long-overlay', + ), + ); + for (const el of alertEls) { + if (!isVisibleAlertElement(el)) continue; + const msg = cleanAlertElementText(el); + if (msg) return msg; + } + + const videoBox = findEditVideoPromptBox(); + if (!videoBox) return null; + const format = activeEditBuild(); + const loading = Boolean(callSignal(videoBox, format?.clipLoading ?? "H_")); + if (loading) return null; + + const regionBlocked = + Boolean(callSignal(videoBox, format?.regionBlocked ?? "lT")) || + (Boolean(callSignal(videoBox, format?.selectedClip ?? "Rn")) && + Boolean(callSignal(videoBox, format?.regionBlockedInput ?? "eJa"))); + if (regionBlocked) { + const msg = + callSignal(videoBox, format?.regionBlockedMessage ?? "iPa") ?? + callSignal(videoBox, format?.submitDisabledReason ?? "UO"); + return typeof msg === "string" && msg.trim() + ? msg.trim() + : "Editing uploaded videos is not available in your region right now."; + } + + if (Boolean(callSignal(videoBox, format?.tooLong ?? "ina"))) { + const msg = callSignal(videoBox, format?.tooLongMessage ?? "dpb"); + return typeof msg === "string" && msg.trim() + ? msg.trim() + : "Videos longer than 10s can't be edited. Trim to 10s or under to edit."; + } + + if (Boolean(callSignal(videoBox, format?.resolutionBlocked ?? "nna"))) { + const msg = readOwn(videoBox, format?.resolutionBlockedMessage ?? "sXa"); + return typeof msg === "string" && msg.trim() + ? msg.trim() + : "Videos of this resolution cannot be edited currently."; + } + + if (Boolean(callSignal(videoBox, format?.tooShort ?? "AKa"))) { + const msg = callSignal(videoBox, format?.tooShortMessage ?? "epb"); + return typeof msg === "string" && msg.trim() + ? msg.trim() + : "Video clip is shorter than the minimum editable duration."; + } + + const disabledReason = callSignal(videoBox, format?.submitDisabledReason ?? "UO"); + if (typeof disabledReason === "string" && disabledReason.trim()) { + return disabledReason.trim(); + } + return null; +} + +/** Selects `clipWorkflowId` on `` and waits for clip state to settle. */ +export async function selectSceneTimelineClip( + clipWorkflowId: string, +): Promise { + const targetId = String(clipWorkflowId || "").trim(); + if (!targetId) return false; + const format = activeEditBuild(); + const clipsKey = format?.timelineClips ?? "zh"; + const serviceKey = format?.timelineService ?? "Ef"; + const setSigKey = format?.timelineSelectedSignal ?? "la"; + const readSigKey = format?.timelineSelectedRead ?? "Ca"; + const outKey = format?.timelineSelectOutput ?? "WBa"; + + interface TimelineController { + [key: string]: unknown; + } + + const isTimeline = (cand: unknown): cand is TimelineController => + Boolean( + cand && + typeof cand === "object" && + !(cand instanceof Node) && + typeof readOwn(cand, clipsKey) === "function" && + readOwn(cand, serviceKey) != null, + ); + + let selected = false; + for (let attempt = 0; attempt < 25; attempt += 1) { + const timelines = Array.from( + document.querySelectorAll("flow-scene-timeline"), + ).filter((el) => !isExcludedComposerNode(el)); + const ctrl = findControllerInViews(timelines, isTimeline); + const clipsRaw = ctrl ? callSignal(ctrl, clipsKey) : undefined; + const clips = Array.isArray(clipsRaw) ? clipsRaw : []; + const clipIdx = clips.findIndex( + (item) => + String(readOwn(item, "workflowId") || readOwn(item, "id") || "") === + targetId, + ); + + const domClips = Array.from( + document.querySelectorAll( + "flow-scene-timeline .clip, flow-scene-builder .clip", + ), + ).filter((el): el is HTMLElement => el instanceof HTMLElement && !isExcludedComposerNode(el)); + + if (clipIdx >= 0 && domClips[clipIdx]) { + const targetEl = domClips[clipIdx]; + const clickTarget = + targetEl.querySelector("div") || targetEl; + clickTarget.click(); + selected = true; + } + + if (ctrl) { + const svc = readOwn(ctrl, serviceKey); + const curSelected = callSignal(svc, readSigKey); + if (curSelected === targetId) { + selected = true; + } else if (clipIdx >= 0 || clips.length === 0) { + const sig = readOwn(svc, setSigKey) as { set?: (id: string) => void } | undefined; + if (typeof sig?.set === "function") { + try { + sig.set(targetId); + selected = true; + } catch { + // Fall through to DOM click fallback. + } + } + const emitter = readOwn(ctrl, outKey) as { emit?: (id: string) => void } | undefined; + if (typeof emitter?.emit === "function") { + try { + emitter.emit(targetId); + selected = true; + } catch { + // Ignore emitter errors on partially initialized views. + } + } + } + } + + if (!selected && domClips.length === 1) { + const clickTarget = + domClips[0].querySelector("div") || domClips[0]; + clickTarget.click(); + selected = true; + } + + const videoBox = findEditVideoPromptBox(); + const activeClip = videoBox + ? callSignal(videoBox, format?.selectedClip ?? "Rn") + : undefined; + if (selected && (activeClip != null || readEditBlockReason() !== null)) { + break; + } + await delay(100); + } + + for (let waitIdx = 0; waitIdx < 25; waitIdx += 1) { + const videoBox = findEditVideoPromptBox(); + const loading = videoBox + ? Boolean(callSignal(videoBox, format?.clipLoading ?? "H_")) + : false; + if (!loading) break; + await delay(100); + } + return selected; +} diff --git a/ts/frontend_compatibility.ts b/ts/frontend_compatibility.ts index 26f1f1a..bf5041c 100644 --- a/ts/frontend_compatibility.ts +++ b/ts/frontend_compatibility.ts @@ -16,6 +16,7 @@ import type { FrontendFormats, ProjectUploadFormat, } from "./frontend_builds"; +import { editBuildChecks } from "./edit_builds"; import { findProjectPage } from "./project_upload"; import { projectWriteChecks } from "./project_store"; import { legacyTile, pickTileUrl } from "./dom"; @@ -435,6 +436,7 @@ export function probeStore(): StoreProbeResult { const views = runtimeState.ngLViewMap; const checks = [ verified, + ...editBuildChecks(build), { name: "lview_registry", ok: views instanceof Map, diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..e813fbe 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -1,7 +1,7 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Open the Google Flow asset editor via Angular Router or tile controls. +// Open the Google Flow asset editor or delegate scene clips via Angular Router. import { buildProjectUrl, @@ -10,43 +10,228 @@ import { readOwn, type NgContextCarrier, } from "./angular"; -import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; -import { clearStore } from "./state"; +import { + delay, + elText, + isDisabledProp, + isTrashedTile, + isVisibleEnabled, +} from "./dom"; +import { + EDIT_PROMPT_BOX_SELECTOR, + EDIT_SCOPE_SELECTOR, + isExcludedComposerNode, + readEditBlockReason, + selectSceneTimelineClip, +} from "./edit_composer"; +import { sceneClipIds, sceneContents } from "./scene_tiles"; +import { clearStore, runtimeState } from "./state"; + +/** Finds a visible enabled prompt textbox inside edit containers outside excluded panels. */ +function findVisibleTextbox(): Element | null { + for (const scopeSel of [EDIT_PROMPT_BOX_SELECTOR, EDIT_SCOPE_SELECTOR]) { + for (const root of document.querySelectorAll(scopeSel)) { + if (isExcludedComposerNode(root)) continue; + const candidates = Array.from( + root.querySelectorAll( + '.ProseMirror[contenteditable="true"], [role="textbox"][contenteditable="true"], textarea', + ), + ); + const hit = candidates.find( + (el) => + el.getClientRects().length > 0 && + !isDisabledProp(el) && + !isExcludedComposerNode(el), + ); + if (hit) return hit; + } + } + return null; +} + +/** Resolves scene delegation targets for `SCENE` tiles and clips owned by a scene. */ +function resolveSceneDelegation( + assetId: string, + explicitSceneId?: string | null, +): + | { kind: "blocked"; error: string; detail: string; clipIds: string[] } + | { kind: "scene"; sceneId: string; clipId: string } + | { kind: "direct" } { + const explicit = String(explicitSceneId || "").trim(); + const store = runtimeState.store; + const tileMap = store?.getTileMap?.(); + + if (tileMap instanceof Map && assetId) { + const rawTile = tileMap.get(assetId); + const rawType = String(rawTile?.type || "").toUpperCase(); + if (rawTile && rawType === "SCENE") { + const clipIds = sceneClipIds(rawTile); + if (clipIds.length === 0) { + return { + kind: "blocked", + error: "empty_scene", + detail: "Scene contains no clips to edit", + clipIds: [], + }; + } + if (clipIds.length > 1) { + return { + kind: "blocked", + error: "multi_clip_scene", + detail: `Scene contains multiple clips (${clipIds.join(", ")})`, + clipIds, + }; + } + return { kind: "scene", sceneId: assetId, clipId: clipIds[0] }; + } + + if (explicit) { + return { kind: "scene", sceneId: explicit, clipId: assetId }; + } + + if (rawType !== "IMAGE" && rawType !== "CHARACTER") { + for (const st of tileMap.values()) { + if (!st || isTrashedTile(st)) continue; + if (String(st.type || "").toUpperCase() !== "SCENE") continue; + const sid = String(st.id || st.workflowId || "").trim(); + if (!sid) continue; + const { history } = sceneContents(st); + const inScene = + sceneClipIds(st).includes(assetId) || history.has(assetId); + if (inScene) { + return { kind: "scene", sceneId: sid, clipId: assetId }; + } + } + } + } else if (explicit && assetId) { + return { kind: "scene", sceneId: explicit, clipId: assetId }; + } -/** Navigates to `/edit/` using Angular Router or triggers an inline tile edit action. */ + return { kind: "direct" }; +} + +/** Opens `/edit/` or delegates 1-clip scenes and scene clips to `/scene/`. */ export async function openEditAsset( assetId: string, mediaUrl: string | null, primaryMediaId: string | null, + sceneId?: string | null, ): Promise { const idStr = String(assetId || "").trim(); + const delegation = resolveSceneDelegation(idStr, sceneId); + if (delegation.kind === "blocked") { + return { + opened: false, + blocked: true, + error: delegation.error, + alert: delegation.detail, + detail: delegation.detail, + clip_ids: delegation.clipIds, + }; + } + + const pm = /\/project\/([^/?#]+)/.exec(location.pathname || ""); + const pid = pm ? pm[1] : runtimeState.store?.projectId || null; + const router = pid ? findRouter() : null; + + if (delegation.kind === "scene") { + const targetSceneId = delegation.sceneId; + const targetClipId = delegation.clipId; + let onSceneBuilder = + (location.pathname || "").includes(`/scene/${targetSceneId}`) && + Boolean(document.querySelector("flow-scene-builder")); + + if (!onSceneBuilder && router && pid) { + await navigateSpa(router, ["/project", pid, "scene", targetSceneId]); + for (let i = 0; i < 60; i += 1) { + if ( + (location.pathname || "").includes(`/scene/${targetSceneId}`) && + document.querySelector("flow-scene-builder") + ) { + onSceneBuilder = true; + break; + } + await delay(100); + } + } + + if (onSceneBuilder) { + for (let i = 0; i < 40; i += 1) { + if ( + document.querySelector( + "flow-scene-timeline, flow-edit-video-prompt-box", + ) + ) { + break; + } + await delay(100); + } + await selectSceneTimelineClip(targetClipId); + for (let i = 0; i < 20; i += 1) { + if (findVisibleTextbox() || readEditBlockReason() !== null) break; + await delay(100); + } + const alertText = readEditBlockReason(); + clearStore(); + if (alertText) { + return { + opened: true, + blocked: true, + error: "editor_blocked", + alert: alertText, + detail: alertText, + method: "scene_delegation", + view: "scene_builder", + scene_id: targetSceneId, + clip_id: targetClipId, + }; + } + return { + opened: true, + blocked: false, + method: "scene_delegation", + view: "scene_builder", + scene_id: targetSceneId, + clip_id: targetClipId, + has_textbox: Boolean(findVisibleTextbox()), + }; + } + + if (pid) { + return { + opened: false, + edit_url: buildProjectUrl(pid, ["scene", targetSceneId]), + scene_id: targetSceneId, + clip_id: targetClipId, + method: "route_fallback_needed", + }; + } + return { opened: false, method: "none" }; + } + const candidateIds = Array.from( new Set([idStr, String(primaryMediaId || "").trim()].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 + let viewKind: string | null = null; + if ((location.pathname || "").includes("/edit/")) { + const edPage = document.querySelector( + "flow-editor-page, flow-image-editor, flow-edit-image-prompt-box", ); + const sbPage = document.querySelector("flow-scene-builder"); + if (edPage || sbPage) { + viewKind = sbPage ? "scene_builder" : "editor_page"; + } } - 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; + if (!viewKind && router && pid && candidateIds.length > 0) { for (const candId of candidateIds) { await navigateSpa(router, ["/project", pid, "edit", candId]); for (let i = 0; i < 60; i += 1) { const onRoute = (location.pathname || "").includes("/edit/"); - const edPage = document.querySelector("flow-editor-page"); + const edPage = document.querySelector( + "flow-editor-page, flow-image-editor, flow-edit-image-prompt-box", + ); const sbPage = document.querySelector("flow-scene-builder"); if (onRoute && (edPage || sbPage)) { viewKind = sbPage ? "scene_builder" : "editor_page"; @@ -56,57 +241,49 @@ export async function openEditAsset( } if (viewKind) break; } + } - if (viewKind) { - for (let i = 0; i < 25; i += 1) { - if (findVisibleTextbox()) break; - await delay(100); - } - if (viewKind === "scene_builder" && !findVisibleTextbox()) { - const sb = document.querySelector("flow-scene-builder") || document; - const clip = sb.querySelector( - '[class*="clip"], [data-testid*="clip"], video', - ); - if (clip instanceof HTMLElement) { - clip.click(); - await delay(200); - } - if (!findVisibleTextbox()) { - const editTrigger = Array.from( - sb.querySelectorAll('button, [role="button"], [role="tab"]'), - ).find((b): b is HTMLElement => { - if (!isVisibleEnabled(b)) return false; - const lbl = ( - b.getAttribute("aria-label") || - elText(b) || - b.getAttribute("title") || - "" - ).trim(); - if (/done editing|delete|split|download/i.test(lbl)) return false; - return /^(?:edit(?:\s+(?:clip|video))?)$/i.test(lbl); - }); - if (editTrigger) { - editTrigger.click(); - await delay(300); - } - } - } - for (let i = 0; i < 20; i += 1) { - if (findVisibleTextbox()) break; - await delay(100); - } - clearStore(); + if (viewKind) { + for (let i = 0; i < 25; i += 1) { + if (findVisibleTextbox() || readEditBlockReason() !== null) break; + await delay(100); + } + if ( + viewKind === "scene_builder" && + !findVisibleTextbox() && + readEditBlockReason() === null + ) { + await selectSceneTimelineClip(idStr); + } + for (let i = 0; i < 15; i += 1) { + if (findVisibleTextbox() || readEditBlockReason() !== null) break; + await delay(100); + } + const alertText = readEditBlockReason(); + clearStore(); + if (alertText) { return { opened: true, + blocked: true, + error: "editor_blocked", + alert: alertText, + detail: alertText, method: "spa_router", view: viewKind, - has_textbox: Boolean(findVisibleTextbox()), + clip_id: idStr, }; } + return { + opened: true, + blocked: false, + method: "spa_router", + view: viewKind, + has_textbox: Boolean(findVisibleTextbox()), + }; } function mentionsAsset(el: Element): boolean { - if (!el) return false; + if (!el || isExcludedComposerNode(el)) return false; if (mediaUrl) { const media = el.querySelectorAll("img[src], video[src], source[src]"); for (const m of media) { @@ -167,7 +344,7 @@ 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) || isExcludedComposerNode(el)) return false; const txt = ( el.getAttribute("aria-label") || elText(el) || @@ -179,7 +356,18 @@ export async function openEditAsset( if (editBtn) { editBtn.click(); await delay(300); - return { opened: true, method: "ui_edit" }; + const alertText = readEditBlockReason(); + if (alertText) { + return { + opened: true, + blocked: true, + error: "editor_blocked", + alert: alertText, + detail: alertText, + method: "ui_edit", + }; + } + return { opened: true, blocked: false, method: "ui_edit" }; } } } diff --git a/ts/prompt_writer.ts b/ts/prompt_writer.ts index 2f3e320..852722c 100644 --- a/ts/prompt_writer.ts +++ b/ts/prompt_writer.ts @@ -5,6 +5,7 @@ import { readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe, isVisibleEnabled, setNativeValue } from "./dom"; +import { buildPromptPayload } from "./edit_builds"; import { runtimeState } from "./state"; import type { NgLView, @@ -315,6 +316,7 @@ export async function writePromptBox( 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 +325,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"), @@ -452,14 +455,32 @@ export async function writePromptBox( ? promptState.Wn : null; if (!promptState || !applyFn) return false; - const segments = [{ type: "text", content }]; - applyFn.call(promptState, { Oe: segments, Te: segments }); + applyFn.call(promptState, buildPromptPayload(content)); return true; }; + const promptStateMatches = (): boolean => { + if (typeof promptState?.prompt?.content !== "function") return true; + try { + const raw = promptState.prompt.content(); + if (!raw || typeof raw !== "object") return true; + const segs = + readOwn(raw, "kf") ?? readOwn(raw, "Te") ?? readOwn(raw, "Oe"); + if (!Array.isArray(segs)) return true; + if (segs.some((s) => readOwn(s, "type") === "mention")) return true; + const joined = segs + .map((s) => String(readOwn(s, "content") ?? "")) + .join("") + .trim(); + const target = text.trim(); + return target.length === 0 ? joined.length === 0 : joined === target; + } catch { + return true; + } + }; const isPromptPopulated = (): boolean => { const empty = readPromptEmpty(); - if (empty !== null) return empty === false; - return hasValidator() ? isPromptValid() : false; + if (empty !== null) return empty === false && promptStateMatches(); + return hasValidator() ? isPromptValid() && promptStateMatches() : false; }; const isSynced = (): boolean => opts.strictSync && (readPromptEmpty() !== null || hasValidator()) diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..625dc03 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -7,7 +7,7 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; import { currentProjectStore, projectInRoute } from "./project_store"; -import { sceneContents } from "./scene_tiles"; +import { sceneClipIds, sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, characterLookMedia, @@ -28,6 +28,7 @@ import type { SceneClipItem, SnapshotAssetItem, SnapshotCollectionItem, + SnapshotVariantItem, StoreSnapshotResult, } from "./types"; @@ -264,6 +265,68 @@ export function readStoreTiles(tileMap: Map): { } }; + const normalizeVariantList = ( + rawItems: unknown, + assetKind: string, + ): SnapshotVariantItem[] => { + if (!Array.isArray(rawItems) || rawItems.length === 0) return []; + const out: SnapshotVariantItem[] = []; + const seen = new Set(); + for (const rawItem of rawItems) { + if (!rawItem || typeof rawItem !== "object") continue; + const rawMediaItem = rawItem as FlowMediaPayload; + const m = legacyMedia(rawMediaItem); + const vid = String( + m?.id ?? rawMediaItem.id ?? m?.mediaId ?? rawMediaItem.mediaId ?? "", + ).trim(); + if (!vid || seen.has(vid)) continue; + seen.add(vid); + const statusRaw = String( + m?.Zc ?? rawMediaItem.od ?? rawMediaItem.Zc ?? "", + ) + .trim() + .toLowerCase(); + const err = formatMediaError( + m?.nf ?? rawMediaItem.Bf ?? rawMediaItem.nf, + ); + const notReady = + statusRaw === "pending" || + statusRaw === "scheduled" || + statusRaw === "failed" || + statusRaw === "canceled" || + Boolean(err); + const cachedUrl = asHttpOrDataUrl( + runtimeState.mediaInfoCache.get(vid)?.url, + ); + const directUrl = + (assetKind === "video" ? readMediaUrl(m, true) : null) || + readMediaUrl(m) || + null; + const pickedUrl = isSignedUrlStr(directUrl) + ? directUrl + : isSignedUrlStr(cachedUrl) + ? cachedUrl + : directUrl || cachedUrl || null; + const readyUrl = + !notReady && pickedUrl + ? normalizeFlowMediaUrl(String(pickedUrl), assetKind, env) + : null; + const vPrompt = m?.prompt + ? String(m.prompt) + : m?.inputs?.prompt + ? String(m.inputs.prompt) + : null; + out.push({ + id: vid, + status: statusRaw || null, + error: err, + url: readyUrl, + prompt: vPrompt, + }); + } + return out; + }; + const collectionIds = new Set(); for (const [id, rawTile] of tileMap.entries()) { if (String(rawTile?.type ?? "").toUpperCase() === collectionType) { @@ -389,6 +452,9 @@ export function readStoreTiles(tileMap: Map): { null; const { start: trimStart, end: trimEnd } = videoTrimBounds(t); + const clipIdsForScene = baseKind === "scene" ? sceneClipIds(rawTile) : null; + const rawHistory = readOwn(rawTile, "history") ?? readOwn(t, "history"); + const tileVariants = normalizeVariantList(rawHistory, kind); const topEntry: Omit = { id: tid, @@ -404,6 +470,8 @@ export function readStoreTiles(tileMap: Map): { url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind, env) : null, collection_id: cid, primary_media_id: primaryMediaId ? String(primaryMediaId) : null, + ...(clipIdsForScene !== null ? { clip_ids: clipIdsForScene } : {}), + variants: tileVariants, personality_notes: bio == null ? null : String(bio), voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, @@ -458,6 +526,7 @@ export function readStoreTiles(tileMap: Map): { } for (const st of sceneTiles) { + const parentSceneId = String(st.id ?? st.workflowId ?? "").trim() || null; const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); const candidates: Array< @@ -484,6 +553,7 @@ export function readStoreTiles(tileMap: Map): { for (const [wfId, clip, rawMedia] of candidates) { if (!wfId) continue; + const clipVariants = normalizeVariantList(history.get(wfId), "video"); const mObj = legacyMedia(rawMedia); const cObj = legacyMedia(clip as FlowMediaPayload | null); const mStatus = String( @@ -492,6 +562,15 @@ export function readStoreTiles(tileMap: Map): { const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); const existing = byId.get(wfId); if (existing) { + if (!existing.scene_id && parentSceneId) { + existing.scene_id = parentSceneId; + } + if (clipVariants.length > 0) { + const merged = new Map(); + for (const v of existing.variants ?? []) merged.set(v.id, v); + for (const v of clipVariants) merged.set(v.id, v); + existing.variants = Array.from(merged.values()); + } if (mStatus === "failed" || mStatus === "canceled" || mError) { if ( existing.media_status !== "failed" && @@ -587,6 +666,8 @@ export function readStoreTiles(tileMap: Map): { url: clipUrl ? normalizeFlowMediaUrl(String(clipUrl), "video", env) : null, collection_id: sceneCid, primary_media_id: clipPrimaryMediaId, + ...(parentSceneId ? { scene_id: parentSceneId } : {}), + variants: clipVariants, personality_notes: null, voice: null, trim_start_seconds: trimStartVal, diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..60cc8cc 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -10,8 +10,8 @@ import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { const format = frontendBuild(readBuildLabel())?.projectStore.scene; - const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; - const history = (format && readOwn(tile, format.history)) ?? tile.Yf; + const clips = (format && readOwn(tile, format.clips)) ?? readOwn(tile, "Uc") ?? tile.Oc; + const history = (format && readOwn(tile, format.history)) ?? readOwn(tile, "Cg") ?? tile.Yf; const entries: Iterable<[string, FlowMediaPayload[]]> = history instanceof Map ? history.entries() : history && typeof history === "object" ? Object.entries(history) : []; @@ -20,3 +20,20 @@ export function sceneContents(tile: FlowTile) { history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), }; } + +/** Extracts ordered workflow clip IDs from a scene tile. */ +export function sceneClipIds(tile: FlowTile): string[] { + const { clips } = sceneContents(tile); + const ids: string[] = []; + for (const item of clips as unknown[]) { + const raw = + typeof item === "string" + ? item + : item && typeof item === "object" + ? String(readOwn(item, "workflowId") ?? readOwn(item, "id") ?? "") + : ""; + const trimmed = raw.trim(); + if (trimmed && !ids.includes(trimmed)) ids.push(trimmed); + } + return ids; +} diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..d4bdc4d 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -14,6 +14,7 @@ import { settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { isEditContext } from "./edit_composer"; import { runtimeState } from "./state"; import type { GenerationConfig, NgLView } from "./types"; @@ -232,7 +233,7 @@ 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 = isEditContext(cfg.edit); if (!onEditPage) { const textbox = await ensureManualComposer(); diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..5e418ab 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -6,6 +6,12 @@ import { readAngularTooltip, readOwn, resolveLView } from "./angular"; import { findComposerWarning } from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; +import { + EDIT_SCOPE_SELECTOR, + isEditContext, + isExcludedComposerNode, + readEditBlockReason, +} from "./edit_composer"; import { runtimeState } from "./state"; import type { NgLView } from "./types"; @@ -45,7 +51,9 @@ function readCandidateValidatorReason(cand: unknown): string { } /** Finds the enabled Start generation button, uncovers it if needed, and returns its viewport point. */ -export async function submitGeneration(): Promise { +export async function submitGeneration( + explicitEdit?: boolean | null, +): Promise { const isVisible = (b: Element | null | undefined): b is HTMLElement => Boolean(b instanceof HTMLElement && b.getClientRects().length > 0); @@ -102,11 +110,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 = isEditContext(explicitEdit); 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 +127,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 +136,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 && !isExcludedComposerNode(el))); 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 +152,13 @@ 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) && !isExcludedComposerNode(b), ); 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) && !isExcludedComposerNode(b)); return fallback ?? null; }; @@ -183,17 +179,27 @@ export async function submitGeneration(): Promise { const warningAfter = checkWarning(); if (warningAfter) return warningAfter; + if (onEditPage) { + const blockReason = readEditBlockReason(); + if (blockReason) { + return { ok: false, error: "editor_blocked", detail: blockReason }; + } + } + const exactAfter = findStartButton(); if (exactAfter && isVisible(exactAfter) && !isVisibleEnabled(exactAfter)) { let reason = + (onEditPage ? readEditBlockReason() || "" : "") || runtimeState.promptState?.Ff?.N7a?.() || runtimeState.promptState?.lf?.jYa?.() || ""; if (!reason) { let cur: Element | null = exactAfter; for (let depth = 0; depth < 6 && cur && !reason; depth += 1) { + if (isExcludedComposerNode(cur)) break; let lv: NgLView | null = resolveLView(cur); for (let pDepth = 0; pDepth < 6 && Array.isArray(lv) && !reason; pDepth += 1) { + if (lv[0] instanceof Node && isExcludedComposerNode(lv[0])) break; for (const cand of lv) { const msg = readCandidateValidatorReason(cand); if (msg) { @@ -210,11 +216,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 Node && isExcludedComposerNode(lv[0])) { continue; } for (const cand of lv) { @@ -231,11 +233,14 @@ 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 && !isExcludedComposerNode(el), + ); + const fallbackPm = Array.from(document.querySelectorAll(".ProseMirror")).find( + (el) => !isExcludedComposerNode(el), ); const detail = [ reason, - ((visiblePm || document.querySelector(".ProseMirror"))?.textContent || "").slice( + ((visiblePm || fallbackPm)?.textContent || "").slice( 0, 40, ), @@ -245,10 +250,27 @@ export async function submitGeneration(): Promise { return { ok: false, error: "start_generation_disabled", detail }; } - const btns = Array.from(document.querySelectorAll('button, [role="button"]')); + const scopedRoots: ParentNode[] = onEditPage + ? [ + ...Array.from(document.querySelectorAll(EDIT_SCOPE_SELECTOR)).filter( + (el) => !isExcludedComposerNode(el), + ), + document, + ] + : [document]; + const btns: Element[] = []; + const seenBtns = new Set(); + for (const root of scopedRoots) { + for (const b of root.querySelectorAll('button, [role="button"]')) { + if (!seenBtns.has(b)) { + seenBtns.add(b); + btns.push(b); + } + } + } const createBtn = btns.find((b): b is HTMLElement => { if (b.tagName === "A" || !isVisibleEnabled(b)) return false; - if (!onEditPage && b.closest(agentSelector)) { + if (isExcludedComposerNode(b)) { return false; } if ( diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..a6b46aa 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -300,9 +300,11 @@ export interface PromptTextSegment { /** Serialized prompt document accepted by `PromptStateController`. */ export interface PromptDocumentPayload { + /** Prompt segments produced by `_.QI` in build 20261120.00. */ + kf?: PromptTextSegment[]; /** Prompt segments in earlier builds. */ Oe?: PromptTextSegment[]; - /** Prompt segments in build 20261120.00. */ + /** Prompt segments in fallback builds. */ Te?: PromptTextSegment[]; } @@ -314,6 +316,8 @@ export interface PromptStateController { Gp?: (doc: PromptDocumentPayload) => void; /** Prompt text helper object. */ prompt?: { + /** Returns the active serialized prompt document when available. */ + content?: () => unknown; /** Returns true when the prompt is empty in earlier builds. */ Le?: () => boolean; /** Returns true when the prompt is empty in build 20261120.00. */ @@ -516,6 +520,20 @@ export interface DiscoverStoreResult { error?: string; } +/** Normalized media variant entry from tile or scene clip history. */ +export interface SnapshotVariantItem { + /** Variant media identifier. */ + id: string; + /** Lowercase variant status (`pending`, `scheduled`, `success`, `failed`, or `canceled`). */ + status: string | null; + /** Failure description when present. */ + error: string | null; + /** Normalized media URL when resolved and ready. */ + url: string | null; + /** Variant prompt text when present. */ + prompt: string | null; +} + /** Asset entry normalized for `readStoreSnapshot`. */ export interface SnapshotAssetItem { /** Tile or clip workflow identifier. */ @@ -534,6 +552,12 @@ export interface SnapshotAssetItem { collection_name: string | null; /** Primary media identifier. */ primary_media_id: string | null; + /** Parent scene identifier when the clip belongs to a scene. */ + scene_id?: string | null; + /** Ordered clip workflow identifiers when the tile is a scene. */ + clip_ids?: string[] | null; + /** Normalized variant history entries for this tile or scene clip. */ + variants?: SnapshotVariantItem[]; /** Character personality notes. */ personality_notes: string | null; /** Assigned voice name or identifier. */ @@ -639,6 +663,8 @@ export interface GenerationConfig { duration?: string | null; /** Video resolution label. */ resolution?: string | null; + /** Explicit flag marking an asset or scene clip edit operation. */ + edit?: boolean | null; } /** Request payload for `sceneOp`. */ @@ -846,9 +872,14 @@ 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, + sceneId?: string | null, + ) => Promise; /** Locates the enabled generation submit button and returns its viewport click point. */ - submitGeneration: () => Promise; + submitGeneration: (explicitEdit?: boolean | null) => Promise; /** Creates Flow scenes and adds clips. */ sceneOp: (req: SceneOpRequest) => Promise; /** Applies video trim timestamps or drives the scene builder extend workflow. */