From cebab2ee8f4ef76fa6bc16ed1283483eeed636c5 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:54:39 +0000 Subject: [PATCH 1/4] fix(flow): guard edit composers, routes, and variant history - Bind image edit prompt boxes and exclude non-composer panels - Include kf segments in fallback PromptState document updates - Route scene clips to /scene/, check alerts, and reject scenes - Track latest_variant_id in history while keeping primary URLs --- src/assets.rs | 21 +- src/characters.rs | 14 +- src/generation.rs | 157 ++++++++---- ts/attach_ingredients.ts | 64 ++--- ts/composer.ts | 109 ++++++--- ts/open_edit_asset.ts | 496 +++++++++++++++++++++++++++++++++----- ts/prompt_writer.ts | 18 +- ts/read_store_snapshot.ts | 171 ++++++++++--- ts/setup_generation.ts | 13 +- ts/submit_generation.ts | 53 ++-- ts/types.ts | 15 +- 11 files changed, 871 insertions(+), 260 deletions(-) diff --git a/src/assets.rs b/src/assets.rs index c3c8975..3c94698 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -28,7 +28,7 @@ const MEDIA_URL_LOOKUPS: usize = 4; const ASSET_LIST_URL_BUDGET: Duration = Duration::from_secs(10); /// 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, @@ -48,6 +48,9 @@ pub(crate) struct FlowAsset { /// Parent collection display name. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) collection_name: Option, + /// Parent scene ID when this clip exists only inside a scene timeline. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) scene_id: Option, /// Media width in pixels. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) width: Option, @@ -60,6 +63,9 @@ 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, + /// Newest variant ID in asset or scene clip history. + #[serde(default, skip_serializing)] + pub(crate) latest_variant_id: Option, /// Character personality notes or introduction text. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) personality_notes: Option, @@ -166,15 +172,18 @@ async fn populate_missing_media_urls( ) { let mut missing: HashMap> = HashMap::new(); for (index, asset) in assets.iter().enumerate() { + let primary_not_ready = (asset.media_error.is_some() + || matches!( + asset.media_status.as_deref(), + Some("pending" | "scheduled" | "failed" | "canceled") + )) + && (asset.latest_variant_id.is_none() + || asset.latest_variant_id == asset.primary_media_id); if !matches!( asset.kind.as_str(), "video" | "image" | "character" | "audio" ) || asset.url.is_some() - || asset.media_error.is_some() - || matches!( - asset.media_status.as_deref(), - Some("pending" | "scheduled" | "failed" | "canceled") - ) + || primary_not_ready { continue; } 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/generation.rs b/src/generation.rs index b9f3f55..78f8c7a 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -73,12 +73,27 @@ pub(crate) struct EditParams { pub(crate) prompt: String, } +/// Baseline state of an existing asset watched for edit updates or failures. +#[derive(Clone, Copy)] +struct WatchedAsset<'a> { + /// Asset or scene clip workflow ID. + id: &'a str, + /// Primary media ID before edit submission. + primary_media_id: Option<&'a str>, + /// Newest variant ID in history before edit submission. + latest_variant_id: Option<&'a str>, + /// Resolved media URL before edit submission. + url: Option<&'a str>, + /// True when the watched asset already reported a failed or canceled variant before submission. + was_failed: bool, +} + /// Specification controlling asset polling during generation and edit jobs. 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>)>, + /// Optional existing tile watched for replacement updates or variant failures. + watch_updated: Option>, /// Target number of generated outputs in the batch. expected_count: usize, /// Maximum wait time in seconds before failing with timeout. @@ -363,15 +378,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 +402,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,15 +435,16 @@ 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) + if let Some(w) = spec.watch_updated + && let Some(watched) = snap.assets.iter().find(|a| a.id == w.id) && matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) - && (watched.primary_media_id.as_deref() != prev_pmid - || watched.media_error.is_some()) + && (watched.latest_variant_id.as_deref() != w.latest_variant_id + || watched.primary_media_id.as_deref() != w.primary_media_id + || !w.was_failed) { anyhow::bail!( "Flow edit failed on {}: {}", - tid, + w.id, watched .media_error .as_deref() @@ -608,6 +624,33 @@ pub(crate) async fn run_edit( 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" => { + let clip_ids: Vec<&str> = snap + .assets + .iter() + .filter(|a| a.scene_id.as_deref() == Some(target.id.as_str())) + .map(|a| a.id.as_str()) + .take(6) + .collect(); + let hint = if clip_ids.is_empty() { + String::new() + } else { + format!(" Available clip IDs: {}.", clip_ids.join(", ")) + }; + anyhow::bail!( + "Cannot edit scene container '{}' directly; pass one of its video clip IDs to flow_edit.{}", + target.id, + hint + ); + } + "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() { @@ -617,41 +660,63 @@ pub(crate) async fn run_edit( }; 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 edit_mode = if target.kind == "video" { + "video" + } else { + "image" + }; - let open_res = engine - .call_flow_async( - "openEditAsset", - json!([target.id, target.url, target.primary_media_id]), - ) + let open_args = json!([ + target.id, + target.url, + target.primary_media_id, + target.scene_id + ]); + let mut open_res = engine + .call_flow_async("openEditAsset", open_args.clone()) .await .unwrap_or_default(); - let mut opened_in_ui = open_res - .get("opened") - .and_then(|v| v.as_bool()) - .unwrap_or(false); + 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); + } + 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 { - 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; + 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(); + 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); } - } else { + opened_in_ui = is_editor_open(&open_res); + } else if opened_in_ui { let _ = ensure_flow_store(engine).await; } let mut attached_frames: Option> = None; if !opened_in_ui { + ensure_project_workspace_root(engine).await?; if edit_mode == "video" { anyhow::bail!( - "Could not open an inline edit control or /edit/ route for video asset '{}'", + "Could not open an inline edit control or editor route for video asset '{}'", label ); } @@ -674,11 +739,8 @@ pub(crate) async fn run_edit( } } - let in_edit_route = engine - .current_url() - .await - .unwrap_or_default() - .contains("/edit/"); + let cur_url = engine.current_url().await.unwrap_or_default(); + let in_edit_route = opened_in_ui && (cur_url.contains("/edit/") || cur_url.contains("/scene/")); on_progress(format!("submitting edit for {}", label)); let scene = SceneParams { prompt: prompt.to_string(), @@ -696,15 +758,18 @@ pub(crate) async fn run_edit( 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(( - target.id.as_str(), - target.primary_media_id.as_deref(), - target.url.as_deref(), - )), + watch_updated: Some(WatchedAsset { + id: target.id.as_str(), + primary_media_id: target.primary_media_id.as_deref(), + latest_variant_id: target.latest_variant_id.as_deref(), + url: target.url.as_deref(), + was_failed: target_was_failed, + }), expected_count: 1, timeout_secs: 420, submit_summary: &submit_summary, diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 10bef6d..364c09e 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 { @@ -91,7 +93,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?.(); @@ -244,7 +246,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); }); @@ -269,6 +273,7 @@ export async function attachIngredients(cfg: GenerationConfig): Promise 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") || @@ -283,6 +288,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(), ), @@ -335,7 +341,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) || @@ -352,7 +360,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) || @@ -593,27 +603,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,11 +641,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..6adc566 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -17,8 +17,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-editor-side-panel, flow-comment-region-overlay, flow-comment-timeline-lane, [class*="comment-panel"], [class*="comments-panel"]'; + +/** 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 { @@ -28,22 +40,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. */ @@ -52,7 +78,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,9 +253,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) { @@ -264,22 +291,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; @@ -388,9 +429,12 @@ 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 findBaseInst = (lv: NgLView): BasePromptBoxInstance | null => { for (const cand of lv) { if ( @@ -406,8 +450,8 @@ export async function closeSettingsAndMenus(): Promise { return null; }; let baseInst: BasePromptBoxInstance | null = findLiveBasePromptBox( - false, - findPromptBoxHost(findProjectPageInstance()), + onEdit, + onEdit ? null : findPromptBoxHost(findProjectPageInstance()), ); if ( baseInst && @@ -427,6 +471,9 @@ 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; } @@ -446,9 +493,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); diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..78a5dc5 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,43 +8,387 @@ import { findRouter, navigateSpa, readOwn, + resolveLView, type NgContextCarrier, } from "./angular"; -import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; -import { clearStore } from "./state"; +import { + EDIT_PROMPT_BOX_SELECTOR, + findTextbox, + NON_COMPOSER_PANELS, +} from "./composer"; +import { delay, elText, isVisibleEnabled } from "./dom"; +import { sceneContents } from "./scene_tiles"; +import { clearStore, runtimeState } from "./state"; + +/** Returns true when `el` is connected, visible on screen, and outside non-composer panels. */ +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. */ +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; +} + +/** Checks whether an Angular context slot matches the target clip identifier. */ +function objectMatchesClip( + item: unknown, + idStr: string, + primaryStr: string, +): boolean { + if (!item || typeof item !== "object" || item instanceof Node) return false; + const rawType = String(readOwn(item, "type") || "").toUpperCase(); + if (rawType === "SCENE") return false; + const wf = String(readOwn(item, "workflowId") || "").trim(); + if (idStr && wf === idStr) return true; + const pmid = String(readOwn(item, "primaryMediaId") || "").trim(); + if (primaryStr && pmid === primaryStr) return true; + const id = String(readOwn(item, "id") || "").trim(); + return Boolean(idStr && id === idStr); +} + +/** Checks whether a DOM node in `flow-scene-builder` represents the target clip. */ +function elementMatchesSceneClip( + el: Element, + idStr: string, + primaryStr: string, + mediaUrl: string | null, +): boolean { + for (const attr of [ + "data-workflow-id", + "data-clip-id", + "data-asset-id", + "data-id", + "id", + ]) { + const val = (el.getAttribute(attr) || "").trim(); + if (val && (val === idStr || (primaryStr && val === primaryStr))) { + return true; + } + } + if (mediaUrl) { + const mediaNodes = [ + ...(el.matches("img[src], video[src], source[src]") ? [el] : []), + ...Array.from(el.querySelectorAll("img[src], video[src], source[src]")), + ]; + if ( + mediaNodes.length === 1 && + (() => { + const src = mediaNodes[0].getAttribute("src") || ""; + return Boolean( + src && + (src === mediaUrl || + mediaUrl.includes(src) || + src.includes(mediaUrl)), + ); + })() + ) { + return true; + } + } + const lv = resolveLView(el) ?? (el as NgContextCarrier).__ngContext__; + if (Array.isArray(lv)) { + for (const slot of lv) { + if (objectMatchesClip(slot, idStr, primaryStr)) return true; + } + } + return false; +} -/** Navigates to `/edit/` using Angular Router or triggers an inline tile edit action. */ +/** Selects the target clip in `flow-scene-builder` and opens clip edit mode when needed. */ +async function selectSceneClip( + sb: ParentNode, + idStr: string, + primaryStr: string, + mediaUrl: string | null, + clipIndex: number, +): Promise { + for (let i = 0; i < 25; i += 1) { + if ( + sb.querySelector( + 'flow-scene-timeline, [class*="clip"], [data-testid*="clip"], video', + ) + ) { + break; + } + await delay(100); + } + const searchRoot = sb.querySelector("flow-scene-timeline") || sb; + const candidates = Array.from(searchRoot.querySelectorAll("*")).filter( + (el): el is HTMLElement => + isVisibleOutsideNonComposer(el) && !el.closest(EDIT_PROMPT_BOX_SELECTOR), + ); + const directMatches = candidates.filter((el) => + elementMatchesSceneClip(el, idStr, primaryStr, mediaUrl), + ); + let targetClip: HTMLElement | null = + directMatches.find( + (el) => !directMatches.some((other) => other !== el && el.contains(other)), + ) ?? + directMatches[0] ?? + null; + + if (!targetClip && clipIndex >= 0) { + const timeline = sb.querySelector("flow-scene-timeline"); + if (timeline) { + const rawItems = Array.from( + timeline.querySelectorAll( + '[data-clip-index], [data-testid*="clip"], [class*="timeline-clip"], [class*="clip-item"], [class*="clip-card"]', + ), + ).filter(isVisibleOutsideNonComposer); + const topItems = rawItems.filter( + (el) => !rawItems.some((other) => other !== el && other.contains(el)), + ); + if (clipIndex < topItems.length) { + targetClip = topItems[clipIndex]; + } else { + const directChildren = Array.from(timeline.children).filter( + isVisibleOutsideNonComposer, + ); + if (clipIndex < directChildren.length) { + targetClip = directChildren[clipIndex]; + } + } + } + } + + if (!targetClip && !findTextbox(true)) { + const fallback = sb.querySelector( + '[class*="clip"], [data-testid*="clip"], video', + ); + if (isVisibleOutsideNonComposer(fallback)) { + targetClip = fallback; + } + } + + if (targetClip) { + targetClip.click(); + await delay(250); + } + + if (readComposerAlert(false)) return; + + if ( + !findTextbox(true) || + Boolean(document.querySelector(".is-extend-mode, .extend-composing")) + ) { + const editTrigger = Array.from( + sb.querySelectorAll('button, [role="button"], [role="tab"]'), + ).find((b): b is HTMLElement => { + if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) 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); + } + } +} + +/** Navigates to `/edit/` or `/scene/` and confirms edit composer readiness. */ export async function openEditAsset( assetId: string, mediaUrl: string | null, primaryMediaId: string | null, + sceneId: string | null = 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 - ); + let resolvedSceneId = sceneId ? String(sceneId).trim() || null : null; + let clipIndex = -1; + 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") { + const clipIds = sceneContents(directTile) + .clips.map((c) => String(c?.workflowId || "").trim()) + .filter(Boolean); + const hint = + clipIds.length > 0 + ? ` Available clip IDs: ${clipIds.slice(0, 6).join(", ")}.` + : ""; + return { + opened: false, + error: "unsupported_asset_kind", + kind: "scene", + alert: `Cannot edit scene container '${idStr}' directly. Pass one of its video clip IDs to flow_edit.${hint}`, + 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, + }; + } + } else { + for (const st of tileMap.values()) { + if (String(st?.type || "").toUpperCase() !== "SCENE") continue; + const stId = st.id != null ? String(st.id).trim() : ""; + if (resolvedSceneId && stId && stId !== resolvedSceneId) continue; + const { clips, history } = sceneContents(st); + const idx = clips.findIndex( + (c) => String(c?.workflowId || "").trim() === idStr, + ); + if (idx >= 0 || history.has(idStr)) { + if (!resolvedSceneId && stId) resolvedSceneId = stId; + if (idx >= 0) clipIndex = idx; + break; + } + } + } } 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]); + const pid = pm ? pm[1] : runtimeState.store?.projectId || null; + const router = pid ? findRouter() : null; + + if (resolvedSceneId && pid) { + const targetPath = `/scene/${resolvedSceneId}`; + let hasSceneBuilder = + (location.pathname || "").includes(targetPath) && + Boolean(document.querySelector("flow-scene-builder")); + if (!hasSceneBuilder && (location.pathname || "").includes(targetPath)) { + for (let i = 0; i < 30; i += 1) { + if (document.querySelector("flow-scene-builder")) { + hasSceneBuilder = true; + break; + } + await delay(100); + } + } + if (!hasSceneBuilder && router) { + await navigateSpa(router, ["/project", pid, "scene", resolvedSceneId]); for (let i = 0; i < 60; i += 1) { + if ( + (location.pathname || "").includes(targetPath) && + document.querySelector("flow-scene-builder") + ) { + hasSceneBuilder = true; + break; + } + await delay(100); + } + } + if (hasSceneBuilder) { + const sb = document.querySelector("flow-scene-builder") || document; + await selectSceneClip(sb, idStr, primaryStr, mediaUrl, clipIndex); + for (let i = 0; i < 25; i += 1) { + if (readComposerAlert(false) || findTextbox(true)) break; + await delay(100); + } + clearStore(); + const hasTextbox = Boolean(findTextbox(true)); + const alert = readComposerAlert(!hasTextbox); + if (alert) { + return { + opened: false, + error: "edit_alert", + alert, + method: "spa_router", + view: "scene_builder", + scene_id: resolvedSceneId, + has_textbox: false, + }; + } + return { + opened: hasTextbox, + error: hasTextbox ? undefined : "editor_textbox_not_found", + method: "spa_router", + view: "scene_builder", + scene_id: resolvedSceneId, + has_textbox: hasTextbox, + }; + } + if (!(location.pathname || "").includes(targetPath)) { + return { + opened: false, + edit_url: buildProjectUrl(pid, ["scene", resolvedSceneId]), + scene_id: resolvedSceneId, + method: "route_fallback_needed", + }; + } + return { + opened: false, + error: "scene_builder_not_found", + scene_id: resolvedSceneId, + has_textbox: false, + method: "none", + }; + } + + 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 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,53 +398,57 @@ 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 ( + !readComposerAlert(false) && + 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) { - 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); - } + await selectSceneClip(sb, idStr, primaryStr, mediaUrl, clipIndex); + 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 +515,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 +528,36 @@ 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..de026f2 100644 --- a/ts/prompt_writer.ts +++ b/ts/prompt_writer.ts @@ -312,9 +312,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 +327,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 +335,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 +363,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 +403,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); }); @@ -453,7 +463,7 @@ export async function writePromptBox( : null; if (!promptState || !applyFn) return false; const segments = [{ type: "text", content }]; - applyFn.call(promptState, { Oe: segments, Te: segments }); + applyFn.call(promptState, { kf: segments, Te: segments, Oe: segments }); return true; }; const isPromptPopulated = (): boolean => { diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..d017d67 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -37,6 +37,36 @@ const ACCOUNT_CREDITS_RE = /(?:^|[^\w,])(\d[\d,]*)\s+(?:Google\s+Flow|Flow|AI)\s /** Selector matching generation credit cost estimates that are not account balances. */ const COST_LABEL_SELECTOR = "flow-credit-cost-label, .credit-cost-label, .credit-cost-link"; +/** Reads the creation timestamp in milliseconds from a media payload when available. */ +function variantTimestampMs( + media: FlowMediaPayload | null | undefined, +): number | null { + if (!media || typeof media !== "object") return null; + const rawDate = + media.hc ?? media.kc ?? (media as Record).lc; + return rawDate instanceof Date && Number.isFinite(rawDate.getTime()) + ? rawDate.getTime() + : null; +} + +/** Selects the newest normalized media variant from a tile or scene clip history list. */ +function pickLatestHistoryVariant(history: unknown): FlowMediaPayload | null { + if (!Array.isArray(history) || history.length === 0) return null; + let best: FlowMediaPayload | null = null; + let bestTs: number | null = null; + for (const item of history) { + if (!item || typeof item !== "object") continue; + const norm = legacyMedia(item as FlowMediaPayload); + if (!norm) continue; + const curTs = variantTimestampMs(norm); + if (!best || curTs === null || bestTs === null || curTs >= bestTs) { + best = norm; + bestTs = curTs; + } + } + return best; +} + /** Locates an active Angular service instance matching `ServiceClass` in runtime state. */ function findCreditsServiceInstance( ServiceClass: abstract new (...args: never[]) => object, @@ -324,13 +354,13 @@ export function readStoreTiles(tileMap: Map): { readMediaUrl(t.fb, true) : null; - const mediaStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); - const mediaError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); + const primaryStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); + const primaryError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); const mediaNotReady = - mediaStatus === "pending" || - mediaStatus === "scheduled" || - mediaStatus === "failed" || - mediaStatus === "canceled" || + primaryStatus === "pending" || + primaryStatus === "scheduled" || + primaryStatus === "failed" || + primaryStatus === "canceled" || Boolean(t.Fb?.nf || t.fb?.nf || t.nf); const primaryMediaId = @@ -341,6 +371,33 @@ export function readStoreTiles(tileMap: Map): { t.fb?.mediaId || t.mediaId || null; + const primaryMediaIdStr = + primaryMediaId != null && String(primaryMediaId) !== "" + ? String(primaryMediaId) + : null; + const rawHistory = Array.isArray(rawTile.history) + ? rawTile.history + : Array.isArray(t.history) + ? t.history + : null; + const latestVariant = pickLatestHistoryVariant(rawHistory); + const latestVariantIdRaw = + latestVariant?.id ?? latestVariant?.mediaId ?? primaryMediaIdStr; + const latestVariantId = + latestVariantIdRaw != null && String(latestVariantIdRaw) !== "" + ? String(latestVariantIdRaw) + : null; + const latestStatus = latestVariant + ? String(latestVariant.Zc ?? "").toLowerCase() + : ""; + const latestError = latestVariant + ? formatMediaError(latestVariant.nf) + : null; + const mediaStatus = (latestStatus || primaryStatus) || null; + const mediaError = latestVariant + ? latestError ?? + (latestVariantId === primaryMediaIdStr ? primaryError : null) + : primaryError; const cachedEntry = primaryMediaId ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) @@ -403,12 +460,14 @@ export function readStoreTiles(tileMap: Map): { : null, url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind, env) : null, collection_id: cid, - primary_media_id: primaryMediaId ? String(primaryMediaId) : null, + scene_id: null, + primary_media_id: primaryMediaIdStr, + latest_variant_id: latestVariantId, personality_notes: bio == null ? null : String(bio), voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, trim_end_seconds: trimEnd, - media_status: mediaStatus || null, + media_status: mediaStatus, media_error: mediaError, width: typeof t.width === "number" @@ -458,64 +517,108 @@ export function readStoreTiles(tileMap: Map): { } for (const st of sceneTiles) { + const sceneId = + st.id != null && String(st.id) !== "" ? String(st.id) : null; const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); + const seenWfIds = new Set(); const candidates: Array< - [string, SceneClipItem | null, FlowMediaPayload | null] + [ + string, + SceneClipItem | null, + FlowMediaPayload | null, + FlowMediaPayload[] | undefined, + ] > = []; for (const clip of clips) { const wfId = clip?.workflowId ? String(clip.workflowId) : null; - if (!wfId) continue; + if (!wfId || seenWfIds.has(wfId)) continue; + seenWfIds.add(wfId); const hist = history.get(wfId); const primaryId = clip?.primaryMediaId ? String(clip.primaryMediaId) : null; const mObj = Array.isArray(hist) - ? hist.find((x) => x && String(x.id || "") === primaryId) || - hist[0] || + ? (primaryId + ? hist.find((x) => x && String(x.id ?? x.mediaId ?? "") === primaryId) + : null) || + pickLatestHistoryVariant(hist) || null : null; - candidates.push([wfId, clip, mObj]); + candidates.push([wfId, clip, mObj, hist]); } for (const [wfId, hist] of history) { - const mObj = Array.isArray(hist) ? hist[0] || null : null; - candidates.push([wfId, null, mObj]); + if (!wfId || seenWfIds.has(wfId)) continue; + seenWfIds.add(wfId); + const mObj = pickLatestHistoryVariant(hist); + candidates.push([wfId, null, mObj, hist]); } - for (const [wfId, clip, rawMedia] of candidates) { + for (const [wfId, clip, rawMedia, hist] of candidates) { if (!wfId) continue; const mObj = legacyMedia(rawMedia); const cObj = legacyMedia(clip as FlowMediaPayload | null); - const mStatus = String( + const primaryClipStatus = String( mObj?.Zc ?? cObj?.Zc ?? clip?.Zc ?? "", ).toLowerCase(); - const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const primaryClipError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const clipPrimaryMediaId = clip?.primaryMediaId + ? String(clip.primaryMediaId) + : mObj?.id + ? String(mObj.id) + : null; + const latestClipVariant = pickLatestHistoryVariant(hist); + const latestClipIdRaw = + latestClipVariant?.id ?? latestClipVariant?.mediaId ?? clipPrimaryMediaId; + const latestClipVariantId = + latestClipIdRaw != null && String(latestClipIdRaw) !== "" + ? String(latestClipIdRaw) + : null; + const latestClipStatus = latestClipVariant + ? String(latestClipVariant.Zc ?? "").toLowerCase() + : ""; + const latestClipError = latestClipVariant + ? formatMediaError(latestClipVariant.nf) + : null; + const effectiveStatus = (latestClipStatus || primaryClipStatus) || null; + const effectiveError = latestClipVariant + ? latestClipError ?? + (latestClipVariantId === clipPrimaryMediaId ? primaryClipError : null) + : primaryClipError; const existing = byId.get(wfId); if (existing) { - if (mStatus === "failed" || mStatus === "canceled" || mError) { + if ( + latestClipVariantId && + (!existing.latest_variant_id || + existing.latest_variant_id === existing.primary_media_id) + ) { + existing.latest_variant_id = latestClipVariantId; + } + if ( + effectiveStatus === "failed" || + effectiveStatus === "canceled" || + effectiveStatus === "pending" || + effectiveStatus === "scheduled" || + effectiveError + ) { if ( existing.media_status !== "failed" && existing.media_status !== "canceled" ) { - existing.media_status = mStatus || existing.media_status; + existing.media_status = effectiveStatus || existing.media_status; } - if (!existing.media_error && mError) { - existing.media_error = mError; + if (!existing.media_error && effectiveError) { + existing.media_error = effectiveError; } } continue; } const mNotReady = - mStatus === "pending" || - mStatus === "scheduled" || - mStatus === "failed" || - mStatus === "canceled" || + primaryClipStatus === "pending" || + primaryClipStatus === "scheduled" || + primaryClipStatus === "failed" || + primaryClipStatus === "canceled" || Boolean(mObj?.nf || cObj?.nf || clip?.nf); - const clipPrimaryMediaId = clip?.primaryMediaId - ? String(clip.primaryMediaId) - : mObj?.id - ? String(mObj.id) - : null; const cachedClipVideoUrl = clipPrimaryMediaId ? asHttpOrDataUrl( runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, @@ -586,13 +689,15 @@ export function readStoreTiles(tileMap: Map): { prompt: clipPrompt, url: clipUrl ? normalizeFlowMediaUrl(String(clipUrl), "video", env) : null, collection_id: sceneCid, + scene_id: sceneId, primary_media_id: clipPrimaryMediaId, + latest_variant_id: latestClipVariantId, personality_notes: null, voice: null, trim_start_seconds: trimStartVal, trim_end_seconds: trimEndVal, - media_status: mStatus || null, - media_error: mError, + media_status: effectiveStatus, + media_error: effectiveError, width: typeof mObj?.width === "number" ? mObj.width diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..cea8feb 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -11,6 +11,8 @@ import { findLiveBasePromptBox, findProjectPageInstance, findPromptBoxHost, + isEditOrSceneRoute, + NON_COMPOSER_PANELS, settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; @@ -232,16 +234,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()) { diff --git a/ts/submit_generation.ts b/ts/submit_generation.ts index a2849a0..5332790 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -4,7 +4,11 @@ // 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, +} from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; import { runtimeState } from "./state"; import type { NgLView } from "./types"; @@ -102,11 +106,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 +123,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 +132,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 +148,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 +178,16 @@ 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?.() || ""; 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 +206,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 +223,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 +237,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 2e1369d..72480c4 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -226,6 +226,8 @@ export interface FlowTile extends FlowMediaPayload { Eb?: FlowMediaPayload; /** Primary media container in build 20261120.00. */ Kb?: FlowMediaPayload; + /** Generated media variant history ordered from oldest to newest. */ + history?: FlowMediaPayload[]; /** Character preview fallback URL. */ ue?: string; /** Preview media identifier or fallback URL in build 20261120.00. */ @@ -300,6 +302,8 @@ export interface PromptTextSegment { /** Serialized prompt document accepted by `PromptStateController`. */ export interface PromptDocumentPayload { + /** Prompt segments read by `PromptState.Gp` in build 20261120.00. */ + kf?: PromptTextSegment[]; /** Prompt segments in earlier builds. */ Oe?: PromptTextSegment[]; /** Prompt segments in build 20261120.00. */ @@ -532,8 +536,12 @@ export interface SnapshotAssetItem { collection_id: string | null; /** Parent collection name. */ collection_name: string | null; + /** Parent scene identifier for scene-only clips. */ + scene_id: string | null; /** Primary media identifier. */ primary_media_id: string | null; + /** Newest variant identifier in tile or scene clip history. */ + latest_variant_id: string | null; /** Character personality notes. */ personality_notes: string | null; /** Assigned voice name or identifier. */ @@ -846,7 +854,12 @@ 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; /** Creates Flow scenes and adds clips. */ From 89a4670b31031f9faa11126d8d2c9ba0e48c855b 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:55:05 +0000 Subject: [PATCH 2/4] fix(flow): verify selected clip match in scene builder - Require an unambiguous clip ID match without first-clip fallback - Reject unloaded or placeholder clips in scene timelines - Verify selected clip state in DOM and Angular component inputs - Return a selection error when the editor cannot prove the match --- src/generation.rs | 29 +- ts/composer.ts | 39 +++ ts/open_edit_asset.ts | 387 ++++++++++----------- ts/scene_tiles.ts | 776 +++++++++++++++++++++++++++++++++++++++++- 4 files changed, 1011 insertions(+), 220 deletions(-) diff --git a/src/generation.rs b/src/generation.rs index 78f8c7a..62de2ea 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -684,9 +684,26 @@ pub(crate) async fn run_edit( let _ = ensure_project_workspace_root(engine).await; anyhow::bail!("Flow cannot edit '{}': {}", label, alert); } + if let Some(sel_err) = open_res + .get("selection_error") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); + } 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) + if res.get("opened").and_then(|v| v.as_bool()) != Some(true) + || res.get("has_textbox").and_then(|v| v.as_bool()) != Some(true) + || res.get("selection_error").is_some() + { + return false; + } + if target.scene_id.is_some() || res.get("scene_id").and_then(|v| v.as_str()).is_some() { + return res.get("selected_clip_id").and_then(|v| v.as_str()) + == Some(target.id.as_str()); + } + true }; let mut opened_in_ui = is_editor_open(&open_res); @@ -706,6 +723,14 @@ pub(crate) async fn run_edit( let _ = ensure_project_workspace_root(engine).await; anyhow::bail!("Flow cannot edit '{}': {}", label, alert); } + if let Some(sel_err) = open_res + .get("selection_error") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); + } opened_in_ui = is_editor_open(&open_res); } else if opened_in_ui { let _ = ensure_flow_store(engine).await; diff --git a/ts/composer.ts b/ts/composer.ts index 6adc566..c4d1c6c 100644 --- a/ts/composer.ts +++ b/ts/composer.ts @@ -525,3 +525,42 @@ 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; +} + diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 78a5dc5..5afae90 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -9,215 +9,25 @@ import { navigateSpa, readOwn, resolveLView, + withLViewMapCapture, type NgContextCarrier, } from "./angular"; import { - EDIT_PROMPT_BOX_SELECTOR, findTextbox, NON_COMPOSER_PANELS, + readComposerAlert, } from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; -import { sceneContents } from "./scene_tiles"; +import { + collectSceneClipElements, + ensureSceneBuilderLViewMap, + readComponentInput, + sceneContents, + selectSceneClip, + verifySelectedSceneClipInBuilder, +} from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -/** Returns true when `el` is connected, visible on screen, and outside non-composer panels. */ -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. */ -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; -} - -/** Checks whether an Angular context slot matches the target clip identifier. */ -function objectMatchesClip( - item: unknown, - idStr: string, - primaryStr: string, -): boolean { - if (!item || typeof item !== "object" || item instanceof Node) return false; - const rawType = String(readOwn(item, "type") || "").toUpperCase(); - if (rawType === "SCENE") return false; - const wf = String(readOwn(item, "workflowId") || "").trim(); - if (idStr && wf === idStr) return true; - const pmid = String(readOwn(item, "primaryMediaId") || "").trim(); - if (primaryStr && pmid === primaryStr) return true; - const id = String(readOwn(item, "id") || "").trim(); - return Boolean(idStr && id === idStr); -} - -/** Checks whether a DOM node in `flow-scene-builder` represents the target clip. */ -function elementMatchesSceneClip( - el: Element, - idStr: string, - primaryStr: string, - mediaUrl: string | null, -): boolean { - for (const attr of [ - "data-workflow-id", - "data-clip-id", - "data-asset-id", - "data-id", - "id", - ]) { - const val = (el.getAttribute(attr) || "").trim(); - if (val && (val === idStr || (primaryStr && val === primaryStr))) { - return true; - } - } - if (mediaUrl) { - const mediaNodes = [ - ...(el.matches("img[src], video[src], source[src]") ? [el] : []), - ...Array.from(el.querySelectorAll("img[src], video[src], source[src]")), - ]; - if ( - mediaNodes.length === 1 && - (() => { - const src = mediaNodes[0].getAttribute("src") || ""; - return Boolean( - src && - (src === mediaUrl || - mediaUrl.includes(src) || - src.includes(mediaUrl)), - ); - })() - ) { - return true; - } - } - const lv = resolveLView(el) ?? (el as NgContextCarrier).__ngContext__; - if (Array.isArray(lv)) { - for (const slot of lv) { - if (objectMatchesClip(slot, idStr, primaryStr)) return true; - } - } - return false; -} - -/** Selects the target clip in `flow-scene-builder` and opens clip edit mode when needed. */ -async function selectSceneClip( - sb: ParentNode, - idStr: string, - primaryStr: string, - mediaUrl: string | null, - clipIndex: number, -): Promise { - for (let i = 0; i < 25; i += 1) { - if ( - sb.querySelector( - 'flow-scene-timeline, [class*="clip"], [data-testid*="clip"], video', - ) - ) { - break; - } - await delay(100); - } - const searchRoot = sb.querySelector("flow-scene-timeline") || sb; - const candidates = Array.from(searchRoot.querySelectorAll("*")).filter( - (el): el is HTMLElement => - isVisibleOutsideNonComposer(el) && !el.closest(EDIT_PROMPT_BOX_SELECTOR), - ); - const directMatches = candidates.filter((el) => - elementMatchesSceneClip(el, idStr, primaryStr, mediaUrl), - ); - let targetClip: HTMLElement | null = - directMatches.find( - (el) => !directMatches.some((other) => other !== el && el.contains(other)), - ) ?? - directMatches[0] ?? - null; - - if (!targetClip && clipIndex >= 0) { - const timeline = sb.querySelector("flow-scene-timeline"); - if (timeline) { - const rawItems = Array.from( - timeline.querySelectorAll( - '[data-clip-index], [data-testid*="clip"], [class*="timeline-clip"], [class*="clip-item"], [class*="clip-card"]', - ), - ).filter(isVisibleOutsideNonComposer); - const topItems = rawItems.filter( - (el) => !rawItems.some((other) => other !== el && other.contains(el)), - ); - if (clipIndex < topItems.length) { - targetClip = topItems[clipIndex]; - } else { - const directChildren = Array.from(timeline.children).filter( - isVisibleOutsideNonComposer, - ); - if (clipIndex < directChildren.length) { - targetClip = directChildren[clipIndex]; - } - } - } - } - - if (!targetClip && !findTextbox(true)) { - const fallback = sb.querySelector( - '[class*="clip"], [data-testid*="clip"], video', - ); - if (isVisibleOutsideNonComposer(fallback)) { - targetClip = fallback; - } - } - - if (targetClip) { - targetClip.click(); - await delay(250); - } - - if (readComposerAlert(false)) return; - - if ( - !findTextbox(true) || - Boolean(document.querySelector(".is-extend-mode, .extend-composing")) - ) { - const editTrigger = Array.from( - sb.querySelectorAll('button, [role="button"], [role="tab"]'), - ).find((b): b is HTMLElement => { - if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) 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); - } - } -} - /** Navigates to `/edit/` or `/scene/` and confirms edit composer readiness. */ export async function openEditAsset( assetId: string, @@ -230,7 +40,6 @@ export async function openEditAsset( const candidateIds = Array.from(new Set([idStr, primaryStr].filter(Boolean))); let resolvedSceneId = sceneId ? String(sceneId).trim() || null : null; - let clipIndex = -1; const tileMap = runtimeState.store?.getTileMap?.(); if (tileMap instanceof Map && idStr) { const directTile = tileMap.get(idStr); @@ -286,7 +95,6 @@ export async function openEditAsset( ); if (idx >= 0 || history.has(idStr)) { if (!resolvedSceneId && stId) resolvedSceneId = stId; - if (idx >= 0) clipIndex = idx; break; } } @@ -312,7 +120,9 @@ export async function openEditAsset( } } if (!hasSceneBuilder && router) { - await navigateSpa(router, ["/project", pid, "scene", resolvedSceneId]); + await withLViewMapCapture(async () => { + await navigateSpa(router, ["/project", pid, "scene", resolvedSceneId]); + }); for (let i = 0; i < 60; i += 1) { if ( (location.pathname || "").includes(targetPath) && @@ -326,11 +136,36 @@ export async function openEditAsset( } if (hasSceneBuilder) { const sb = document.querySelector("flow-scene-builder") || document; - await selectSceneClip(sb, idStr, primaryStr, mediaUrl, clipIndex); + const selection = await selectSceneClip(sb, idStr, primaryStr); + if (!selection.ok) { + clearStore(); + return { + opened: false, + error: selection.error, + selection_error: selection.detail, + method: "spa_router", + view: "scene_builder", + scene_id: resolvedSceneId, + has_textbox: false, + }; + } for (let i = 0; i < 25; i += 1) { if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } + const postCheck = verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); + if (!postCheck.ok) { + clearStore(); + return { + opened: false, + error: postCheck.error, + selection_error: postCheck.detail, + method: "spa_router", + view: "scene_builder", + scene_id: resolvedSceneId, + has_textbox: false, + }; + } clearStore(); const hasTextbox = Boolean(findTextbox(true)); const alert = readComposerAlert(!hasTextbox); @@ -342,6 +177,7 @@ export async function openEditAsset( method: "spa_router", view: "scene_builder", scene_id: resolvedSceneId, + selected_clip_id: postCheck.selectedClipId, has_textbox: false, }; } @@ -351,6 +187,7 @@ export async function openEditAsset( method: "spa_router", view: "scene_builder", scene_id: resolvedSceneId, + selected_clip_id: postCheck.selectedClipId, has_textbox: hasTextbox, }; } @@ -384,7 +221,9 @@ export async function openEditAsset( document.querySelector("flow-scene-builder")) ) ) { - await navigateSpa(router, ["/project", pid, "edit", candId]); + await withLViewMapCapture(async () => { + await navigateSpa(router, ["/project", pid, "edit", candId]); + }); } let viewKind: string | null = null; const waitTicks = router ? 60 : 30; @@ -404,16 +243,87 @@ export async function openEditAsset( if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } - if ( - !readComposerAlert(false) && - viewKind === "scene_builder" && - !findTextbox(true) - ) { - const sb = document.querySelector("flow-scene-builder") || document; - await selectSceneClip(sb, idStr, primaryStr, mediaUrl, clipIndex); - for (let i = 0; i < 20; i += 1) { - if (readComposerAlert(false) || findTextbox(true)) break; - await delay(100); + let selectedClipId: string | undefined; + if (viewKind === "scene_builder") { + const sbEl = document.querySelector("flow-scene-builder"); + const sbNode: ParentNode = sbEl || document; + await ensureSceneBuilderLViewMap(sbNode); + let singleVideoMatch = false; + if (sbEl) { + const rawCtx = (sbEl as NgContextCarrier).__ngContext__; + const sbLv = + resolveLView(sbEl) ?? (Array.isArray(rawCtx) ? rawCtx : null); + const sbSlots: unknown[] = Array.isArray(sbLv) ? sbLv : [sbEl]; + for (const slot of sbSlots) { + if (!slot || typeof slot !== "object" || slot instanceof Node) { + continue; + } + const wfInput = readComponentInput(slot, "workflowId"); + if ( + wfInput.found && + typeof wfInput.value === "string" && + wfInput.value.trim() + ) { + const wfVal = wfInput.value.trim(); + if (wfVal !== candId && wfVal !== idStr && wfVal !== primaryStr) { + clearStore(); + return { + opened: false, + error: "scene_clip_selection_mismatch", + selection_error: `Video editor targets workflow '${wfVal}' instead of '${idStr || candId}'.`, + method: "spa_router", + view: viewKind, + has_textbox: false, + }; + } + singleVideoMatch = true; + selectedClipId = idStr || candId; + break; + } + } + } + const hasTimelineOrClips = + Boolean(sbNode.querySelector("flow-scene-timeline")) || + collectSceneClipElements(sbNode).length > 0; + if (!singleVideoMatch && (hasTimelineOrClips || !findTextbox(true))) { + const selection = await selectSceneClip( + sbNode, + idStr || candId, + primaryStr, + ); + if (!selection.ok) { + clearStore(); + return { + opened: false, + error: selection.error, + selection_error: selection.detail, + method: "spa_router", + view: viewKind, + has_textbox: false, + }; + } + selectedClipId = selection.selectedClipId; + for (let i = 0; i < 20; i += 1) { + if (readComposerAlert(false) || findTextbox(true)) break; + await delay(100); + } + const postCheck = verifySelectedSceneClipInBuilder( + sbNode, + idStr || candId, + primaryStr, + ); + if (!postCheck.ok) { + clearStore(); + return { + opened: false, + error: postCheck.error, + selection_error: postCheck.detail, + method: "spa_router", + view: viewKind, + has_textbox: false, + }; + } + selectedClipId = postCheck.selectedClipId; } } @@ -427,6 +337,7 @@ export async function openEditAsset( alert, method: "spa_router", view: viewKind, + selected_clip_id: selectedClipId, has_textbox: false, }; } @@ -436,6 +347,7 @@ export async function openEditAsset( opened: true, method: "spa_router", view: viewKind, + selected_clip_id: selectedClipId, has_textbox: true, }; } @@ -532,6 +444,43 @@ export async function openEditAsset( if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } + let uiSelectedClipId: string | undefined; + const uiSb = document.querySelector("flow-scene-builder"); + if ( + uiSb && + (Boolean(uiSb.querySelector("flow-scene-timeline")) || + collectSceneClipElements(uiSb).length > 0) + ) { + const uiSelection = await selectSceneClip(uiSb, idStr, primaryStr); + if (!uiSelection.ok) { + clearStore(); + return { + opened: false, + error: uiSelection.error, + selection_error: uiSelection.detail, + method: "ui_edit", + view: "scene_builder", + has_textbox: false, + }; + } + const uiPostCheck = verifySelectedSceneClipInBuilder( + uiSb, + idStr, + primaryStr, + ); + if (!uiPostCheck.ok) { + clearStore(); + return { + opened: false, + error: uiPostCheck.error, + selection_error: uiPostCheck.detail, + method: "ui_edit", + view: "scene_builder", + has_textbox: false, + }; + } + uiSelectedClipId = uiPostCheck.selectedClipId; + } const hasTextbox = Boolean(findTextbox(true)); const alert = readComposerAlert(!hasTextbox); if (alert) { @@ -541,12 +490,18 @@ export async function openEditAsset( error: "edit_alert", alert, method: "ui_edit", + selected_clip_id: uiSelectedClipId, has_textbox: false, }; } if (hasTextbox) { clearStore(); - return { opened: true, method: "ui_edit", has_textbox: true }; + return { + opened: true, + method: "ui_edit", + selected_clip_id: uiSelectedClipId, + has_textbox: true, + }; } } } diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..d2890eb 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -1,12 +1,74 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Read clips and workflow history from the native scene tile. +// Read clips and workflow history from the native scene tile, and select and verify timeline clips in `flow-scene-builder`. -import { readOwn } from "./angular"; +import { + isLiveLView, + readOwn, + resolveLView, + withLViewMapCapture, + type NgContextCarrier, +} from "./angular"; +import { + EDIT_PROMPT_BOX_SELECTOR, + findTextbox, + isVisibleOutsideNonComposer, + NON_COMPOSER_PANELS, + readComposerAlert, +} from "./composer"; +import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { runtimeState } from "./state"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +/** Controls inside `flow-scene-builder` that are never timeline clip items. */ +const NON_CLIP_CONTROLS = `${NON_COMPOSER_PANELS}, ${EDIT_PROMPT_BOX_SELECTOR}, flow-playback-control, flow-extend-menu, flow-clip-context-menu, .add-clip-button-container, .add-clip-button, .timeline-controls, .zoom-controls, .cdk-overlay-pane, [role="menu"], [role="listbox"]`; + +/** Selectors that identify timeline clip containers inside `flow-scene-builder`. */ +const CLIP_CONTAINER_SELECTOR = + '.clip, [data-workflow-id], [data-clip-id], [data-asset-id], [data-clip-index], [data-testid*="clip"]:not(button):not([role="menuitem"]), [class*="timeline-clip"], [class*="clip-item"], [class*="clip-card"]'; + +/** Status strings that indicate a timeline clip is not ready for editing. */ +const NOT_READY_CLIP_STATUS = + /^(?:pending|scheduled|generating|loading|unloaded|failed|canceled)$/i; + +/** Extracted identifiers and readiness flags for one timeline clip element. */ +interface SceneClipInspection { + /** Explicit clip workflow identifiers on the element or its LView. */ + workflowIds: string[]; + /** Clip or asset identifiers on the element or its LView. */ + clipIds: string[]; + /** Media identifiers on the element or its LView. */ + mediaIds: string[]; + /** Stripped identifiers from `PLACEHOLDER_` or `extend-failed-` items. */ + placeholderIds: string[]; + /** True when the clip is loading, a placeholder, splitting, or failed. */ + notReady: boolean; + /** True when the item is a secondary extend-composing or failed-extend pill. */ + isAuxiliaryItem: boolean; +} + +/** Timeline clip elements grouped by match and readiness state. */ +interface MatchedSceneClips { + /** All visible timeline clip container elements in the timeline. */ + allClips: HTMLElement[]; + /** Ready, selectable clip elements matching the requested ID. */ + readyMatches: HTMLElement[]; + /** Unloaded, placeholder, or failed clip elements matching the requested ID. */ + notReadyMatches: HTMLElement[]; +} + +/** Outcome of selecting and verifying a target clip in `flow-scene-builder`. */ +export type SceneClipSelectionResult = + | { ok: true; selectedClipId: string } + | { ok: false; error: string; detail: string }; + +/** Builds a failed scene clip selection result with error code and detail. */ +function selectionFailure(error: string, detail: string): SceneClipSelectionResult { + return { ok: false, error, detail }; +} + /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { const format = frontendBuild(readBuildLabel())?.projectStore.scene; @@ -20,3 +82,713 @@ export function sceneContents(tile: FlowTile) { history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), }; } + +/** Calls a zero-argument signal getter or returns a plain property value from `obj`. */ +function readSignalOrValue(obj: object, key: string): unknown { + const raw = readOwn(obj, key); + if (typeof raw === "function" && raw.length === 0) { + try { + return raw.call(obj); + } catch { + return undefined; + } + } + return raw; +} + +/** Resolves the instance property key for a declared Angular input name. */ +function resolveInputPropertyKey(inst: object, inputName: string): string | null { + if (inputName in inst) return inputName; + const ctor = (inst as { constructor?: unknown }).constructor; + if (typeof ctor !== "function") return null; + for (const staticKey of Object.getOwnPropertyNames(ctor)) { + let def: unknown; + try { + def = Reflect.get(ctor, staticKey); + } catch { + continue; + } + if (!def || typeof def !== "object" || readOwn(def, "type") !== ctor) { + continue; + } + const inputs = readOwn(def, "inputs"); + if (!inputs || typeof inputs !== "object") continue; + const mapping = readOwn(inputs, inputName); + if (typeof mapping === "string" && mapping) return mapping; + if (Array.isArray(mapping) && typeof mapping[0] === "string" && mapping[0]) { + return mapping[0]; + } + for (const [propKey, rawSpec] of Object.entries(inputs)) { + if (rawSpec === inputName) return propKey; + if (Array.isArray(rawSpec) && rawSpec[1] === inputName && propKey) { + return propKey; + } + } + } + return null; +} + +/** Reads a named Angular component input or signal property from `inst`. */ +export function readComponentInput( + inst: object, + inputName: string, +): { found: boolean; value: unknown } { + const propKey = resolveInputPropertyKey(inst, inputName); + if (!propKey) return { found: false, value: undefined }; + return { found: true, value: readSignalOrValue(inst, propKey) }; +} + +/** Appends a trimmed identifier to `target`, recording `PLACEHOLDER_` and `extend-failed-` prefixes separately. */ +function pushClipIdentifier( + raw: unknown, + target: string[], + placeholderIds: string[], +): boolean { + if (typeof raw !== "string" && typeof raw !== "number") return false; + const val = String(raw).trim(); + if (!val || /^flow-scene-timeline-area-\d+$/.test(val)) return false; + if (val.startsWith("PLACEHOLDER_")) { + const rest = val.slice("PLACEHOLDER_".length).trim(); + if (rest && !placeholderIds.includes(rest)) placeholderIds.push(rest); + return true; + } + if (val.startsWith("extend-failed-")) { + const rest = val.slice("extend-failed-".length).trim(); + if (rest && !placeholderIds.includes(rest)) placeholderIds.push(rest); + return true; + } + if (!target.includes(val)) target.push(val); + return false; +} + +/** Returns true when `token` equals `expected` or has the timeline clip ID form `-`. */ +function matchesClipIdToken(token: string, expected: string): boolean { + const clean = token.trim(); + if (!clean || !expected) return false; + if (clean === expected) return true; + return ( + clean.startsWith(`${expected}-`) && + /^\d+$/.test(clean.slice(expected.length + 1)) + ); +} + +/** Inspects a candidate object in an Angular LView for clip identifiers and readiness flags. */ +function inspectClipObject(cand: unknown, info: SceneClipInspection): void { + if ( + !cand || + typeof cand !== "object" || + cand instanceof Node || + cand instanceof Error || + cand instanceof Map || + cand instanceof Set || + Array.isArray(cand) + ) { + return; + } + const rawType = String(readOwn(cand, "type") || "").trim(); + if (rawType.toUpperCase() === "SCENE") return; + const lowType = rawType.toLowerCase(); + if (lowType === "extend-composing" || lowType === "failed") { + info.isAuxiliaryItem = true; + info.notReady = true; + } else if (NOT_READY_CLIP_STATUS.test(lowType)) { + info.notReady = true; + } + if ( + readOwn(cand, "kN") === true || + readOwn(cand, "isLoading") === true || + readOwn(cand, "loaded") === false || + Boolean(readOwn(cand, "AC")) + ) { + info.notReady = true; + } + for (const statusKey of ["od", "Zc", "status", "state"]) { + const st = readOwn(cand, statusKey); + if (typeof st === "string" && NOT_READY_CLIP_STATUS.test(st.trim())) { + info.notReady = true; + } + } + if (pushClipIdentifier(readOwn(cand, "workflowId"), info.workflowIds, info.placeholderIds)) { + info.notReady = true; + } + for (const mediaKey of ["primaryMediaId", "mediaId"]) { + if (pushClipIdentifier(readOwn(cand, mediaKey), info.mediaIds, info.placeholderIds)) { + info.notReady = true; + } + } + for (const clipKey of ["clipId", "gI"]) { + if (pushClipIdentifier(readOwn(cand, clipKey), info.clipIds, info.placeholderIds)) { + info.notReady = true; + } + } + const hasClipShape = + "workflowId" in cand || + "primaryMediaId" in cand || + "mediaId" in cand || + "clipId" in cand || + "gI" in cand || + "Jc" in cand || + "Pc" in cand || + "start" in cand || + "end" in cand; + if (hasClipShape && pushClipIdentifier(readOwn(cand, "id"), info.clipIds, info.placeholderIds)) { + info.notReady = true; + } +} + +/** Extracts all clip identifiers and readiness flags from one timeline clip element. */ +function inspectSceneClipElement(clipEl: HTMLElement): SceneClipInspection { + const info: SceneClipInspection = { + workflowIds: [], + clipIds: [], + mediaIds: [], + placeholderIds: [], + notReady: false, + isAuxiliaryItem: false, + }; + const cls = clipEl.classList; + if (cls.contains("extend-composing") || cls.contains("failed")) { + info.isAuxiliaryItem = true; + info.notReady = true; + } + if ( + cls.contains("pending-placeholder") || + cls.contains("is-extend-generating") || + cls.contains("loading") || + cls.contains("is-loading") || + cls.contains("clip-loading") || + cls.contains("unloaded") || + cls.contains("is-unloaded") + ) { + info.notReady = true; + } + if ( + clipEl.getAttribute("aria-busy") === "true" || + clipEl.getAttribute("aria-disabled") === "true" || + clipEl.hasAttribute("disabled") || + clipEl.getAttribute("data-loading") === "true" || + clipEl.getAttribute("data-loaded") === "false" || + clipEl.getAttribute("data-ready") === "false" || + NOT_READY_CLIP_STATUS.test( + (clipEl.getAttribute("data-status") || clipEl.getAttribute("data-state") || "").trim(), + ) + ) { + info.notReady = true; + } + const busyChild = clipEl.querySelector( + '.processing-shimmer, .extend-loading-overlay, .split-pending-overlay, .loading-spinner, mat-progress-spinner, mat-spinner, flow-error-tile, .extend-failed-tile, [aria-busy="true"]', + ); + if (busyChild && (busyChild === clipEl || isVisibleOutsideNonComposer(busyChild))) { + info.notReady = true; + } + + const innerNodes = [ + clipEl, + ...Array.from(clipEl.querySelectorAll("*")).filter((n) => !n.closest(NON_CLIP_CONTROLS)), + ]; + const candidateLViews: unknown[][] = []; + if (runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if (isLiveLView(lv) && lv[0] instanceof Node && clipEl.contains(lv[0])) { + candidateLViews.push(lv); + } + } + } + const seenSlots = new Set(); + for (const node of innerNodes) { + if (pushClipIdentifier(node.getAttribute("data-workflow-id"), info.workflowIds, info.placeholderIds)) { + info.notReady = true; + } + for (const mAttr of ["data-media-id", "data-primary-media-id"]) { + if (pushClipIdentifier(node.getAttribute(mAttr), info.mediaIds, info.placeholderIds)) { + info.notReady = true; + } + } + for (const cAttr of ["data-clip-id", "data-asset-id", "data-id", "id"]) { + if (pushClipIdentifier(node.getAttribute(cAttr), info.clipIds, info.placeholderIds)) { + info.notReady = true; + } + } + const rawCtx = (node as NgContextCarrier).__ngContext__; + const lv = resolveLView(node) ?? (Array.isArray(rawCtx) ? rawCtx : null); + if (Array.isArray(lv)) { + if (!(lv[0] instanceof Node) || clipEl.contains(lv[0])) candidateLViews.push(lv); + } else if (rawCtx && typeof rawCtx === "object" && !(rawCtx instanceof Node)) { + inspectClipObject(rawCtx, info); + } + } + for (const lv of candidateLViews) { + for (const rawSlot of lv) { + const subItems = Array.isArray(rawSlot) ? rawSlot : [rawSlot]; + for (const slot of subItems) { + if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot) || seenSlots.has(slot)) { + continue; + } + seenSlots.add(slot); + const stripClipId = readComponentInput(slot, "clipId"); + if (stripClipId.found && pushClipIdentifier(stripClipId.value, info.clipIds, info.placeholderIds)) { + info.notReady = true; + } + inspectClipObject(slot, info); + for (const wrapKey of ["$implicit", "Aa", "clip", "item", "data", "Jj"]) { + const nested = readOwn(slot, wrapKey); + if (nested && typeof nested === "object") inspectClipObject(nested, info); + } + } + } + } + return info; +} + +/** Checks whether `info` matches the requested clip `idStr` or `primaryStr` without workflow ID conflicts. */ +function clipIdentityMatches( + info: SceneClipInspection, + idStr: string, + primaryStr: string, +): { matches: boolean; exactAssetId: boolean } { + if (!idStr && !primaryStr) return { matches: false, exactAssetId: false }; + if (idStr && info.workflowIds.length > 0) { + const wfMatch = info.workflowIds.includes(idStr); + return { matches: wfMatch, exactAssetId: wfMatch }; + } + if ( + idStr && + (info.workflowIds.includes(idStr) || + info.clipIds.some((t) => matchesClipIdToken(t, idStr)) || + info.mediaIds.some((t) => matchesClipIdToken(t, idStr)) || + info.placeholderIds.some((t) => matchesClipIdToken(t, idStr))) + ) { + return { matches: true, exactAssetId: true }; + } + if ( + primaryStr && + (info.mediaIds.some((t) => matchesClipIdToken(t, primaryStr)) || + info.clipIds.some((t) => matchesClipIdToken(t, primaryStr)) || + info.placeholderIds.some((t) => matchesClipIdToken(t, primaryStr))) + ) { + return { matches: true, exactAssetId: false }; + } + return { matches: false, exactAssetId: false }; +} + +/** Collects distinct visible timeline clip container elements inside `searchRoot`. */ +export function collectSceneClipElements(searchRoot: ParentNode): HTMLElement[] { + const rawSet = new Set(); + for (const el of Array.from(searchRoot.querySelectorAll(CLIP_CONTAINER_SELECTOR))) { + if (isVisibleOutsideNonComposer(el) && !el.closest(NON_CLIP_CONTROLS)) { + rawSet.add(el); + } + } + for (const el of Array.from(searchRoot.querySelectorAll("*"))) { + if (!isVisibleOutsideNonComposer(el) || el.closest(NON_CLIP_CONTROLS)) continue; + const container = el.closest(CLIP_CONTAINER_SELECTOR); + if ( + container instanceof HTMLElement && + searchRoot.contains(container) && + isVisibleOutsideNonComposer(container) && + !container.closest(NON_CLIP_CONTROLS) + ) { + rawSet.add(container); + continue; + } + if (el.hasAttribute("data-media-id") || el.hasAttribute("data-primary-media-id")) { + rawSet.add(el); + } + } + const all = Array.from(rawSet); + const singleContainers = all.filter((el) => { + const children = all.filter((other) => other !== el && el.contains(other)); + for (let i = 0; i < children.length; i += 1) { + for (let j = i + 1; j < children.length; j += 1) { + if (!children[i].contains(children[j]) && !children[j].contains(children[i])) { + return false; + } + } + } + return true; + }); + return singleContainers.filter( + (el) => !singleContainers.some((anc) => anc !== el && anc.contains(el)), + ); +} + +/** Finds all ready and not-ready clip elements matching `idStr` or `primaryStr` in `searchRoot`. */ +function matchSceneClips( + searchRoot: ParentNode, + idStr: string, + primaryStr: string, +): MatchedSceneClips { + const allClips = collectSceneClipElements(searchRoot); + const exactReady: HTMLElement[] = []; + const primaryReady: HTMLElement[] = []; + const notReadyMatches: HTMLElement[] = []; + for (const clipEl of allClips) { + const info = inspectSceneClipElement(clipEl); + const match = clipIdentityMatches(info, idStr, primaryStr); + if (!match.matches) continue; + if (info.isAuxiliaryItem || info.notReady) { + notReadyMatches.push(clipEl); + } else if (match.exactAssetId) { + exactReady.push(clipEl); + } else { + primaryReady.push(clipEl); + } + } + return { + allClips, + readyMatches: exactReady.length > 0 ? exactReady : primaryReady, + notReadyMatches, + }; +} + +/** Returns true when a timeline clip container carries a positive DOM selection state. */ +function isClipElementSelectedInDom(el: HTMLElement): boolean { + if (el.getAttribute("aria-selected") === "false" || el.getAttribute("data-selected") === "false") { + return false; + } + if (el.querySelector(".unselected-mask")) return false; + return ( + el.classList.contains("selected") || + el.classList.contains("is-selected") || + el.classList.contains("active") || + el.getAttribute("aria-selected") === "true" || + el.getAttribute("aria-current") === "true" || + el.getAttribute("data-selected") === "true" || + el.hasAttribute("selected") + ); +} + +/** Verifies that `sb` selects `targetClip` and marks it ready for editing. */ +function verifySceneClipSelection( + sb: ParentNode, + targetClip: HTMLElement, + allClips: HTMLElement[], + idStr: string, + primaryStr: string, +): SceneClipSelectionResult { + const label = idStr || primaryStr; + if (!isVisibleOutsideNonComposer(targetClip)) { + return selectionFailure("scene_clip_not_selected", `Clip '${label}' is no longer visible in the scene timeline.`); + } + const targetInfo = inspectSceneClipElement(targetClip); + if (!clipIdentityMatches(targetInfo, idStr, primaryStr).matches) { + return selectionFailure("scene_clip_selection_mismatch", `Selected timeline element does not match clip '${label}'.`); + } + if (targetInfo.notReady) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); + } + if ( + targetClip.getAttribute("aria-selected") === "false" || + targetClip.getAttribute("data-selected") === "false" || + Boolean(targetClip.querySelector(".unselected-mask")) + ) { + return selectionFailure("scene_clip_not_selected", `Clip '${label}' is not selected in the scene timeline.`); + } + for (const other of allClips) { + if (other === targetClip || targetClip.contains(other) || other.contains(targetClip)) { + continue; + } + if (isClipElementSelectedInDom(other)) { + return selectionFailure("scene_clip_selection_mismatch", `Another timeline clip is selected instead of '${label}'.`); + } + } + + const domProvesSelected = isClipElementSelectedInDom(targetClip); + let componentProvesSelected = false; + + const mediaSharedInTimeline = + Boolean(primaryStr) && + allClips.some((other) => { + if (other === targetClip) return false; + const otherInfo = inspectSceneClipElement(other); + return ( + !otherInfo.isAuxiliaryItem && + (otherInfo.mediaIds.some((t) => matchesClipIdToken(t, primaryStr)) || + otherInfo.clipIds.some((t) => matchesClipIdToken(t, primaryStr))) + ); + }); + + const hostCandidates = [ + ...(sb instanceof Element ? [sb] : []), + ...Array.from( + sb.querySelectorAll(`flow-scene-timeline, ${EDIT_PROMPT_BOX_SELECTOR}, flow-base-prompt-box`), + ).filter((el) => !el.closest(NON_COMPOSER_PANELS)), + ]; + const hostSet = new Set(hostCandidates); + const rawSlots: unknown[] = [...hostCandidates]; + for (const host of hostCandidates) { + const rawCtx = (host as NgContextCarrier).__ngContext__; + const lv = resolveLView(host) ?? (Array.isArray(rawCtx) ? rawCtx : null); + if (Array.isArray(lv)) rawSlots.push(...lv); + else if (rawCtx && typeof rawCtx === "object") rawSlots.push(rawCtx); + } + if (runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if ( + isLiveLView(lv) && + lv[0] instanceof Element && + !lv[0].closest(NON_COMPOSER_PANELS) && + (lv[0] === sb || sb.contains(lv[0])) + ) { + rawSlots.push(...lv); + } + } + } + const seenObjs = new Set(); + for (const rawSlot of rawSlots) { + const subSlots = Array.isArray(rawSlot) ? rawSlot : [rawSlot]; + for (const slot of subSlots) { + if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue; + if (slot instanceof Node && (!(slot instanceof Element) || !hostSet.has(slot))) continue; + if (seenObjs.has(slot)) continue; + seenObjs.add(slot); + + const loadingInput = readComponentInput(slot, "isClipLoading"); + if (loadingInput.found && loadingInput.value === true) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the editor.`); + } + const disabledReason = readComponentInput(slot, "submitDisabledReason"); + if ( + disabledReason.found && + typeof disabledReason.value === "string" && + /finish loading/i.test(disabledReason.value) + ) { + return selectionFailure("scene_clip_not_loaded", disabledReason.value.trim()); + } + const placeholderInput = readComponentInput(slot, "placeholderText"); + if ( + placeholderInput.found && + typeof placeholderInput.value === "string" && + /select a clip to edit/i.test(placeholderInput.value) + ) { + return selectionFailure("scene_clip_not_selected", `Editor still prompts to select a clip instead of '${label}'.`); + } + + for (const wfProp of ["selectedWorkflowId", "selectedClipId", "activeWorkflowId", "activeClipId"]) { + if (!(wfProp in slot)) continue; + const rawWf = readSignalOrValue(slot, wfProp); + if (typeof rawWf === "string" && rawWf.trim()) { + const val = rawWf.trim(); + const matchesTarget = + (Boolean(idStr) && matchesClipIdToken(val, idStr)) || + (Boolean(primaryStr) && matchesClipIdToken(val, primaryStr)) || + targetInfo.clipIds.includes(val); + if (!matchesTarget) { + return selectionFailure("scene_clip_selection_mismatch", `Active scene clip is '${val}' instead of '${label}'.`); + } + if (!mediaSharedInTimeline || (Boolean(idStr) && val === idStr)) { + componentProvesSelected = true; + } + } + } + + const selClip = readComponentInput(slot, "selectedClip"); + if (selClip.found) { + if (selClip.value === null || selClip.value === undefined) { + return selectionFailure("scene_clip_not_selected", `No clip is loaded in the edit composer for '${label}'.`); + } + if (typeof selClip.value === "object") { + const sc = selClip.value as object; + const scWf = String(readOwn(sc, "workflowId") || "").trim(); + const scId = String(readOwn(sc, "id") || readOwn(sc, "clipId") || "").trim(); + const scMedia = String(readOwn(sc, "primaryMediaId") || readOwn(sc, "mediaId") || "").trim(); + if (scId.startsWith("PLACEHOLDER_")) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the edit composer.`); + } + if (scWf && idStr && scWf !== idStr) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets workflow '${scWf}' instead of '${label}'.`); + } + if (scWf && idStr && scWf === idStr) componentProvesSelected = true; + for (const tok of [scMedia, scId].filter(Boolean)) { + const matchesKnown = + (Boolean(idStr) && matchesClipIdToken(tok, idStr)) || + (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr)) || + targetInfo.clipIds.some((c) => matchesClipIdToken(tok, c)) || + targetInfo.mediaIds.some((m) => matchesClipIdToken(tok, m)); + if ( + !matchesKnown && + (Boolean(primaryStr) || targetInfo.clipIds.length > 0 || targetInfo.mediaIds.length > 0) + ) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets clip '${tok}' instead of '${label}'.`); + } + if ( + matchesKnown && + !mediaSharedInTimeline && + ((Boolean(idStr) && matchesClipIdToken(tok, idStr)) || + (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr))) + ) { + componentProvesSelected = true; + } + } + } + } + + const selMedia = readComponentInput(slot, "selectedClipMediaId"); + if (selMedia.found) { + const sm = selMedia.value != null ? String(selMedia.value).trim() : ""; + if (!sm) { + return selectionFailure("scene_clip_not_selected", `Edit composer has no selected clip media ID for '${label}'.`); + } + const matchesMedia = + (Boolean(primaryStr) && sm === primaryStr) || + (Boolean(idStr) && sm === idStr) || + targetInfo.mediaIds.includes(sm); + if (!matchesMedia && (Boolean(primaryStr) || targetInfo.mediaIds.length > 0)) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets media '${sm}' instead of '${label}'.`); + } + if (!mediaSharedInTimeline && ((Boolean(primaryStr) && sm === primaryStr) || (Boolean(idStr) && sm === idStr))) { + componentProvesSelected = true; + } + } + } + } + + const tb = findTextbox(true); + if (tb) { + const ph = ( + tb.getAttribute("placeholder") || + tb.getAttribute("data-placeholder") || + tb.getAttribute("aria-placeholder") || + "" + ).trim(); + if (/select a clip to edit/i.test(ph)) { + return selectionFailure("scene_clip_not_selected", `Editor textbox still asks to select a clip instead of '${label}'.`); + } + } + + if (!domProvesSelected && !componentProvesSelected) { + return selectionFailure("scene_clip_selection_unverified", `Cannot verify selection of clip '${label}' in the scene timeline.`); + } + return { ok: true, selectedClipId: label }; +} + +/** Finds the unique matching clip in `sb` and verifies its active selection. */ +export function verifySelectedSceneClipInBuilder( + sb: ParentNode, + idStr: string, + primaryStr: string, +): SceneClipSelectionResult { + const label = idStr || primaryStr; + if (!label) { + return selectionFailure("scene_clip_id_required", "A clip ID is required to select a scene clip."); + } + const searchRoot = sb.querySelector("flow-scene-timeline") || sb; + const { allClips, readyMatches, notReadyMatches } = matchSceneClips(searchRoot, idStr, primaryStr); + if (readyMatches.length === 0) { + if (notReadyMatches.length > 0) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); + } + return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); + } + if (readyMatches.length > 1) { + return selectionFailure("scene_clip_ambiguous", `Multiple timeline clips match '${label}'.`); + } + return verifySceneClipSelection(sb, readyMatches[0], allClips, idStr, primaryStr); +} + +/** Captures Angular's LView registry map from `sb` when numeric `__ngContext__` slots are unresolved. */ +export async function ensureSceneBuilderLViewMap(sb: ParentNode): Promise { + const numericNodes = Array.from(sb.querySelectorAll("*")) + .slice(0, 60) + .filter((el) => typeof (el as NgContextCarrier).__ngContext__ === "number"); + if (numericNodes.length === 0) return; + if (runtimeState.ngLViewMap instanceof Map) { + const allResolved = numericNodes.every((el) => { + const idx = (el as NgContextCarrier).__ngContext__ as number; + const lv = runtimeState.ngLViewMap?.get(idx); + return isLiveLView(lv) && (!(lv[0] instanceof Node) || el === lv[0] || sb.contains(lv[0])); + }); + if (allResolved) return; + runtimeState.ngLViewMap = null; + } + await withLViewMapCapture(async () => { + const probes = Array.from( + sb.querySelectorAll("[mattooltip], [cdkoverlayorigin], button[aria-label], .clip, [class*='clip']"), + ) + .filter((el) => !el.closest(NON_COMPOSER_PANELS) && el.getClientRects().length > 0) + .slice(0, 8); + await hoverProbe(probes, 20); + }); +} + +/** Selects the matching clip ID in `flow-scene-builder`, opens clip edit mode, and proves selection. */ +export async function selectSceneClip( + sb: ParentNode, + idStr: string, + primaryStr: string, +): Promise { + const label = idStr || primaryStr; + if (!label) { + return { + ok: false, + error: "scene_clip_id_required", + detail: "A clip ID is required to select a scene clip.", + }; + } + + await ensureSceneBuilderLViewMap(sb); + + let targetClip: HTMLElement | null = null; + let allClips: HTMLElement[] = []; + let sawNotReadyMatch = false; + let sawAmbiguousMatch = false; + + for (let i = 0; i < 25; i += 1) { + await ensureSceneBuilderLViewMap(sb); + const searchRoot = sb.querySelector("flow-scene-timeline") || sb; + const matched = matchSceneClips(searchRoot, idStr, primaryStr); + allClips = matched.allClips; + if (matched.readyMatches.length === 1) { + targetClip = matched.readyMatches[0]; + sawAmbiguousMatch = false; + break; + } + sawAmbiguousMatch = matched.readyMatches.length > 1; + sawNotReadyMatch = matched.notReadyMatches.length > 0; + await delay(100); + } + + if (!targetClip) { + if (sawAmbiguousMatch) { + return selectionFailure("scene_clip_ambiguous", `Multiple timeline clips match '${label}'.`); + } + if (sawNotReadyMatch) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); + } + return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); + } + + let verified = verifySceneClipSelection(sb, targetClip, allClips, idStr, primaryStr); + if (!verified.ok) { + targetClip.scrollIntoView({ block: "nearest", inline: "center" }); + await withLViewMapCapture(async () => { + targetClip.click(); + await delay(150); + }); + for (let i = 0; i < 15; i += 1) { + verified = verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); + if (verified.ok) break; + await delay(100); + } + } + if (!verified.ok) return verified; + + if (readComposerAlert(false)) return verified; + + if (!findTextbox(true) || Boolean(document.querySelector(".is-extend-mode, .extend-composing"))) { + const editTrigger = Array.from( + sb.querySelectorAll('button, [role="button"], [role="tab"]'), + ).find((b): b is HTMLElement => { + if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) 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 /^(?:exit extend mode|edit(?:\s+(?:clip|video))?)$/i.test(lbl); + }); + if (editTrigger) { + editTrigger.click(); + await delay(300); + } + } + + return verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); +} From 0b1db25dd6514802a8e61bfe0659ea1670402eb9 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:15:01 +0000 Subject: [PATCH 3/4] fix(flow): fix edit history, timeline, and fallback checks - Collect failed history variants without timestamp keys or order - Keep primary media_status and media_error in asset snapshots - Read timeline clips from declared Angular inputs and store data - Allow selection of failed clips and report unreadable timelines - Move run_edit and shared open-edit checks into src/edit.rs - Keep image edit fallback active if workspace navigation fails --- src/assets.rs | 22 +- src/edit.rs | 243 +++++++++++++++ src/generation.rs | 294 +++--------------- src/main.rs | 1 + src/mcp.rs | 3 +- src/service.rs | 6 +- ts/read_store_snapshot.ts | 145 ++++----- ts/scene_tiles.ts | 621 +++++++++++++++++++------------------- ts/types.ts | 14 +- 9 files changed, 691 insertions(+), 658 deletions(-) create mode 100644 src/edit.rs diff --git a/src/assets.rs b/src/assets.rs index 3c94698..1e8c2d0 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -27,6 +27,18 @@ 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); +/// Failed or canceled media variant entry recorded in asset history. +#[derive(Debug, Clone, Default, Deserialize)] +pub(crate) struct FailedVariant { + /// Variant media ID or permutation-invariant fallback key. + pub(crate) id: String, + /// Lowercase failure status (`"failed"` or `"canceled"`). + pub(crate) status: String, + /// Optional failure message reported by Flow. + #[serde(default)] + pub(crate) error: Option, +} + /// Media asset or scene item inside a Google Flow project. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub(crate) struct FlowAsset { @@ -63,9 +75,9 @@ 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, - /// Newest variant ID in asset or scene clip history. + /// Internal failed or canceled variants recorded in asset history. #[serde(default, skip_serializing)] - pub(crate) latest_variant_id: Option, + pub(crate) failed_variants: Vec, /// Character personality notes or introduction text. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) personality_notes: Option, @@ -172,13 +184,11 @@ async fn populate_missing_media_urls( ) { let mut missing: HashMap> = HashMap::new(); for (index, asset) in assets.iter().enumerate() { - let primary_not_ready = (asset.media_error.is_some() + let primary_not_ready = asset.media_error.is_some() || matches!( asset.media_status.as_deref(), Some("pending" | "scheduled" | "failed" | "canceled") - )) - && (asset.latest_variant_id.is_none() - || asset.latest_variant_id == asset.primary_media_id); + ); if !matches!( asset.kind.as_str(), "video" | "image" | "character" | "audio" diff --git a/src/edit.rs b/src/edit.rs new file mode 100644 index 0000000..c285974 --- /dev/null +++ b/src/edit.rs @@ -0,0 +1,243 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Google Flow asset editing and scene clip selection workflow. +//! +//! Opens the asset or scene editor through the browser runtime, submits edit prompts, and tracks +//! updated or failed variants. + +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::download::download_resolved_asset; +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 an alert or clip error. +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); + } + if let Some(sel_err) = open_res + .get("selection_error") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); + } + 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" => { + let clip_ids: Vec<&str> = snap + .assets + .iter() + .filter(|a| a.scene_id.as_deref() == Some(target.id.as_str())) + .map(|a| a.id.as_str()) + .take(6) + .collect(); + let hint = if clip_ids.is_empty() { + String::new() + } else { + format!(" Available clip IDs: {}.", clip_ids.join(", ")) + }; + anyhow::bail!( + "Cannot edit scene container '{}' directly; pass one of its video clip IDs to flow_edit.{}", + target.id, + hint + ); + } + "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" { + "video" + } else { + "image" + }; + + let open_args = json!([ + target.id, + target.url, + target.primary_media_id, + target.scene_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| { + if res.get("opened").and_then(|v| v.as_bool()) != Some(true) + || res.get("has_textbox").and_then(|v| v.as_bool()) != Some(true) + || res.get("selection_error").is_some() + { + return false; + } + if target.scene_id.is_some() || res.get("scene_id").and_then(|v| v.as_str()).is_some() { + return res.get("selected_clip_id").and_then(|v| v.as_str()) + == Some(target.id.as_str()); + } + 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; + } + + let mut attached_frames: Option> = None; + if !opened_in_ui { + if edit_mode == "video" { + let _ = ensure_project_workspace_root(engine).await; + anyhow::bail!( + "Could not open an inline edit control or editor route for video asset '{}'", + label + ); + } + if ensure_project_workspace_root(engine).await.is_err() { + let _ = ensure_flow_store(engine).await; + } + 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 cur_url = engine.current_url().await.unwrap_or_default(); + let in_edit_route = opened_in_ui && (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: 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 before_failed_ids: HashSet = target + .failed_variants + .iter() + .map(|v| v.id.clone()) + .collect(); + 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(), + before_failed_variant_ids: &before_failed_ids, + url: target.url.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 62de2ea..cb920ea 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,47 +63,37 @@ 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)] -struct WatchedAsset<'a> { +pub(crate) struct WatchedAsset<'a> { /// Asset or scene clip workflow ID. - id: &'a str, + pub(crate) id: &'a str, /// Primary media ID before edit submission. - primary_media_id: Option<&'a str>, - /// Newest variant ID in history before edit submission. - latest_variant_id: Option<&'a str>, + pub(crate) primary_media_id: Option<&'a str>, + /// Failed or canceled variant IDs already present before edit submission. + pub(crate) before_failed_variant_ids: &'a HashSet, /// Resolved media URL before edit submission. - url: Option<&'a str>, - /// True when the watched asset already reported a failed or canceled variant before submission. - was_failed: bool, + pub(crate) url: 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, + pub(crate) before_ids: &'a HashSet, /// Optional existing tile watched for replacement updates or variant failures. - watch_updated: Option>, + 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 { @@ -241,7 +231,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()) @@ -338,7 +328,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, @@ -437,19 +427,38 @@ async fn wait_for_new_assets( } if let Some(w) = spec.watch_updated && let Some(watched) = snap.assets.iter().find(|a| a.id == w.id) - && matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) - && (watched.latest_variant_id.as_deref() != w.latest_variant_id - || watched.primary_media_id.as_deref() != w.primary_media_id - || !w.was_failed) { - anyhow::bail!( - "Flow edit failed on {}: {}", - w.id, - watched - .media_error - .as_deref() - .unwrap_or(watched.media_status.as_deref().unwrap_or("failed")) - ); + if let Some(failed_variant) = watched + .failed_variants + .iter() + .find(|v| !v.id.is_empty() && !w.before_failed_variant_ids.contains(&v.id)) + { + anyhow::bail!( + "Flow edit failed on {}: {}", + w.id, + failed_variant + .error + .as_deref() + .unwrap_or(failed_variant.status.as_str()) + ); + } + let primary_changed = + match (watched.primary_media_id.as_deref(), w.primary_media_id) { + (Some(cur), Some(prev)) => cur != prev, + _ => false, + }; + if matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) + && (!w.was_failed || primary_changed) + { + anyhow::bail!( + "Flow edit failed on {}: {}", + w.id, + watched + .media_error + .as_deref() + .unwrap_or(watched.media_status.as_deref().unwrap_or("failed")) + ); + } } } @@ -610,208 +619,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))?; - match target.kind.as_str() { - "scene" => { - let clip_ids: Vec<&str> = snap - .assets - .iter() - .filter(|a| a.scene_id.as_deref() == Some(target.id.as_str())) - .map(|a| a.id.as_str()) - .take(6) - .collect(); - let hint = if clip_ids.is_empty() { - String::new() - } else { - format!(" Available clip IDs: {}.", clip_ids.join(", ")) - }; - anyhow::bail!( - "Cannot edit scene container '{}' directly; pass one of its video clip IDs to flow_edit.{}", - target.id, - hint - ); - } - "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" { - "video" - } else { - "image" - }; - - let open_args = json!([ - target.id, - target.url, - target.primary_media_id, - target.scene_id - ]); - let mut open_res = engine - .call_flow_async("openEditAsset", open_args.clone()) - .await - .unwrap_or_default(); - 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); - } - if let Some(sel_err) = open_res - .get("selection_error") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - { - let _ = ensure_project_workspace_root(engine).await; - anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); - } - let is_editor_open = |res: &serde_json::Value| { - if res.get("opened").and_then(|v| v.as_bool()) != Some(true) - || res.get("has_textbox").and_then(|v| v.as_bool()) != Some(true) - || res.get("selection_error").is_some() - { - return false; - } - if target.scene_id.is_some() || res.get("scene_id").and_then(|v| v.as_str()).is_some() { - return res.get("selected_clip_id").and_then(|v| v.as_str()) - == Some(target.id.as_str()); - } - 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(); - 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); - } - if let Some(sel_err) = open_res - .get("selection_error") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - { - let _ = ensure_project_workspace_root(engine).await; - anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); - } - opened_in_ui = is_editor_open(&open_res); - } else if opened_in_ui { - let _ = ensure_flow_store(engine).await; - } - - let mut attached_frames: Option> = None; - if !opened_in_ui { - ensure_project_workspace_root(engine).await?; - if edit_mode == "video" { - anyhow::bail!( - "Could not open an inline edit control or editor 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 cur_url = engine.current_url().await.unwrap_or_default(); - let in_edit_route = opened_in_ui && (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: 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 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(), - latest_variant_id: target.latest_variant_id.as_deref(), - url: target.url.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/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/read_store_snapshot.ts b/ts/read_store_snapshot.ts index d017d67..9b0b33e 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -28,6 +28,7 @@ import type { SceneClipItem, SnapshotAssetItem, SnapshotCollectionItem, + SnapshotFailedVariant, StoreSnapshotResult, } from "./types"; @@ -37,34 +38,54 @@ const ACCOUNT_CREDITS_RE = /(?:^|[^\w,])(\d[\d,]*)\s+(?:Google\s+Flow|Flow|AI)\s /** Selector matching generation credit cost estimates that are not account balances. */ const COST_LABEL_SELECTOR = "flow-credit-cost-label, .credit-cost-label, .credit-cost-link"; -/** Reads the creation timestamp in milliseconds from a media payload when available. */ -function variantTimestampMs( - media: FlowMediaPayload | null | undefined, -): number | null { - if (!media || typeof media !== "object") return null; - const rawDate = - media.hc ?? media.kc ?? (media as Record).lc; - return rawDate instanceof Date && Number.isFinite(rawDate.getTime()) - ? rawDate.getTime() - : null; -} - -/** Selects the newest normalized media variant from a tile or scene clip history list. */ -function pickLatestHistoryVariant(history: unknown): FlowMediaPayload | null { - if (!Array.isArray(history) || history.length === 0) return null; - let best: FlowMediaPayload | null = null; - let bestTs: number | null = null; +/** Collects failed or canceled variants from a history array without relying on sort order. */ +function collectFailedVariants( + history: unknown, + formatMediaError: (errVal: unknown) => string | null, +): SnapshotFailedVariant[] { + if (!Array.isArray(history) || history.length === 0) return []; + const out: SnapshotFailedVariant[] = []; + const seenIds = new Set(); + const anonCounts = new Map(); for (const item of history) { if (!item || typeof item !== "object") continue; const norm = legacyMedia(item as FlowMediaPayload); if (!norm) continue; - const curTs = variantTimestampMs(norm); - if (!best || curTs === null || bestTs === null || curTs >= bestTs) { - best = norm; - bestTs = curTs; + const status = String(norm.Zc ?? "").toLowerCase(); + const error = formatMediaError(norm.nf); + if (status !== "failed" && status !== "canceled" && error === null) { + continue; + } + const rawId = String(norm.id ?? norm.mediaId ?? "").trim(); + let key = rawId; + if (!key) { + const sig = `${status || "failed"}:${error ?? ""}`; + const occ = (anonCounts.get(sig) ?? 0) + 1; + anonCounts.set(sig, occ); + key = `anon#${occ}:${sig}`; + } + if (seenIds.has(key)) continue; + seenIds.add(key); + out.push({ id: key, status: status || "failed", error }); + } + return out; +} + +/** Appends failed variant entries from `extra` whose IDs are not already in `base`. */ +function mergeFailedVariants( + base: SnapshotFailedVariant[], + extra: SnapshotFailedVariant[], +): SnapshotFailedVariant[] { + if (extra.length === 0) return base; + const seen = new Set(base.map((v) => v.id)); + const merged = [...base]; + for (const item of extra) { + if (!seen.has(item.id)) { + seen.add(item.id); + merged.push(item); } } - return best; + return merged; } /** Locates an active Angular service instance matching `ServiceClass` in runtime state. */ @@ -380,24 +401,9 @@ export function readStoreTiles(tileMap: Map): { : Array.isArray(t.history) ? t.history : null; - const latestVariant = pickLatestHistoryVariant(rawHistory); - const latestVariantIdRaw = - latestVariant?.id ?? latestVariant?.mediaId ?? primaryMediaIdStr; - const latestVariantId = - latestVariantIdRaw != null && String(latestVariantIdRaw) !== "" - ? String(latestVariantIdRaw) - : null; - const latestStatus = latestVariant - ? String(latestVariant.Zc ?? "").toLowerCase() - : ""; - const latestError = latestVariant - ? formatMediaError(latestVariant.nf) - : null; - const mediaStatus = (latestStatus || primaryStatus) || null; - const mediaError = latestVariant - ? latestError ?? - (latestVariantId === primaryMediaIdStr ? primaryError : null) - : primaryError; + const failedVariants = collectFailedVariants(rawHistory, formatMediaError); + const mediaStatus = primaryStatus || null; + const mediaError = primaryError; const cachedEntry = primaryMediaId ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) @@ -462,7 +468,7 @@ export function readStoreTiles(tileMap: Map): { collection_id: cid, scene_id: null, primary_media_id: primaryMediaIdStr, - latest_variant_id: latestVariantId, + failed_variants: failedVariants, personality_notes: bio == null ? null : String(bio), voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, @@ -542,7 +548,7 @@ export function readStoreTiles(tileMap: Map): { ? (primaryId ? hist.find((x) => x && String(x.id ?? x.mediaId ?? "") === primaryId) : null) || - pickLatestHistoryVariant(hist) || + hist[0] || null : null; candidates.push([wfId, clip, mObj, hist]); @@ -550,7 +556,7 @@ export function readStoreTiles(tileMap: Map): { for (const [wfId, hist] of history) { if (!wfId || seenWfIds.has(wfId)) continue; seenWfIds.add(wfId); - const mObj = pickLatestHistoryVariant(hist); + const mObj = (Array.isArray(hist) && hist[0]) || null; candidates.push([wfId, null, mObj, hist]); } @@ -567,50 +573,13 @@ export function readStoreTiles(tileMap: Map): { : mObj?.id ? String(mObj.id) : null; - const latestClipVariant = pickLatestHistoryVariant(hist); - const latestClipIdRaw = - latestClipVariant?.id ?? latestClipVariant?.mediaId ?? clipPrimaryMediaId; - const latestClipVariantId = - latestClipIdRaw != null && String(latestClipIdRaw) !== "" - ? String(latestClipIdRaw) - : null; - const latestClipStatus = latestClipVariant - ? String(latestClipVariant.Zc ?? "").toLowerCase() - : ""; - const latestClipError = latestClipVariant - ? formatMediaError(latestClipVariant.nf) - : null; - const effectiveStatus = (latestClipStatus || primaryClipStatus) || null; - const effectiveError = latestClipVariant - ? latestClipError ?? - (latestClipVariantId === clipPrimaryMediaId ? primaryClipError : null) - : primaryClipError; + const clipFailedVariants = collectFailedVariants(hist, formatMediaError); const existing = byId.get(wfId); if (existing) { - if ( - latestClipVariantId && - (!existing.latest_variant_id || - existing.latest_variant_id === existing.primary_media_id) - ) { - existing.latest_variant_id = latestClipVariantId; - } - if ( - effectiveStatus === "failed" || - effectiveStatus === "canceled" || - effectiveStatus === "pending" || - effectiveStatus === "scheduled" || - effectiveError - ) { - if ( - existing.media_status !== "failed" && - existing.media_status !== "canceled" - ) { - existing.media_status = effectiveStatus || existing.media_status; - } - if (!existing.media_error && effectiveError) { - existing.media_error = effectiveError; - } - } + existing.failed_variants = mergeFailedVariants( + existing.failed_variants, + clipFailedVariants, + ); continue; } const mNotReady = @@ -691,13 +660,13 @@ export function readStoreTiles(tileMap: Map): { collection_id: sceneCid, scene_id: sceneId, primary_media_id: clipPrimaryMediaId, - latest_variant_id: latestClipVariantId, + failed_variants: clipFailedVariants, personality_notes: null, voice: null, trim_start_seconds: trimStartVal, trim_end_seconds: trimEndVal, - media_status: effectiveStatus, - media_error: effectiveError, + media_status: primaryClipStatus || null, + media_error: primaryClipError, width: typeof mObj?.width === "number" ? mObj.width diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index d2890eb..3eb65e0 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -25,38 +25,44 @@ import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; /** Controls inside `flow-scene-builder` that are never timeline clip items. */ const NON_CLIP_CONTROLS = `${NON_COMPOSER_PANELS}, ${EDIT_PROMPT_BOX_SELECTOR}, flow-playback-control, flow-extend-menu, flow-clip-context-menu, .add-clip-button-container, .add-clip-button, .timeline-controls, .zoom-controls, .cdk-overlay-pane, [role="menu"], [role="listbox"]`; -/** Selectors that identify timeline clip containers inside `flow-scene-builder`. */ +/** Selectors that identify timeline clip elements inside `flow-scene-timeline`. */ const CLIP_CONTAINER_SELECTOR = - '.clip, [data-workflow-id], [data-clip-id], [data-asset-id], [data-clip-index], [data-testid*="clip"]:not(button):not([role="menuitem"]), [class*="timeline-clip"], [class*="clip-item"], [class*="clip-card"]'; + ".timeline-contents > .clip, .clip, [data-workflow-id], [data-clip-id]"; -/** Status strings that indicate a timeline clip is not ready for editing. */ -const NOT_READY_CLIP_STATUS = - /^(?:pending|scheduled|generating|loading|unloaded|failed|canceled)$/i; +/** Selectors that indicate an intentionally empty scene timeline track. */ +const EMPTY_TIMELINE_SELECTOR = ".empty-timeline-track, .is-empty"; + +/** Status values that indicate a timeline clip is still loading or generating. */ +const NOT_READY_CLIP_STATUS = /^(?:pending|scheduled|generating|loading|unloaded)$/i; /** Extracted identifiers and readiness flags for one timeline clip element. */ interface SceneClipInspection { - /** Explicit clip workflow identifiers on the element or its LView. */ + /** Clip workflow identifiers read from component inputs, LViews, or attributes. */ workflowIds: string[]; - /** Clip or asset identifiers on the element or its LView. */ + /** Clip identifiers read from component inputs, LViews, or attributes. */ clipIds: string[]; - /** Media identifiers on the element or its LView. */ + /** Media identifiers read from component inputs, LViews, or attributes. */ mediaIds: string[]; - /** Stripped identifiers from `PLACEHOLDER_` or `extend-failed-` items. */ + /** Stripped identifiers from `PLACEHOLDER_` clip items. */ placeholderIds: string[]; - /** True when the clip is loading, a placeholder, splitting, or failed. */ + /** True when the clip is actively loading, generating, splitting, or a placeholder. */ notReady: boolean; - /** True when the item is a secondary extend-composing or failed-extend pill. */ + /** True when the element is a secondary `extend-composing` or `extend-failed-` pill. */ isAuxiliaryItem: boolean; } -/** Timeline clip elements grouped by match and readiness state. */ +/** Timeline clip elements grouped by match, readiness, and UI readability state. */ interface MatchedSceneClips { - /** All visible timeline clip container elements in the timeline. */ + /** All visible timeline clip elements in the timeline. */ allClips: HTMLElement[]; - /** Ready, selectable clip elements matching the requested ID. */ + /** Selectable clip elements matching the requested ID. */ readyMatches: HTMLElement[]; - /** Unloaded, placeholder, or failed clip elements matching the requested ID. */ + /** Loading or placeholder clip elements matching the requested ID. */ notReadyMatches: HTMLElement[]; + /** True when the scene has clips or a non-empty timeline, yet clip metadata cannot be read. */ + unreadable: boolean; + /** Cached inspection metadata per timeline clip element. */ + inspections: Map; } /** Outcome of selecting and verifying a target clip in `flow-scene-builder`. */ @@ -108,9 +114,7 @@ function resolveInputPropertyKey(inst: object, inputName: string): string | null } catch { continue; } - if (!def || typeof def !== "object" || readOwn(def, "type") !== ctor) { - continue; - } + if (!def || typeof def !== "object" || readOwn(def, "type") !== ctor) continue; const inputs = readOwn(def, "inputs"); if (!inputs || typeof inputs !== "object") continue; const mapping = readOwn(inputs, inputName); @@ -120,9 +124,7 @@ function resolveInputPropertyKey(inst: object, inputName: string): string | null } for (const [propKey, rawSpec] of Object.entries(inputs)) { if (rawSpec === inputName) return propKey; - if (Array.isArray(rawSpec) && rawSpec[1] === inputName && propKey) { - return propKey; - } + if (Array.isArray(rawSpec) && rawSpec[1] === inputName && propKey) return propKey; } } return null; @@ -138,41 +140,122 @@ export function readComponentInput( return { found: true, value: readSignalOrValue(inst, propKey) }; } -/** Appends a trimmed identifier to `target`, recording `PLACEHOLDER_` and `extend-failed-` prefixes separately. */ -function pushClipIdentifier( +/** Collects unique non-Node object slots associated with `hosts` and live child LViews. */ +function collectHostSlots(hosts: Element[], scopeRoot?: ParentNode): object[] { + const hostSet = new Set(hosts); + const rawSlots: unknown[] = [...hosts]; + for (const host of hosts) { + const rawCtx = (host as NgContextCarrier).__ngContext__; + const lv = resolveLView(host) ?? (Array.isArray(rawCtx) ? rawCtx : null); + if (Array.isArray(lv)) rawSlots.push(...lv); + else if (rawCtx && typeof rawCtx === "object") rawSlots.push(rawCtx); + } + if (scopeRoot && runtimeState.ngLViewMap instanceof Map) { + for (const lv of runtimeState.ngLViewMap.values()) { + if ( + isLiveLView(lv) && + lv[0] instanceof Element && + !lv[0].closest(NON_COMPOSER_PANELS) && + (lv[0] === scopeRoot || scopeRoot.contains(lv[0])) + ) { + rawSlots.push(...lv); + } + } + } + const seen = new Set(); + const out: object[] = []; + for (const rawSlot of rawSlots) { + for (const slot of Array.isArray(rawSlot) ? rawSlot : [rawSlot]) { + if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue; + if (slot instanceof Node && (!(slot instanceof Element) || !hostSet.has(slot))) continue; + if (seen.has(slot)) continue; + seen.add(slot); + out.push(slot); + } + } + return out; +} + +/** Reads the declared `clips` input array from `` when available. */ +function readTimelineClipsInput(timelineEl: Element | null): { + found: boolean; + items: unknown[]; +} { + if (!timelineEl) return { found: false, items: [] }; + for (const slot of collectHostSlots([timelineEl], timelineEl)) { + const res = readComponentInput(slot, "clips"); + if (res.found && Array.isArray(res.value)) { + return { found: true, items: res.value }; + } + } + return { found: false, items: [] }; +} + +/** Checks whether the active scene in the bound store has clips, is empty, or is unknown. */ +function sceneStoreClipState( + sb: ParentNode, + timelineEl: Element | null, +): "has_clips" | "empty" | "unknown" { + const tileMap = runtimeState.store?.getTileMap?.(); + if (!(tileMap instanceof Map)) return "unknown"; + let sceneId = /\/scene\/([^/?#]+)/.exec(location.pathname || "")?.[1] || ""; + if (!sceneId && timelineEl) { + for (const slot of collectHostSlots([timelineEl])) { + const inp = readComponentInput(slot, "sceneId"); + if (inp.found && typeof inp.value === "string" && inp.value.trim()) { + sceneId = inp.value.trim(); + break; + } + } + } + if (!sceneId && sb instanceof Element) { + sceneId = sb.getAttribute("data-scene-id") || ""; + } + const sceneTile = sceneId ? tileMap.get(sceneId) : undefined; + if (!sceneTile) return "unknown"; + return sceneContents(sceneTile).clips.length > 0 ? "has_clips" : "empty"; +} + +/** Appends a trimmed clip token, flagging `PLACEHOLDER_` and `extend-failed-` prefixes. */ +function recordClipToken( raw: unknown, target: string[], - placeholderIds: string[], -): boolean { - if (typeof raw !== "string" && typeof raw !== "number") return false; + info: SceneClipInspection, +): void { + if (typeof raw !== "string" && typeof raw !== "number") return; const val = String(raw).trim(); - if (!val || /^flow-scene-timeline-area-\d+$/.test(val)) return false; + if (!val || /^flow-scene-timeline-area-\d+$/.test(val)) return; + if (val === "PLACEHOLDER_extend_clip") { + info.isAuxiliaryItem = true; + info.notReady = true; + return; + } if (val.startsWith("PLACEHOLDER_")) { const rest = val.slice("PLACEHOLDER_".length).trim(); - if (rest && !placeholderIds.includes(rest)) placeholderIds.push(rest); - return true; + if (rest && !info.placeholderIds.includes(rest)) info.placeholderIds.push(rest); + info.notReady = true; + return; } if (val.startsWith("extend-failed-")) { const rest = val.slice("extend-failed-".length).trim(); - if (rest && !placeholderIds.includes(rest)) placeholderIds.push(rest); - return true; + if (rest && !info.clipIds.includes(rest)) info.clipIds.push(rest); + info.isAuxiliaryItem = true; + return; } if (!target.includes(val)) target.push(val); - return false; } /** Returns true when `token` equals `expected` or has the timeline clip ID form `-`. */ function matchesClipIdToken(token: string, expected: string): boolean { const clean = token.trim(); if (!clean || !expected) return false; - if (clean === expected) return true; return ( - clean.startsWith(`${expected}-`) && - /^\d+$/.test(clean.slice(expected.length + 1)) + clean === expected || + (clean.startsWith(`${expected}-`) && /^\d+$/.test(clean.slice(expected.length + 1))) ); } -/** Inspects a candidate object in an Angular LView for clip identifiers and readiness flags. */ +/** Inspects a plain clip descriptor using non-minified property names. */ function inspectClipObject(cand: unknown, info: SceneClipInspection): void { if ( !cand || @@ -188,56 +271,43 @@ function inspectClipObject(cand: unknown, info: SceneClipInspection): void { const rawType = String(readOwn(cand, "type") || "").trim(); if (rawType.toUpperCase() === "SCENE") return; const lowType = rawType.toLowerCase(); - if (lowType === "extend-composing" || lowType === "failed") { + if (lowType === "extend-composing") { info.isAuxiliaryItem = true; info.notReady = true; } else if (NOT_READY_CLIP_STATUS.test(lowType)) { info.notReady = true; } - if ( - readOwn(cand, "kN") === true || - readOwn(cand, "isLoading") === true || - readOwn(cand, "loaded") === false || - Boolean(readOwn(cand, "AC")) - ) { + if (readOwn(cand, "isLoading") === true || readOwn(cand, "loaded") === false) { info.notReady = true; } - for (const statusKey of ["od", "Zc", "status", "state"]) { + for (const statusKey of ["status", "state"]) { const st = readOwn(cand, statusKey); if (typeof st === "string" && NOT_READY_CLIP_STATUS.test(st.trim())) { info.notReady = true; } } - if (pushClipIdentifier(readOwn(cand, "workflowId"), info.workflowIds, info.placeholderIds)) { - info.notReady = true; - } - for (const mediaKey of ["primaryMediaId", "mediaId"]) { - if (pushClipIdentifier(readOwn(cand, mediaKey), info.mediaIds, info.placeholderIds)) { - info.notReady = true; - } - } - for (const clipKey of ["clipId", "gI"]) { - if (pushClipIdentifier(readOwn(cand, clipKey), info.clipIds, info.placeholderIds)) { - info.notReady = true; - } - } + recordClipToken(readOwn(cand, "workflowId"), info.workflowIds, info); + recordClipToken(readOwn(cand, "primaryMediaId"), info.mediaIds, info); + recordClipToken(readOwn(cand, "mediaId"), info.mediaIds, info); + recordClipToken(readOwn(cand, "clipId"), info.clipIds, info); const hasClipShape = "workflowId" in cand || "primaryMediaId" in cand || "mediaId" in cand || "clipId" in cand || - "gI" in cand || - "Jc" in cand || - "Pc" in cand || "start" in cand || - "end" in cand; - if (hasClipShape && pushClipIdentifier(readOwn(cand, "id"), info.clipIds, info.placeholderIds)) { - info.notReady = true; + "end" in cand || + (lowType !== "" && lowType !== "collection"); + if (hasClipShape) { + recordClipToken(readOwn(cand, "id"), info.clipIds, info); } } -/** Extracts all clip identifiers and readiness flags from one timeline clip element. */ -function inspectSceneClipElement(clipEl: HTMLElement): SceneClipInspection { +/** Extracts clip identifiers and readiness flags from one timeline clip element and optional `clips` input item. */ +function inspectSceneClipElement( + clipEl: HTMLElement, + timelineClipItem?: unknown, +): SceneClipInspection { const info: SceneClipInspection = { workflowIds: [], clipIds: [], @@ -246,8 +316,10 @@ function inspectSceneClipElement(clipEl: HTMLElement): SceneClipInspection { notReady: false, isAuxiliaryItem: false, }; + if (timelineClipItem !== undefined) inspectClipObject(timelineClipItem, info); + const cls = clipEl.classList; - if (cls.contains("extend-composing") || cls.contains("failed")) { + if (cls.contains("extend-composing")) { info.isAuxiliaryItem = true; info.notReady = true; } @@ -256,91 +328,65 @@ function inspectSceneClipElement(clipEl: HTMLElement): SceneClipInspection { cls.contains("is-extend-generating") || cls.contains("loading") || cls.contains("is-loading") || - cls.contains("clip-loading") || cls.contains("unloaded") || - cls.contains("is-unloaded") - ) { - info.notReady = true; - } - if ( clipEl.getAttribute("aria-busy") === "true" || clipEl.getAttribute("aria-disabled") === "true" || clipEl.hasAttribute("disabled") || clipEl.getAttribute("data-loading") === "true" || clipEl.getAttribute("data-loaded") === "false" || - clipEl.getAttribute("data-ready") === "false" || NOT_READY_CLIP_STATUS.test( (clipEl.getAttribute("data-status") || clipEl.getAttribute("data-state") || "").trim(), ) ) { info.notReady = true; } + if (clipEl.querySelector(".extend-failed-tile")) info.isAuxiliaryItem = true; const busyChild = clipEl.querySelector( - '.processing-shimmer, .extend-loading-overlay, .split-pending-overlay, .loading-spinner, mat-progress-spinner, mat-spinner, flow-error-tile, .extend-failed-tile, [aria-busy="true"]', + '.processing-shimmer, .extend-loading-overlay, .split-pending-overlay, mat-progress-spinner, mat-spinner, [aria-busy="true"]', ); if (busyChild && (busyChild === clipEl || isVisibleOutsideNonComposer(busyChild))) { info.notReady = true; } - const innerNodes = [ + const probeEls = [ clipEl, - ...Array.from(clipEl.querySelectorAll("*")).filter((n) => !n.closest(NON_CLIP_CONTROLS)), + ...Array.from( + clipEl.querySelectorAll( + ".thumbnail-strip, [data-workflow-id], [data-clip-id], [data-media-id], [data-primary-media-id]", + ), + ).filter((el) => !el.closest(NON_CLIP_CONTROLS)), ]; - const candidateLViews: unknown[][] = []; - if (runtimeState.ngLViewMap instanceof Map) { - for (const lv of runtimeState.ngLViewMap.values()) { - if (isLiveLView(lv) && lv[0] instanceof Node && clipEl.contains(lv[0])) { - candidateLViews.push(lv); - } - } - } - const seenSlots = new Set(); - for (const node of innerNodes) { - if (pushClipIdentifier(node.getAttribute("data-workflow-id"), info.workflowIds, info.placeholderIds)) { - info.notReady = true; - } - for (const mAttr of ["data-media-id", "data-primary-media-id"]) { - if (pushClipIdentifier(node.getAttribute(mAttr), info.mediaIds, info.placeholderIds)) { - info.notReady = true; - } - } - for (const cAttr of ["data-clip-id", "data-asset-id", "data-id", "id"]) { - if (pushClipIdentifier(node.getAttribute(cAttr), info.clipIds, info.placeholderIds)) { - info.notReady = true; - } - } - const rawCtx = (node as NgContextCarrier).__ngContext__; - const lv = resolveLView(node) ?? (Array.isArray(rawCtx) ? rawCtx : null); - if (Array.isArray(lv)) { - if (!(lv[0] instanceof Node) || clipEl.contains(lv[0])) candidateLViews.push(lv); - } else if (rawCtx && typeof rawCtx === "object" && !(rawCtx instanceof Node)) { - inspectClipObject(rawCtx, info); - } - } - for (const lv of candidateLViews) { - for (const rawSlot of lv) { - const subItems = Array.isArray(rawSlot) ? rawSlot : [rawSlot]; - for (const slot of subItems) { - if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot) || seenSlots.has(slot)) { - continue; - } - seenSlots.add(slot); - const stripClipId = readComponentInput(slot, "clipId"); - if (stripClipId.found && pushClipIdentifier(stripClipId.value, info.clipIds, info.placeholderIds)) { - info.notReady = true; - } - inspectClipObject(slot, info); - for (const wrapKey of ["$implicit", "Aa", "clip", "item", "data", "Jj"]) { - const nested = readOwn(slot, wrapKey); - if (nested && typeof nested === "object") inspectClipObject(nested, info); - } - } + for (const node of probeEls) { + recordClipToken(node.getAttribute("data-workflow-id"), info.workflowIds, info); + recordClipToken(node.getAttribute("data-media-id"), info.mediaIds, info); + recordClipToken(node.getAttribute("data-primary-media-id"), info.mediaIds, info); + recordClipToken(node.getAttribute("data-clip-id"), info.clipIds, info); + recordClipToken(node.getAttribute("id"), info.clipIds, info); + } + for (const slot of collectHostSlots(probeEls, clipEl)) { + if (slot instanceof Node) continue; + const stripClipId = readComponentInput(slot, "clipId"); + if (stripClipId.found) recordClipToken(stripClipId.value, info.clipIds, info); + inspectClipObject(slot, info); + for (const wrapKey of ["$implicit", "clip", "item", "data"]) { + const nested = readOwn(slot, wrapKey); + if (nested && typeof nested === "object") inspectClipObject(nested, info); } } return info; } -/** Checks whether `info` matches the requested clip `idStr` or `primaryStr` without workflow ID conflicts. */ +/** Returns true when `info` exposes at least one clip, workflow, media, or placeholder identifier. */ +function hasAnyClipIdentifier(info: SceneClipInspection): boolean { + return ( + info.workflowIds.length > 0 || + info.clipIds.length > 0 || + info.mediaIds.length > 0 || + info.placeholderIds.length > 0 + ); +} + +/** Checks whether `info` matches `idStr` or `primaryStr` without workflow ID conflicts. */ function clipIdentityMatches( info: SceneClipInspection, idStr: string, @@ -353,8 +399,7 @@ function clipIdentityMatches( } if ( idStr && - (info.workflowIds.includes(idStr) || - info.clipIds.some((t) => matchesClipIdToken(t, idStr)) || + (info.clipIds.some((t) => matchesClipIdToken(t, idStr)) || info.mediaIds.some((t) => matchesClipIdToken(t, idStr)) || info.placeholderIds.some((t) => matchesClipIdToken(t, idStr))) ) { @@ -373,71 +418,65 @@ function clipIdentityMatches( /** Collects distinct visible timeline clip container elements inside `searchRoot`. */ export function collectSceneClipElements(searchRoot: ParentNode): HTMLElement[] { - const rawSet = new Set(); - for (const el of Array.from(searchRoot.querySelectorAll(CLIP_CONTAINER_SELECTOR))) { - if (isVisibleOutsideNonComposer(el) && !el.closest(NON_CLIP_CONTROLS)) { - rawSet.add(el); - } - } - for (const el of Array.from(searchRoot.querySelectorAll("*"))) { - if (!isVisibleOutsideNonComposer(el) || el.closest(NON_CLIP_CONTROLS)) continue; - const container = el.closest(CLIP_CONTAINER_SELECTOR); - if ( - container instanceof HTMLElement && - searchRoot.contains(container) && - isVisibleOutsideNonComposer(container) && - !container.closest(NON_CLIP_CONTROLS) - ) { - rawSet.add(container); - continue; - } - if (el.hasAttribute("data-media-id") || el.hasAttribute("data-primary-media-id")) { - rawSet.add(el); - } - } - const all = Array.from(rawSet); - const singleContainers = all.filter((el) => { - const children = all.filter((other) => other !== el && el.contains(other)); - for (let i = 0; i < children.length; i += 1) { - for (let j = i + 1; j < children.length; j += 1) { - if (!children[i].contains(children[j]) && !children[j].contains(children[i])) { - return false; - } - } - } - return true; - }); - return singleContainers.filter( - (el) => !singleContainers.some((anc) => anc !== el && anc.contains(el)), + const candidates = Array.from( + searchRoot.querySelectorAll(CLIP_CONTAINER_SELECTOR), + ).filter((el) => isVisibleOutsideNonComposer(el) && !el.closest(NON_CLIP_CONTROLS)); + return candidates.filter( + (el) => !candidates.some((anc) => anc !== el && anc.contains(el)), ); } -/** Finds all ready and not-ready clip elements matching `idStr` or `primaryStr` in `searchRoot`. */ -function matchSceneClips( - searchRoot: ParentNode, - idStr: string, - primaryStr: string, -): MatchedSceneClips { +/** Matches timeline clip elements in `sb` against `idStr` and `primaryStr`. */ +function matchSceneClips(sb: ParentNode, idStr: string, primaryStr: string): MatchedSceneClips { + const timelineEl = sb.querySelector("flow-scene-timeline"); + const searchRoot = timelineEl || sb; const allClips = collectSceneClipElements(searchRoot); + const timelineInput = readTimelineClipsInput(timelineEl); + const useIndexBinding = + timelineInput.found && timelineInput.items.length === allClips.length; + + const inspections = new Map(); const exactReady: HTMLElement[] = []; const primaryReady: HTMLElement[] = []; const notReadyMatches: HTMLElement[] = []; - for (const clipEl of allClips) { - const info = inspectSceneClipElement(clipEl); + let anyReadableId = false; + + for (let idx = 0; idx < allClips.length; idx += 1) { + const clipEl = allClips[idx]; + const info = inspectSceneClipElement( + clipEl, + useIndexBinding ? timelineInput.items[idx] : undefined, + ); + inspections.set(clipEl, info); + if (hasAnyClipIdentifier(info)) anyReadableId = true; const match = clipIdentityMatches(info, idStr, primaryStr); - if (!match.matches) continue; - if (info.isAuxiliaryItem || info.notReady) { - notReadyMatches.push(clipEl); - } else if (match.exactAssetId) { - exactReady.push(clipEl); - } else { - primaryReady.push(clipEl); - } + if (!match.matches || info.isAuxiliaryItem) continue; + if (info.notReady) notReadyMatches.push(clipEl); + else if (match.exactAssetId) exactReady.push(clipEl); + else primaryReady.push(clipEl); + } + + let unreadable = false; + if (allClips.length === 0) { + const storeState = sceneStoreClipState(sb, timelineEl); + const explicitlyEmpty = + Boolean(searchRoot.querySelector(EMPTY_TIMELINE_SELECTOR)) || + (timelineEl?.classList.contains("is-empty") ?? false) || + (timelineInput.found && timelineInput.items.length === 0); + unreadable = + storeState === "has_clips" || + (timelineInput.found && timelineInput.items.length > 0) || + (storeState !== "empty" && !explicitlyEmpty); + } else if (!anyReadableId) { + unreadable = true; } + return { allClips, readyMatches: exactReady.length > 0 ? exactReady : primaryReady, notReadyMatches, + unreadable, + inspections, }; } @@ -463,6 +502,7 @@ function verifySceneClipSelection( sb: ParentNode, targetClip: HTMLElement, allClips: HTMLElement[], + inspections: Map, idStr: string, primaryStr: string, ): SceneClipSelectionResult { @@ -470,7 +510,7 @@ function verifySceneClipSelection( if (!isVisibleOutsideNonComposer(targetClip)) { return selectionFailure("scene_clip_not_selected", `Clip '${label}' is no longer visible in the scene timeline.`); } - const targetInfo = inspectSceneClipElement(targetClip); + const targetInfo = inspections.get(targetClip) ?? inspectSceneClipElement(targetClip); if (!clipIdentityMatches(targetInfo, idStr, primaryStr).matches) { return selectionFailure("scene_clip_selection_mismatch", `Selected timeline element does not match clip '${label}'.`); } @@ -485,9 +525,7 @@ function verifySceneClipSelection( return selectionFailure("scene_clip_not_selected", `Clip '${label}' is not selected in the scene timeline.`); } for (const other of allClips) { - if (other === targetClip || targetClip.contains(other) || other.contains(targetClip)) { - continue; - } + if (other === targetClip || targetClip.contains(other) || other.contains(targetClip)) continue; if (isClipElementSelectedInDom(other)) { return selectionFailure("scene_clip_selection_mismatch", `Another timeline clip is selected instead of '${label}'.`); } @@ -495,12 +533,11 @@ function verifySceneClipSelection( const domProvesSelected = isClipElementSelectedInDom(targetClip); let componentProvesSelected = false; - const mediaSharedInTimeline = Boolean(primaryStr) && allClips.some((other) => { if (other === targetClip) return false; - const otherInfo = inspectSceneClipElement(other); + const otherInfo = inspections.get(other) ?? inspectSceneClipElement(other); return ( !otherInfo.isAuxiliaryItem && (otherInfo.mediaIds.some((t) => matchesClipIdToken(t, primaryStr)) || @@ -514,131 +551,84 @@ function verifySceneClipSelection( sb.querySelectorAll(`flow-scene-timeline, ${EDIT_PROMPT_BOX_SELECTOR}, flow-base-prompt-box`), ).filter((el) => !el.closest(NON_COMPOSER_PANELS)), ]; - const hostSet = new Set(hostCandidates); - const rawSlots: unknown[] = [...hostCandidates]; - for (const host of hostCandidates) { - const rawCtx = (host as NgContextCarrier).__ngContext__; - const lv = resolveLView(host) ?? (Array.isArray(rawCtx) ? rawCtx : null); - if (Array.isArray(lv)) rawSlots.push(...lv); - else if (rawCtx && typeof rawCtx === "object") rawSlots.push(rawCtx); - } - if (runtimeState.ngLViewMap instanceof Map) { - for (const lv of runtimeState.ngLViewMap.values()) { - if ( - isLiveLView(lv) && - lv[0] instanceof Element && - !lv[0].closest(NON_COMPOSER_PANELS) && - (lv[0] === sb || sb.contains(lv[0])) - ) { - rawSlots.push(...lv); - } + for (const slot of collectHostSlots(hostCandidates, sb)) { + const loadingInput = readComponentInput(slot, "isClipLoading"); + if (loadingInput.found && loadingInput.value === true) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the editor.`); + } + const disabledReason = readComponentInput(slot, "submitDisabledReason"); + if ( + disabledReason.found && + typeof disabledReason.value === "string" && + /finish loading/i.test(disabledReason.value) + ) { + return selectionFailure("scene_clip_not_loaded", disabledReason.value.trim()); + } + const placeholderInput = readComponentInput(slot, "placeholderText"); + if ( + placeholderInput.found && + typeof placeholderInput.value === "string" && + /select a clip to edit/i.test(placeholderInput.value) + ) { + return selectionFailure("scene_clip_not_selected", `Editor still prompts to select a clip instead of '${label}'.`); } - } - const seenObjs = new Set(); - for (const rawSlot of rawSlots) { - const subSlots = Array.isArray(rawSlot) ? rawSlot : [rawSlot]; - for (const slot of subSlots) { - if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue; - if (slot instanceof Node && (!(slot instanceof Element) || !hostSet.has(slot))) continue; - if (seenObjs.has(slot)) continue; - seenObjs.add(slot); - const loadingInput = readComponentInput(slot, "isClipLoading"); - if (loadingInput.found && loadingInput.value === true) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the editor.`); + const selClip = readComponentInput(slot, "selectedClip"); + if (selClip.found) { + if (selClip.value === null || selClip.value === undefined) { + return selectionFailure("scene_clip_not_selected", `No clip is loaded in the edit composer for '${label}'.`); } - const disabledReason = readComponentInput(slot, "submitDisabledReason"); - if ( - disabledReason.found && - typeof disabledReason.value === "string" && - /finish loading/i.test(disabledReason.value) - ) { - return selectionFailure("scene_clip_not_loaded", disabledReason.value.trim()); - } - const placeholderInput = readComponentInput(slot, "placeholderText"); - if ( - placeholderInput.found && - typeof placeholderInput.value === "string" && - /select a clip to edit/i.test(placeholderInput.value) - ) { - return selectionFailure("scene_clip_not_selected", `Editor still prompts to select a clip instead of '${label}'.`); - } - - for (const wfProp of ["selectedWorkflowId", "selectedClipId", "activeWorkflowId", "activeClipId"]) { - if (!(wfProp in slot)) continue; - const rawWf = readSignalOrValue(slot, wfProp); - if (typeof rawWf === "string" && rawWf.trim()) { - const val = rawWf.trim(); - const matchesTarget = - (Boolean(idStr) && matchesClipIdToken(val, idStr)) || - (Boolean(primaryStr) && matchesClipIdToken(val, primaryStr)) || - targetInfo.clipIds.includes(val); - if (!matchesTarget) { - return selectionFailure("scene_clip_selection_mismatch", `Active scene clip is '${val}' instead of '${label}'.`); - } - if (!mediaSharedInTimeline || (Boolean(idStr) && val === idStr)) { - componentProvesSelected = true; - } + if (typeof selClip.value === "object") { + const sc = selClip.value as object; + const scWf = String(readOwn(sc, "workflowId") || "").trim(); + const scId = String(readOwn(sc, "id") || readOwn(sc, "clipId") || "").trim(); + const scMedia = String(readOwn(sc, "primaryMediaId") || readOwn(sc, "mediaId") || "").trim(); + if (scId.startsWith("PLACEHOLDER_")) { + return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the edit composer.`); } - } - - const selClip = readComponentInput(slot, "selectedClip"); - if (selClip.found) { - if (selClip.value === null || selClip.value === undefined) { - return selectionFailure("scene_clip_not_selected", `No clip is loaded in the edit composer for '${label}'.`); + if (scWf && idStr && scWf !== idStr) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets workflow '${scWf}' instead of '${label}'.`); } - if (typeof selClip.value === "object") { - const sc = selClip.value as object; - const scWf = String(readOwn(sc, "workflowId") || "").trim(); - const scId = String(readOwn(sc, "id") || readOwn(sc, "clipId") || "").trim(); - const scMedia = String(readOwn(sc, "primaryMediaId") || readOwn(sc, "mediaId") || "").trim(); - if (scId.startsWith("PLACEHOLDER_")) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the edit composer.`); + if (scWf && idStr && scWf === idStr) componentProvesSelected = true; + for (const tok of [scMedia, scId].filter(Boolean)) { + const matchesKnown = + (Boolean(idStr) && matchesClipIdToken(tok, idStr)) || + (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr)) || + targetInfo.clipIds.some((c) => matchesClipIdToken(tok, c)) || + targetInfo.mediaIds.some((m) => matchesClipIdToken(tok, m)); + if ( + !matchesKnown && + (Boolean(primaryStr) || targetInfo.clipIds.length > 0 || targetInfo.mediaIds.length > 0) + ) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets clip '${tok}' instead of '${label}'.`); } - if (scWf && idStr && scWf !== idStr) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets workflow '${scWf}' instead of '${label}'.`); - } - if (scWf && idStr && scWf === idStr) componentProvesSelected = true; - for (const tok of [scMedia, scId].filter(Boolean)) { - const matchesKnown = - (Boolean(idStr) && matchesClipIdToken(tok, idStr)) || - (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr)) || - targetInfo.clipIds.some((c) => matchesClipIdToken(tok, c)) || - targetInfo.mediaIds.some((m) => matchesClipIdToken(tok, m)); - if ( - !matchesKnown && - (Boolean(primaryStr) || targetInfo.clipIds.length > 0 || targetInfo.mediaIds.length > 0) - ) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets clip '${tok}' instead of '${label}'.`); - } - if ( - matchesKnown && - !mediaSharedInTimeline && - ((Boolean(idStr) && matchesClipIdToken(tok, idStr)) || - (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr))) - ) { - componentProvesSelected = true; - } + if ( + matchesKnown && + !mediaSharedInTimeline && + ((Boolean(idStr) && matchesClipIdToken(tok, idStr)) || + (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr))) + ) { + componentProvesSelected = true; } } } + } - const selMedia = readComponentInput(slot, "selectedClipMediaId"); - if (selMedia.found) { - const sm = selMedia.value != null ? String(selMedia.value).trim() : ""; - if (!sm) { - return selectionFailure("scene_clip_not_selected", `Edit composer has no selected clip media ID for '${label}'.`); - } - const matchesMedia = - (Boolean(primaryStr) && sm === primaryStr) || - (Boolean(idStr) && sm === idStr) || - targetInfo.mediaIds.includes(sm); - if (!matchesMedia && (Boolean(primaryStr) || targetInfo.mediaIds.length > 0)) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets media '${sm}' instead of '${label}'.`); - } - if (!mediaSharedInTimeline && ((Boolean(primaryStr) && sm === primaryStr) || (Boolean(idStr) && sm === idStr))) { - componentProvesSelected = true; - } + const selMedia = readComponentInput(slot, "selectedClipMediaId"); + if (selMedia.found) { + const sm = selMedia.value != null ? String(selMedia.value).trim() : ""; + if (!sm) { + return selectionFailure("scene_clip_not_selected", `Edit composer has no selected clip media ID for '${label}'.`); + } + const matchesMedia = + (Boolean(primaryStr) && sm === primaryStr) || + (Boolean(idStr) && sm === idStr) || + targetInfo.mediaIds.includes(sm); + if (!matchesMedia && (Boolean(primaryStr) || targetInfo.mediaIds.length > 0)) { + return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets media '${sm}' instead of '${label}'.`); + } + if (!mediaSharedInTimeline && ((Boolean(primaryStr) && sm === primaryStr) || (Boolean(idStr) && sm === idStr))) { + componentProvesSelected = true; } } } @@ -672,18 +662,21 @@ export function verifySelectedSceneClipInBuilder( if (!label) { return selectionFailure("scene_clip_id_required", "A clip ID is required to select a scene clip."); } - const searchRoot = sb.querySelector("flow-scene-timeline") || sb; - const { allClips, readyMatches, notReadyMatches } = matchSceneClips(searchRoot, idStr, primaryStr); + const { allClips, readyMatches, notReadyMatches, unreadable, inspections } = + matchSceneClips(sb, idStr, primaryStr); if (readyMatches.length === 0) { if (notReadyMatches.length > 0) { return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); } + if (unreadable) { + return selectionFailure("scene_timeline_unreadable", "Scene timeline clips could not be read from the current Flow UI."); + } return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); } if (readyMatches.length > 1) { return selectionFailure("scene_clip_ambiguous", `Multiple timeline clips match '${label}'.`); } - return verifySceneClipSelection(sb, readyMatches[0], allClips, idStr, primaryStr); + return verifySceneClipSelection(sb, readyMatches[0], allClips, inspections, idStr, primaryStr); } /** Captures Angular's LView registry map from `sb` when numeric `__ngContext__` slots are unresolved. */ @@ -703,7 +696,7 @@ export async function ensureSceneBuilderLViewMap(sb: ParentNode): Promise } await withLViewMapCapture(async () => { const probes = Array.from( - sb.querySelectorAll("[mattooltip], [cdkoverlayorigin], button[aria-label], .clip, [class*='clip']"), + sb.querySelectorAll("[mattooltip], [cdkoverlayorigin], button[aria-label], .clip"), ) .filter((el) => !el.closest(NON_COMPOSER_PANELS) && el.getClientRects().length > 0) .slice(0, 8); @@ -719,25 +712,23 @@ export async function selectSceneClip( ): Promise { const label = idStr || primaryStr; if (!label) { - return { - ok: false, - error: "scene_clip_id_required", - detail: "A clip ID is required to select a scene clip.", - }; + return selectionFailure("scene_clip_id_required", "A clip ID is required to select a scene clip."); } await ensureSceneBuilderLViewMap(sb); let targetClip: HTMLElement | null = null; let allClips: HTMLElement[] = []; + let inspections = new Map(); let sawNotReadyMatch = false; let sawAmbiguousMatch = false; + let sawUnreadable = false; for (let i = 0; i < 25; i += 1) { await ensureSceneBuilderLViewMap(sb); - const searchRoot = sb.querySelector("flow-scene-timeline") || sb; - const matched = matchSceneClips(searchRoot, idStr, primaryStr); + const matched = matchSceneClips(sb, idStr, primaryStr); allClips = matched.allClips; + inspections = matched.inspections; if (matched.readyMatches.length === 1) { targetClip = matched.readyMatches[0]; sawAmbiguousMatch = false; @@ -745,6 +736,7 @@ export async function selectSceneClip( } sawAmbiguousMatch = matched.readyMatches.length > 1; sawNotReadyMatch = matched.notReadyMatches.length > 0; + sawUnreadable = matched.unreadable; await delay(100); } @@ -755,10 +747,13 @@ export async function selectSceneClip( if (sawNotReadyMatch) { return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); } + if (sawUnreadable) { + return selectionFailure("scene_timeline_unreadable", "Scene timeline clips could not be read from the current Flow UI."); + } return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); } - let verified = verifySceneClipSelection(sb, targetClip, allClips, idStr, primaryStr); + let verified = verifySceneClipSelection(sb, targetClip, allClips, inspections, idStr, primaryStr); if (!verified.ok) { targetClip.scrollIntoView({ block: "nearest", inline: "center" }); await withLViewMapCapture(async () => { diff --git a/ts/types.ts b/ts/types.ts index 72480c4..a30941a 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -520,6 +520,16 @@ export interface DiscoverStoreResult { error?: string; } +/** Failed or canceled media variant entry recorded in asset history. */ +export interface SnapshotFailedVariant { + /** Variant media identifier or permutation-invariant fallback key. */ + id: string; + /** Lowercase failure status (`failed` or `canceled`). */ + status: string; + /** Extracted failure message when present. */ + error: string | null; +} + /** Asset entry normalized for `readStoreSnapshot`. */ export interface SnapshotAssetItem { /** Tile or clip workflow identifier. */ @@ -540,8 +550,8 @@ export interface SnapshotAssetItem { scene_id: string | null; /** Primary media identifier. */ primary_media_id: string | null; - /** Newest variant identifier in tile or scene clip history. */ - latest_variant_id: string | null; + /** Failed or canceled variants recorded in tile or clip history. */ + failed_variants: SnapshotFailedVariant[]; /** Character personality notes. */ personality_notes: string | null; /** Assigned voice name or identifier. */ From 77943ac5e9fcff9196eeee0336b21b4927f4b6c2 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:52:20 +0000 Subject: [PATCH 4/4] fix(flow): verify nov29 composer fields and split out scene clip edits - Define PromptComposerFormat for build 20261129.06 and drop kf. - Bind flow-edit-image-prompt-box and exclude non-composer panels. - Fail explicitly when no edit textbox opens and keep scene duration. - Cut scene clip timeline and tile history changes for a second PR. - Bail fast when a failed primary fails again in wait_for_new_assets. --- src/assets.rs | 31 +- src/characters.rs | 14 +- src/edit.rs | 117 ++---- src/generation.rs | 54 +-- ts/attach_ingredients.ts | 87 ++--- ts/composer.ts | 99 +++-- ts/frontend_builds.ts | 104 +++-- ts/frontend_nov29.ts | 9 + ts/open_edit_asset.ts | 313 +++------------- ts/prompt_writer.ts | 132 +++---- ts/read_store_snapshot.ts | 152 ++------ ts/scene_tiles.ts | 771 +------------------------------------- ts/setup_generation.ts | 54 ++- ts/submit_generation.ts | 35 +- ts/types.ts | 103 +---- ts/video_ops.ts | 6 +- 16 files changed, 437 insertions(+), 1644 deletions(-) diff --git a/src/assets.rs b/src/assets.rs index 1e8c2d0..c3c8975 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -27,20 +27,8 @@ 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); -/// Failed or canceled media variant entry recorded in asset history. -#[derive(Debug, Clone, Default, Deserialize)] -pub(crate) struct FailedVariant { - /// Variant media ID or permutation-invariant fallback key. - pub(crate) id: String, - /// Lowercase failure status (`"failed"` or `"canceled"`). - pub(crate) status: String, - /// Optional failure message reported by Flow. - #[serde(default)] - pub(crate) error: Option, -} - /// Media asset or scene item inside a Google Flow project. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct FlowAsset { /// Flow asset or tile ID. pub(crate) id: String, @@ -60,9 +48,6 @@ pub(crate) struct FlowAsset { /// Parent collection display name. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) collection_name: Option, - /// Parent scene ID when this clip exists only inside a scene timeline. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub(crate) scene_id: Option, /// Media width in pixels. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) width: Option, @@ -75,9 +60,6 @@ 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, - /// Internal failed or canceled variants recorded in asset history. - #[serde(default, skip_serializing)] - pub(crate) failed_variants: Vec, /// Character personality notes or introduction text. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) personality_notes: Option, @@ -184,16 +166,15 @@ async fn populate_missing_media_urls( ) { let mut missing: HashMap> = HashMap::new(); for (index, asset) in assets.iter().enumerate() { - let primary_not_ready = asset.media_error.is_some() - || matches!( - asset.media_status.as_deref(), - Some("pending" | "scheduled" | "failed" | "canceled") - ); if !matches!( asset.kind.as_str(), "video" | "image" | "character" | "audio" ) || asset.url.is_some() - || primary_not_ready + || asset.media_error.is_some() + || matches!( + asset.media_status.as_deref(), + Some("pending" | "scheduled" | "failed" | "canceled") + ) { continue; } diff --git a/src/characters.rs b/src/characters.rs index d1ec45b..12c6de2 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -761,9 +761,21 @@ 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, - ..FlowAsset::default() + personality_notes: None, + voice: None, + trim_start_seconds: None, + trim_end_seconds: None, + media_status: None, + media_error: None, + created_at: None, }; if let Ok(rec) = download_resolved_asset( engine, diff --git a/src/edit.rs b/src/edit.rs index c285974..821a7b5 100644 --- a/src/edit.rs +++ b/src/edit.rs @@ -1,10 +1,10 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Google Flow asset editing and scene clip selection workflow. +//! Google Flow asset editing workflow. //! -//! Opens the asset or scene editor through the browser runtime, submits edit prompts, and tracks -//! updated or failed variants. +//! Opens the asset editor through the browser runtime, submits edit prompts, and tracks updated +//! outputs. use anyhow::{Context, Result}; use schemars::JsonSchema; @@ -15,7 +15,6 @@ use tokio::time::Duration; use crate::assets::{list_assets_with_project, match_asset}; use crate::db::FlowDb; -use crate::download::download_resolved_asset; use crate::engine::ChromeEngine; use crate::generation::{ AssetWaitSpec, WatchedAsset, apply_generation_controls, collect_created_assets, @@ -34,7 +33,7 @@ pub(crate) struct EditParams { pub(crate) prompt: String, } -/// Exits any editor subroute and returns an error when `openEditAsset` reports an alert or clip error. +/// 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, @@ -48,14 +47,6 @@ async fn check_open_edit_errors( let _ = ensure_project_workspace_root(engine).await; anyhow::bail!("Flow cannot edit '{}': {}", label, alert); } - if let Some(sel_err) = open_res - .get("selection_error") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - { - let _ = ensure_project_workspace_root(engine).await; - anyhow::bail!("Flow cannot select clip '{}': {}", label, sel_err); - } Ok(()) } @@ -73,25 +64,10 @@ pub(crate) async fn run_edit( .cloned() .with_context(|| format!("No asset matches '{}' for edit", match_str))?; match target.kind.as_str() { - "scene" => { - let clip_ids: Vec<&str> = snap - .assets - .iter() - .filter(|a| a.scene_id.as_deref() == Some(target.id.as_str())) - .map(|a| a.id.as_str()) - .take(6) - .collect(); - let hint = if clip_ids.is_empty() { - String::new() - } else { - format!(" Available clip IDs: {}.", clip_ids.join(", ")) - }; - anyhow::bail!( - "Cannot edit scene container '{}' directly; pass one of its video clip IDs to flow_edit.{}", - target.id, - hint - ); - } + "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 @@ -108,35 +84,22 @@ pub(crate) async fn run_edit( }; on_progress(format!("preparing edit for {}", label)); - let edit_mode = if target.kind == "video" { - "video" - } else { - "image" - }; + 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, - target.scene_id - ]); + 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| { - if res.get("opened").and_then(|v| v.as_bool()) != Some(true) - || res.get("has_textbox").and_then(|v| v.as_bool()) != Some(true) - || res.get("selection_error").is_some() - { - return false; - } - if target.scene_id.is_some() || res.get("scene_id").and_then(|v| v.as_str()).is_some() { - return res.get("selected_clip_id").and_then(|v| v.as_str()) - == Some(target.id.as_str()); - } - true + 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); @@ -154,39 +117,17 @@ pub(crate) async fn run_edit( let _ = ensure_flow_store(engine).await; } - let mut attached_frames: Option> = None; if !opened_in_ui { - if edit_mode == "video" { - let _ = ensure_project_workspace_root(engine).await; - anyhow::bail!( - "Could not open an inline edit control or editor route for video asset '{}'", - label - ); - } - if ensure_project_workspace_root(engine).await.is_err() { - let _ = ensure_flow_store(engine).await; - } - 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 _ = 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 = opened_in_ui && (cur_url.contains("/edit/") || cur_url.contains("/scene/")); + 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(), @@ -195,7 +136,7 @@ pub(crate) async fn run_edit( } else { Some(edit_mode.to_string()) }, - frames: attached_frames, + frames: None, count: Some(1), ..Default::default() }; @@ -204,11 +145,6 @@ pub(crate) async fn run_edit( let submit_summary = format_submit_progress("submitted edit", &submit_res); on_progress(submit_summary.clone()); - let before_failed_ids: HashSet = target - .failed_variants - .iter() - .map(|v| v.id.clone()) - .collect(); let target_was_failed = matches!(target.media_status.as_deref(), Some("failed" | "canceled")); let (created, project_id, project_title) = wait_for_new_assets( engine, @@ -217,8 +153,9 @@ pub(crate) async fn run_edit( watch_updated: Some(WatchedAsset { id: target.id.as_str(), primary_media_id: target.primary_media_id.as_deref(), - before_failed_variant_ids: &before_failed_ids, 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, diff --git a/src/generation.rs b/src/generation.rs index cb920ea..c90640e 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -66,14 +66,16 @@ pub(crate) struct GenerateParams { /// Baseline state of an existing asset watched for edit updates or failures. #[derive(Clone, Copy)] pub(crate) struct WatchedAsset<'a> { - /// Asset or scene clip workflow ID. + /// Asset workflow ID. pub(crate) id: &'a str, /// Primary media ID before edit submission. pub(crate) primary_media_id: Option<&'a str>, - /// Failed or canceled variant IDs already present before edit submission. - pub(crate) before_failed_variant_ids: &'a HashSet, /// 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, } @@ -340,6 +342,8 @@ pub(crate) 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; @@ -428,27 +432,31 @@ pub(crate) async fn wait_for_new_assets( if let Some(w) = spec.watch_updated && let Some(watched) = snap.assets.iter().find(|a| a.id == w.id) { - if let Some(failed_variant) = watched - .failed_variants - .iter() - .find(|v| !v.id.is_empty() && !w.before_failed_variant_ids.contains(&v.id)) - { - anyhow::bail!( - "Flow edit failed on {}: {}", - w.id, - failed_variant - .error - .as_deref() - .unwrap_or(failed_variant.status.as_str()) - ); + 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 = - match (watched.primary_media_id.as_deref(), w.primary_media_id) { - (Some(cur), Some(prev)) => cur != prev, - _ => false, - }; - if matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) - && (!w.was_failed || primary_changed) + 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 {}: {}", diff --git a/ts/attach_ingredients.ts b/ts/attach_ingredients.ts index 2e93b9d..ed08fbb 100644 --- a/ts/attach_ingredients.ts +++ b/ts/attach_ingredients.ts @@ -34,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 { @@ -266,13 +267,17 @@ 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( @@ -424,28 +429,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; } } @@ -473,10 +475,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 @@ -489,18 +493,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); } } } @@ -639,6 +636,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 @@ -655,23 +656,17 @@ export async function attachIngredients(cfg: GenerationConfig): Promise 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 579b91d..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, @@ -20,7 +21,7 @@ const TEXTBOX_SELECTOR = /** 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-editor-side-panel, flow-comment-region-overlay, flow-comment-timeline-lane, [class*="comment-panel"], [class*="comments-panel"]'; + "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 = @@ -108,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. @@ -130,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 => { @@ -137,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 => @@ -167,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; @@ -236,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)), @@ -275,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; @@ -434,15 +422,14 @@ export async function closeSettingsAndMenus(): Promise { "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; } } @@ -452,11 +439,7 @@ export async function closeSettingsAndMenus(): Promise { 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) { @@ -477,12 +460,7 @@ export async function closeSettingsAndMenus(): Promise { 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); @@ -563,3 +541,14 @@ export function readComposerAlert(includePageAlerts: boolean): string | null { 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 9f32fc5..bb9f662 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -13,6 +13,7 @@ import { NOVEMBER_29_COLLECTION, NOVEMBER_29_CREATE, NOVEMBER_29_PREVIEW, + NOVEMBER_29_PROMPT_COMPOSER, NOVEMBER_29_SNAPSHOT, NOVEMBER_29_STORE, NOVEMBER_29_TRASH, @@ -739,38 +740,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. */ @@ -789,6 +771,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. */ @@ -904,6 +888,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", { @@ -913,12 +955,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ operations: { collection_write: { tileId: "Uc", tileChange: "df", moveTarget: "Sj", moveTiles: "Bb" }, asset_trash_store: { - entries: "Kv", - tile: "Oa", - trashed: "Ab", - date: "jc", - destination: "Dm", - sceneWorkflows: "qg", + entries: "Kv", tile: "Oa", trashed: "Ab", date: "jc", destination: "Dm", sceneWorkflows: "qg", }, character_bio: { tileId: "Uc", tileChange: "df", notes: "mx" }, }, @@ -960,6 +997,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], }, projectTitle: { saveEmitter: "HSa", stateSignal: "state" }, + promptComposer: NOVEMBER_20_PROMPT_COMPOSER, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -983,6 +1021,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ characterVoice: NOVEMBER_29_VOICE, characterCreate: NOVEMBER_29_CREATE, projectTitle: { saveEmitter: "cYa", stateSignal: "state" }, + promptComposer: NOVEMBER_29_PROMPT_COMPOSER, operations: { collection_write: NOVEMBER_29_COLLECTION, asset_trash_store: NOVEMBER_29_TRASH, @@ -1062,6 +1101,11 @@ export function projectTitleFormat(): ProjectTitleFormat { return frontendBuild(readBuildLabel())?.projectTitle ?? LEGACY_PROJECT_TITLE; } +/** Returns the prompt composer field mapping for the active build. */ +export function promptComposerFormat(): PromptComposerFormat { + return frontendBuild(readBuildLabel())?.promptComposer ?? LEGACY_PROMPT_COMPOSER; +} + /** Returns the uploaded-media flag and source symbol names of the active build. */ export function uploadMediaFields(): { uploaded: string; uploadSource: string } { const media = snapshotFormat()?.media; diff --git a/ts/frontend_nov29.ts b/ts/frontend_nov29.ts index 26ef030..536bf5e 100644 --- a/ts/frontend_nov29.ts +++ b/ts/frontend_nov29.ts @@ -12,6 +12,7 @@ import type { CollectionWriteFormat, VoiceConfirmationFormat, ProjectStoreFormat, + PromptComposerFormat, SnapshotFormat, } from "./frontend_builds"; @@ -107,3 +108,11 @@ export const NOVEMBER_29_VOICE_CONFIRMATION: VoiceConfirmationFormat = { editor: "Gv", entityQuery: "ma", savedVoice: "yrb", selectedVoice: "D6", previewSaved: "RM", pickerSelection: "yo", }; + +/** Prompt composer fields of build 20261129.06. */ +export const NOVEMBER_29_PROMPT_COMPOSER: PromptComposerFormat = { + promptState: "Oa", applyPrompt: "Ao", segments: "vf", promptEmpty: "ze", validator: "Ff", + validatorReason: "hdb", richEditor: "RL", editorView: "Ah", pmTransaction: "df", pmDispatch: "Nd", + submit: "submit", canSubmit: "NO", settingsOverlay: "DP", disabledReason: "XX", settingsSetCount: "zwa", + pagePromptHost: "qz", hostToggleAgent: "Qv", hostIsAgent: "Kn", hostManualBox: "Mo", +}; diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 5afae90..3781ee0 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,7 +8,6 @@ import { findRouter, navigateSpa, readOwn, - resolveLView, withLViewMapCapture, type NgContextCarrier, } from "./angular"; @@ -18,46 +17,50 @@ import { readComposerAlert, } from "./composer"; import { delay, elText, isVisibleEnabled } from "./dom"; -import { - collectSceneClipElements, - ensureSceneBuilderLViewMap, - readComponentInput, - sceneContents, - selectSceneClip, - verifySelectedSceneClipInBuilder, -} from "./scene_tiles"; +import { snapshotFormat } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; -/** Navigates to `/edit/` or `/scene/` and confirms edit composer readiness. */ +/** Returns true when `tile` carries a positive numeric duration on itself or its primary media. */ +function hasTileDuration(tile: unknown): boolean { + const mediaFmt = snapshotFormat()?.media; + const container = + (mediaFmt ? readOwn(tile, mediaFmt.container) : undefined) ?? + readOwn(tile, "Fb") ?? + readOwn(tile, "fb"); + const candidates = [ + readOwn(tile, "durationSeconds"), + readOwn(tile, "duration"), + mediaFmt ? readOwn(tile, mediaFmt.duration) : undefined, + readOwn(tile, "Lf"), + readOwn(container, "durationSeconds"), + readOwn(container, "duration"), + mediaFmt ? readOwn(container, mediaFmt.duration) : undefined, + readOwn(container, "Lf"), + ]; + return candidates.some((v) => typeof v === "number" && Number.isFinite(v) && v > 0); +} + +/** 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, - sceneId: string | null = null, ): Promise { const idStr = String(assetId || "").trim(); const primaryStr = String(primaryMediaId || "").trim(); const candidateIds = Array.from(new Set([idStr, primaryStr].filter(Boolean))); - let resolvedSceneId = sceneId ? String(sceneId).trim() || null : 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") { - const clipIds = sceneContents(directTile) - .clips.map((c) => String(c?.workflowId || "").trim()) - .filter(Boolean); - const hint = - clipIds.length > 0 - ? ` Available clip IDs: ${clipIds.slice(0, 6).join(", ")}.` - : ""; + if (rawType === "SCENE" && !hasTileDuration(directTile)) { return { opened: false, error: "unsupported_asset_kind", kind: "scene", - alert: `Cannot edit scene container '${idStr}' directly. Pass one of its video clip IDs to flow_edit.${hint}`, + alert: `Cannot edit scene '${idStr}' without a duration; pass a video asset ID to flow_edit.`, has_textbox: false, }; } @@ -84,131 +87,14 @@ export async function openEditAsset( has_textbox: false, }; } - } else { - for (const st of tileMap.values()) { - if (String(st?.type || "").toUpperCase() !== "SCENE") continue; - const stId = st.id != null ? String(st.id).trim() : ""; - if (resolvedSceneId && stId && stId !== resolvedSceneId) continue; - const { clips, history } = sceneContents(st); - const idx = clips.findIndex( - (c) => String(c?.workflowId || "").trim() === idStr, - ); - if (idx >= 0 || history.has(idStr)) { - if (!resolvedSceneId && stId) resolvedSceneId = stId; - break; - } - } } } const pm = /\/project\/([^/?#]+)/.exec(location.pathname || ""); const pid = pm ? pm[1] : runtimeState.store?.projectId || null; const router = pid ? findRouter() : null; - - if (resolvedSceneId && pid) { - const targetPath = `/scene/${resolvedSceneId}`; - let hasSceneBuilder = - (location.pathname || "").includes(targetPath) && - Boolean(document.querySelector("flow-scene-builder")); - if (!hasSceneBuilder && (location.pathname || "").includes(targetPath)) { - for (let i = 0; i < 30; i += 1) { - if (document.querySelector("flow-scene-builder")) { - hasSceneBuilder = true; - break; - } - await delay(100); - } - } - if (!hasSceneBuilder && router) { - await withLViewMapCapture(async () => { - await navigateSpa(router, ["/project", pid, "scene", resolvedSceneId]); - }); - for (let i = 0; i < 60; i += 1) { - if ( - (location.pathname || "").includes(targetPath) && - document.querySelector("flow-scene-builder") - ) { - hasSceneBuilder = true; - break; - } - await delay(100); - } - } - if (hasSceneBuilder) { - const sb = document.querySelector("flow-scene-builder") || document; - const selection = await selectSceneClip(sb, idStr, primaryStr); - if (!selection.ok) { - clearStore(); - return { - opened: false, - error: selection.error, - selection_error: selection.detail, - method: "spa_router", - view: "scene_builder", - scene_id: resolvedSceneId, - has_textbox: false, - }; - } - for (let i = 0; i < 25; i += 1) { - if (readComposerAlert(false) || findTextbox(true)) break; - await delay(100); - } - const postCheck = verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); - if (!postCheck.ok) { - clearStore(); - return { - opened: false, - error: postCheck.error, - selection_error: postCheck.detail, - method: "spa_router", - view: "scene_builder", - scene_id: resolvedSceneId, - has_textbox: false, - }; - } - clearStore(); - const hasTextbox = Boolean(findTextbox(true)); - const alert = readComposerAlert(!hasTextbox); - if (alert) { - return { - opened: false, - error: "edit_alert", - alert, - method: "spa_router", - view: "scene_builder", - scene_id: resolvedSceneId, - selected_clip_id: postCheck.selectedClipId, - has_textbox: false, - }; - } - return { - opened: hasTextbox, - error: hasTextbox ? undefined : "editor_textbox_not_found", - method: "spa_router", - view: "scene_builder", - scene_id: resolvedSceneId, - selected_clip_id: postCheck.selectedClipId, - has_textbox: hasTextbox, - }; - } - if (!(location.pathname || "").includes(targetPath)) { - return { - opened: false, - edit_url: buildProjectUrl(pid, ["scene", resolvedSceneId]), - scene_id: resolvedSceneId, - method: "route_fallback_needed", - }; - } - return { - opened: false, - error: "scene_builder_not_found", - scene_id: resolvedSceneId, - has_textbox: false, - method: "none", - }; - } - 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]]; @@ -243,87 +129,37 @@ export async function openEditAsset( if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } - let selectedClipId: string | undefined; - if (viewKind === "scene_builder") { - const sbEl = document.querySelector("flow-scene-builder"); - const sbNode: ParentNode = sbEl || document; - await ensureSceneBuilderLViewMap(sbNode); - let singleVideoMatch = false; - if (sbEl) { - const rawCtx = (sbEl as NgContextCarrier).__ngContext__; - const sbLv = - resolveLView(sbEl) ?? (Array.isArray(rawCtx) ? rawCtx : null); - const sbSlots: unknown[] = Array.isArray(sbLv) ? sbLv : [sbEl]; - for (const slot of sbSlots) { - if (!slot || typeof slot !== "object" || slot instanceof Node) { - continue; - } - const wfInput = readComponentInput(slot, "workflowId"); - if ( - wfInput.found && - typeof wfInput.value === "string" && - wfInput.value.trim() - ) { - const wfVal = wfInput.value.trim(); - if (wfVal !== candId && wfVal !== idStr && wfVal !== primaryStr) { - clearStore(); - return { - opened: false, - error: "scene_clip_selection_mismatch", - selection_error: `Video editor targets workflow '${wfVal}' instead of '${idStr || candId}'.`, - method: "spa_router", - view: viewKind, - has_textbox: false, - }; - } - singleVideoMatch = true; - selectedClipId = idStr || candId; - break; - } - } + if (viewKind === "scene_builder" && !findTextbox(true)) { + const sb = document.querySelector("flow-scene-builder") || document; + 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); } - const hasTimelineOrClips = - Boolean(sbNode.querySelector("flow-scene-timeline")) || - collectSceneClipElements(sbNode).length > 0; - if (!singleVideoMatch && (hasTimelineOrClips || !findTextbox(true))) { - const selection = await selectSceneClip( - sbNode, - idStr || candId, - primaryStr, - ); - if (!selection.ok) { - clearStore(); - return { - opened: false, - error: selection.error, - selection_error: selection.detail, - method: "spa_router", - view: viewKind, - has_textbox: false, - }; - } - selectedClipId = selection.selectedClipId; - for (let i = 0; i < 20; i += 1) { - if (readComposerAlert(false) || findTextbox(true)) break; - await delay(100); + if (!findTextbox(true)) { + const editTrigger = Array.from( + sb.querySelectorAll('button, [role="button"], [role="tab"]'), + ).find((b): b is HTMLElement => { + if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) 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); } - const postCheck = verifySelectedSceneClipInBuilder( - sbNode, - idStr || candId, - primaryStr, - ); - if (!postCheck.ok) { - clearStore(); - return { - opened: false, - error: postCheck.error, - selection_error: postCheck.detail, - method: "spa_router", - view: viewKind, - has_textbox: false, - }; - } - selectedClipId = postCheck.selectedClipId; + } + for (let i = 0; i < 20; i += 1) { + if (readComposerAlert(false) || findTextbox(true)) break; + await delay(100); } } @@ -337,7 +173,6 @@ export async function openEditAsset( alert, method: "spa_router", view: viewKind, - selected_clip_id: selectedClipId, has_textbox: false, }; } @@ -347,7 +182,6 @@ export async function openEditAsset( opened: true, method: "spa_router", view: viewKind, - selected_clip_id: selectedClipId, has_textbox: true, }; } @@ -444,43 +278,6 @@ export async function openEditAsset( if (readComposerAlert(false) || findTextbox(true)) break; await delay(100); } - let uiSelectedClipId: string | undefined; - const uiSb = document.querySelector("flow-scene-builder"); - if ( - uiSb && - (Boolean(uiSb.querySelector("flow-scene-timeline")) || - collectSceneClipElements(uiSb).length > 0) - ) { - const uiSelection = await selectSceneClip(uiSb, idStr, primaryStr); - if (!uiSelection.ok) { - clearStore(); - return { - opened: false, - error: uiSelection.error, - selection_error: uiSelection.detail, - method: "ui_edit", - view: "scene_builder", - has_textbox: false, - }; - } - const uiPostCheck = verifySelectedSceneClipInBuilder( - uiSb, - idStr, - primaryStr, - ); - if (!uiPostCheck.ok) { - clearStore(); - return { - opened: false, - error: uiPostCheck.error, - selection_error: uiPostCheck.detail, - method: "ui_edit", - view: "scene_builder", - has_textbox: false, - }; - } - uiSelectedClipId = uiPostCheck.selectedClipId; - } const hasTextbox = Boolean(findTextbox(true)); const alert = readComposerAlert(!hasTextbox); if (alert) { @@ -490,7 +287,6 @@ export async function openEditAsset( error: "edit_alert", alert, method: "ui_edit", - selected_clip_id: uiSelectedClipId, has_textbox: false, }; } @@ -499,7 +295,6 @@ export async function openEditAsset( return { opened: true, method: "ui_edit", - selected_clip_id: uiSelectedClipId, has_textbox: true, }; } diff --git a/ts/prompt_writer.ts b/ts/prompt_writer.ts index de026f2..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 && @@ -433,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, { kf: segments, Te: segments, Oe: 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 => { @@ -476,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) { @@ -489,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 { @@ -600,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/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 99fc50a..ff0c6fb 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -29,7 +29,6 @@ import type { SceneClipItem, SnapshotAssetItem, SnapshotCollectionItem, - SnapshotFailedVariant, StoreSnapshotResult, } from "./types"; @@ -39,56 +38,6 @@ const ACCOUNT_CREDITS_RE = /(?:^|[^\w,])(\d[\d,]*)\s+(?:Google\s+Flow|Flow|AI)\s /** Selector matching generation credit cost estimates that are not account balances. */ const COST_LABEL_SELECTOR = "flow-credit-cost-label, .credit-cost-label, .credit-cost-link"; -/** Collects failed or canceled variants from a history array without relying on sort order. */ -function collectFailedVariants( - history: unknown, - formatMediaError: (errVal: unknown) => string | null, -): SnapshotFailedVariant[] { - if (!Array.isArray(history) || history.length === 0) return []; - const out: SnapshotFailedVariant[] = []; - const seenIds = new Set(); - const anonCounts = new Map(); - for (const item of history) { - if (!item || typeof item !== "object") continue; - const norm = legacyMedia(item as FlowMediaPayload); - if (!norm) continue; - const status = String(norm.Zc ?? "").toLowerCase(); - const error = formatMediaError(norm.nf); - if (status !== "failed" && status !== "canceled" && error === null) { - continue; - } - const rawId = String(norm.id ?? norm.mediaId ?? "").trim(); - let key = rawId; - if (!key) { - const sig = `${status || "failed"}:${error ?? ""}`; - const occ = (anonCounts.get(sig) ?? 0) + 1; - anonCounts.set(sig, occ); - key = `anon#${occ}:${sig}`; - } - if (seenIds.has(key)) continue; - seenIds.add(key); - out.push({ id: key, status: status || "failed", error }); - } - return out; -} - -/** Appends failed variant entries from `extra` whose IDs are not already in `base`. */ -function mergeFailedVariants( - base: SnapshotFailedVariant[], - extra: SnapshotFailedVariant[], -): SnapshotFailedVariant[] { - if (extra.length === 0) return base; - const seen = new Set(base.map((v) => v.id)); - const merged = [...base]; - for (const item of extra) { - if (!seen.has(item.id)) { - seen.add(item.id); - merged.push(item); - } - } - return merged; -} - /** Locates an active Angular service instance matching `ServiceClass` in runtime state. */ function findCreditsServiceInstance( ServiceClass: abstract new (...args: never[]) => object, @@ -376,13 +325,13 @@ export function readStoreTiles(tileMap: Map): { readMediaUrl(t.fb, true) : null; - const primaryStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); - const primaryError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); + const mediaStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); + const mediaError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); const mediaNotReady = - primaryStatus === "pending" || - primaryStatus === "scheduled" || - primaryStatus === "failed" || - primaryStatus === "canceled" || + mediaStatus === "pending" || + mediaStatus === "scheduled" || + mediaStatus === "failed" || + mediaStatus === "canceled" || Boolean(t.Fb?.nf || t.fb?.nf || t.nf); const primaryMediaId = @@ -393,18 +342,6 @@ export function readStoreTiles(tileMap: Map): { t.fb?.mediaId || t.mediaId || null; - const primaryMediaIdStr = - primaryMediaId != null && String(primaryMediaId) !== "" - ? String(primaryMediaId) - : null; - const rawHistory = Array.isArray(rawTile.history) - ? rawTile.history - : Array.isArray(t.history) - ? t.history - : null; - const failedVariants = collectFailedVariants(rawHistory, formatMediaError); - const mediaStatus = primaryStatus || null; - const mediaError = primaryError; const cachedEntry = primaryMediaId ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) @@ -467,14 +404,12 @@ export function readStoreTiles(tileMap: Map): { : null, url: mediaUrl ? normalizeFlowMediaUrl(String(mediaUrl), kind, env) : null, collection_id: cid, - scene_id: null, - primary_media_id: primaryMediaIdStr, - failed_variants: failedVariants, + primary_media_id: primaryMediaId ? String(primaryMediaId) : null, personality_notes: bio == null ? null : String(bio), voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, trim_end_seconds: trimEnd, - media_status: mediaStatus, + media_status: mediaStatus || null, media_error: mediaError, width: typeof t.width === "number" @@ -517,71 +452,64 @@ export function readStoreTiles(tileMap: Map): { } for (const st of sceneTiles) { - const sceneId = - st.id != null && String(st.id) !== "" ? String(st.id) : null; const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); - const seenWfIds = new Set(); const candidates: Array< - [ - string, - SceneClipItem | null, - FlowMediaPayload | null, - FlowMediaPayload[] | undefined, - ] + [string, SceneClipItem | null, FlowMediaPayload | null] > = []; for (const clip of clips) { const wfId = clip?.workflowId ? String(clip.workflowId) : null; - if (!wfId || seenWfIds.has(wfId)) continue; - seenWfIds.add(wfId); + if (!wfId) continue; const hist = history.get(wfId); const primaryId = clip?.primaryMediaId ? String(clip.primaryMediaId) : null; const mObj = Array.isArray(hist) - ? (primaryId - ? hist.find((x) => x && String(x.id ?? x.mediaId ?? "") === primaryId) - : null) || + ? hist.find((x) => x && String(x.id || "") === primaryId) || hist[0] || null : null; - candidates.push([wfId, clip, mObj, hist]); + candidates.push([wfId, clip, mObj]); } for (const [wfId, hist] of history) { - if (!wfId || seenWfIds.has(wfId)) continue; - seenWfIds.add(wfId); - const mObj = (Array.isArray(hist) && hist[0]) || null; - candidates.push([wfId, null, mObj, hist]); + const mObj = Array.isArray(hist) ? hist[0] || null : null; + candidates.push([wfId, null, mObj]); } - for (const [wfId, clip, rawMedia, hist] of candidates) { + for (const [wfId, clip, rawMedia] of candidates) { if (!wfId) continue; const mObj = legacyMedia(rawMedia); const cObj = legacyMedia(clip as FlowMediaPayload | null); - const primaryClipStatus = String( + const mStatus = String( mObj?.Zc ?? cObj?.Zc ?? clip?.Zc ?? "", ).toLowerCase(); - const primaryClipError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); - const clipPrimaryMediaId = clip?.primaryMediaId - ? String(clip.primaryMediaId) - : mObj?.id - ? String(mObj.id) - : null; - const clipFailedVariants = collectFailedVariants(hist, formatMediaError); + const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); const existing = byId.get(wfId); if (existing) { - existing.failed_variants = mergeFailedVariants( - existing.failed_variants, - clipFailedVariants, - ); + if (mStatus === "failed" || mStatus === "canceled" || mError) { + if ( + existing.media_status !== "failed" && + existing.media_status !== "canceled" + ) { + existing.media_status = mStatus || existing.media_status; + } + if (!existing.media_error && mError) { + existing.media_error = mError; + } + } continue; } const mNotReady = - primaryClipStatus === "pending" || - primaryClipStatus === "scheduled" || - primaryClipStatus === "failed" || - primaryClipStatus === "canceled" || + mStatus === "pending" || + mStatus === "scheduled" || + mStatus === "failed" || + mStatus === "canceled" || Boolean(mObj?.nf || cObj?.nf || clip?.nf); + const clipPrimaryMediaId = clip?.primaryMediaId + ? String(clip.primaryMediaId) + : mObj?.id + ? String(mObj.id) + : null; const cachedClipVideoUrl = clipPrimaryMediaId ? asHttpOrDataUrl( runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, @@ -650,15 +578,13 @@ export function readStoreTiles(tileMap: Map): { prompt: clipPrompt, url: clipUrl ? normalizeFlowMediaUrl(String(clipUrl), "video", env) : null, collection_id: sceneCid, - scene_id: sceneId, primary_media_id: clipPrimaryMediaId, - failed_variants: clipFailedVariants, personality_notes: null, voice: null, trim_start_seconds: trimStartVal, trim_end_seconds: trimEndVal, - media_status: primaryClipStatus || null, - media_error: primaryClipError, + media_status: mStatus || null, + media_error: mError, width: typeof mObj?.width === "number" ? mObj.width diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index 3eb65e0..df2b2b4 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -1,80 +1,12 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Read clips and workflow history from the native scene tile, and select and verify timeline clips in `flow-scene-builder`. +// Read clips and workflow history from the native scene tile. -import { - isLiveLView, - readOwn, - resolveLView, - withLViewMapCapture, - type NgContextCarrier, -} from "./angular"; -import { - EDIT_PROMPT_BOX_SELECTOR, - findTextbox, - isVisibleOutsideNonComposer, - NON_COMPOSER_PANELS, - readComposerAlert, -} from "./composer"; -import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { readOwn } from "./angular"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; -import { runtimeState } from "./state"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; -/** Controls inside `flow-scene-builder` that are never timeline clip items. */ -const NON_CLIP_CONTROLS = `${NON_COMPOSER_PANELS}, ${EDIT_PROMPT_BOX_SELECTOR}, flow-playback-control, flow-extend-menu, flow-clip-context-menu, .add-clip-button-container, .add-clip-button, .timeline-controls, .zoom-controls, .cdk-overlay-pane, [role="menu"], [role="listbox"]`; - -/** Selectors that identify timeline clip elements inside `flow-scene-timeline`. */ -const CLIP_CONTAINER_SELECTOR = - ".timeline-contents > .clip, .clip, [data-workflow-id], [data-clip-id]"; - -/** Selectors that indicate an intentionally empty scene timeline track. */ -const EMPTY_TIMELINE_SELECTOR = ".empty-timeline-track, .is-empty"; - -/** Status values that indicate a timeline clip is still loading or generating. */ -const NOT_READY_CLIP_STATUS = /^(?:pending|scheduled|generating|loading|unloaded)$/i; - -/** Extracted identifiers and readiness flags for one timeline clip element. */ -interface SceneClipInspection { - /** Clip workflow identifiers read from component inputs, LViews, or attributes. */ - workflowIds: string[]; - /** Clip identifiers read from component inputs, LViews, or attributes. */ - clipIds: string[]; - /** Media identifiers read from component inputs, LViews, or attributes. */ - mediaIds: string[]; - /** Stripped identifiers from `PLACEHOLDER_` clip items. */ - placeholderIds: string[]; - /** True when the clip is actively loading, generating, splitting, or a placeholder. */ - notReady: boolean; - /** True when the element is a secondary `extend-composing` or `extend-failed-` pill. */ - isAuxiliaryItem: boolean; -} - -/** Timeline clip elements grouped by match, readiness, and UI readability state. */ -interface MatchedSceneClips { - /** All visible timeline clip elements in the timeline. */ - allClips: HTMLElement[]; - /** Selectable clip elements matching the requested ID. */ - readyMatches: HTMLElement[]; - /** Loading or placeholder clip elements matching the requested ID. */ - notReadyMatches: HTMLElement[]; - /** True when the scene has clips or a non-empty timeline, yet clip metadata cannot be read. */ - unreadable: boolean; - /** Cached inspection metadata per timeline clip element. */ - inspections: Map; -} - -/** Outcome of selecting and verifying a target clip in `flow-scene-builder`. */ -export type SceneClipSelectionResult = - | { ok: true; selectedClipId: string } - | { ok: false; error: string; detail: string }; - -/** Builds a failed scene clip selection result with error code and detail. */ -function selectionFailure(error: string, detail: string): SceneClipSelectionResult { - return { ok: false, error, detail }; -} - /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { const format = frontendBuild(readBuildLabel())?.projectStore.scene; @@ -88,702 +20,3 @@ export function sceneContents(tile: FlowTile) { history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), }; } - -/** Calls a zero-argument signal getter or returns a plain property value from `obj`. */ -function readSignalOrValue(obj: object, key: string): unknown { - const raw = readOwn(obj, key); - if (typeof raw === "function" && raw.length === 0) { - try { - return raw.call(obj); - } catch { - return undefined; - } - } - return raw; -} - -/** Resolves the instance property key for a declared Angular input name. */ -function resolveInputPropertyKey(inst: object, inputName: string): string | null { - if (inputName in inst) return inputName; - const ctor = (inst as { constructor?: unknown }).constructor; - if (typeof ctor !== "function") return null; - for (const staticKey of Object.getOwnPropertyNames(ctor)) { - let def: unknown; - try { - def = Reflect.get(ctor, staticKey); - } catch { - continue; - } - if (!def || typeof def !== "object" || readOwn(def, "type") !== ctor) continue; - const inputs = readOwn(def, "inputs"); - if (!inputs || typeof inputs !== "object") continue; - const mapping = readOwn(inputs, inputName); - if (typeof mapping === "string" && mapping) return mapping; - if (Array.isArray(mapping) && typeof mapping[0] === "string" && mapping[0]) { - return mapping[0]; - } - for (const [propKey, rawSpec] of Object.entries(inputs)) { - if (rawSpec === inputName) return propKey; - if (Array.isArray(rawSpec) && rawSpec[1] === inputName && propKey) return propKey; - } - } - return null; -} - -/** Reads a named Angular component input or signal property from `inst`. */ -export function readComponentInput( - inst: object, - inputName: string, -): { found: boolean; value: unknown } { - const propKey = resolveInputPropertyKey(inst, inputName); - if (!propKey) return { found: false, value: undefined }; - return { found: true, value: readSignalOrValue(inst, propKey) }; -} - -/** Collects unique non-Node object slots associated with `hosts` and live child LViews. */ -function collectHostSlots(hosts: Element[], scopeRoot?: ParentNode): object[] { - const hostSet = new Set(hosts); - const rawSlots: unknown[] = [...hosts]; - for (const host of hosts) { - const rawCtx = (host as NgContextCarrier).__ngContext__; - const lv = resolveLView(host) ?? (Array.isArray(rawCtx) ? rawCtx : null); - if (Array.isArray(lv)) rawSlots.push(...lv); - else if (rawCtx && typeof rawCtx === "object") rawSlots.push(rawCtx); - } - if (scopeRoot && runtimeState.ngLViewMap instanceof Map) { - for (const lv of runtimeState.ngLViewMap.values()) { - if ( - isLiveLView(lv) && - lv[0] instanceof Element && - !lv[0].closest(NON_COMPOSER_PANELS) && - (lv[0] === scopeRoot || scopeRoot.contains(lv[0])) - ) { - rawSlots.push(...lv); - } - } - } - const seen = new Set(); - const out: object[] = []; - for (const rawSlot of rawSlots) { - for (const slot of Array.isArray(rawSlot) ? rawSlot : [rawSlot]) { - if (!slot || typeof slot !== "object" || Array.isArray(slot)) continue; - if (slot instanceof Node && (!(slot instanceof Element) || !hostSet.has(slot))) continue; - if (seen.has(slot)) continue; - seen.add(slot); - out.push(slot); - } - } - return out; -} - -/** Reads the declared `clips` input array from `` when available. */ -function readTimelineClipsInput(timelineEl: Element | null): { - found: boolean; - items: unknown[]; -} { - if (!timelineEl) return { found: false, items: [] }; - for (const slot of collectHostSlots([timelineEl], timelineEl)) { - const res = readComponentInput(slot, "clips"); - if (res.found && Array.isArray(res.value)) { - return { found: true, items: res.value }; - } - } - return { found: false, items: [] }; -} - -/** Checks whether the active scene in the bound store has clips, is empty, or is unknown. */ -function sceneStoreClipState( - sb: ParentNode, - timelineEl: Element | null, -): "has_clips" | "empty" | "unknown" { - const tileMap = runtimeState.store?.getTileMap?.(); - if (!(tileMap instanceof Map)) return "unknown"; - let sceneId = /\/scene\/([^/?#]+)/.exec(location.pathname || "")?.[1] || ""; - if (!sceneId && timelineEl) { - for (const slot of collectHostSlots([timelineEl])) { - const inp = readComponentInput(slot, "sceneId"); - if (inp.found && typeof inp.value === "string" && inp.value.trim()) { - sceneId = inp.value.trim(); - break; - } - } - } - if (!sceneId && sb instanceof Element) { - sceneId = sb.getAttribute("data-scene-id") || ""; - } - const sceneTile = sceneId ? tileMap.get(sceneId) : undefined; - if (!sceneTile) return "unknown"; - return sceneContents(sceneTile).clips.length > 0 ? "has_clips" : "empty"; -} - -/** Appends a trimmed clip token, flagging `PLACEHOLDER_` and `extend-failed-` prefixes. */ -function recordClipToken( - raw: unknown, - target: string[], - info: SceneClipInspection, -): void { - if (typeof raw !== "string" && typeof raw !== "number") return; - const val = String(raw).trim(); - if (!val || /^flow-scene-timeline-area-\d+$/.test(val)) return; - if (val === "PLACEHOLDER_extend_clip") { - info.isAuxiliaryItem = true; - info.notReady = true; - return; - } - if (val.startsWith("PLACEHOLDER_")) { - const rest = val.slice("PLACEHOLDER_".length).trim(); - if (rest && !info.placeholderIds.includes(rest)) info.placeholderIds.push(rest); - info.notReady = true; - return; - } - if (val.startsWith("extend-failed-")) { - const rest = val.slice("extend-failed-".length).trim(); - if (rest && !info.clipIds.includes(rest)) info.clipIds.push(rest); - info.isAuxiliaryItem = true; - return; - } - if (!target.includes(val)) target.push(val); -} - -/** Returns true when `token` equals `expected` or has the timeline clip ID form `-`. */ -function matchesClipIdToken(token: string, expected: string): boolean { - const clean = token.trim(); - if (!clean || !expected) return false; - return ( - clean === expected || - (clean.startsWith(`${expected}-`) && /^\d+$/.test(clean.slice(expected.length + 1))) - ); -} - -/** Inspects a plain clip descriptor using non-minified property names. */ -function inspectClipObject(cand: unknown, info: SceneClipInspection): void { - if ( - !cand || - typeof cand !== "object" || - cand instanceof Node || - cand instanceof Error || - cand instanceof Map || - cand instanceof Set || - Array.isArray(cand) - ) { - return; - } - const rawType = String(readOwn(cand, "type") || "").trim(); - if (rawType.toUpperCase() === "SCENE") return; - const lowType = rawType.toLowerCase(); - if (lowType === "extend-composing") { - info.isAuxiliaryItem = true; - info.notReady = true; - } else if (NOT_READY_CLIP_STATUS.test(lowType)) { - info.notReady = true; - } - if (readOwn(cand, "isLoading") === true || readOwn(cand, "loaded") === false) { - info.notReady = true; - } - for (const statusKey of ["status", "state"]) { - const st = readOwn(cand, statusKey); - if (typeof st === "string" && NOT_READY_CLIP_STATUS.test(st.trim())) { - info.notReady = true; - } - } - recordClipToken(readOwn(cand, "workflowId"), info.workflowIds, info); - recordClipToken(readOwn(cand, "primaryMediaId"), info.mediaIds, info); - recordClipToken(readOwn(cand, "mediaId"), info.mediaIds, info); - recordClipToken(readOwn(cand, "clipId"), info.clipIds, info); - const hasClipShape = - "workflowId" in cand || - "primaryMediaId" in cand || - "mediaId" in cand || - "clipId" in cand || - "start" in cand || - "end" in cand || - (lowType !== "" && lowType !== "collection"); - if (hasClipShape) { - recordClipToken(readOwn(cand, "id"), info.clipIds, info); - } -} - -/** Extracts clip identifiers and readiness flags from one timeline clip element and optional `clips` input item. */ -function inspectSceneClipElement( - clipEl: HTMLElement, - timelineClipItem?: unknown, -): SceneClipInspection { - const info: SceneClipInspection = { - workflowIds: [], - clipIds: [], - mediaIds: [], - placeholderIds: [], - notReady: false, - isAuxiliaryItem: false, - }; - if (timelineClipItem !== undefined) inspectClipObject(timelineClipItem, info); - - const cls = clipEl.classList; - if (cls.contains("extend-composing")) { - info.isAuxiliaryItem = true; - info.notReady = true; - } - if ( - cls.contains("pending-placeholder") || - cls.contains("is-extend-generating") || - cls.contains("loading") || - cls.contains("is-loading") || - cls.contains("unloaded") || - clipEl.getAttribute("aria-busy") === "true" || - clipEl.getAttribute("aria-disabled") === "true" || - clipEl.hasAttribute("disabled") || - clipEl.getAttribute("data-loading") === "true" || - clipEl.getAttribute("data-loaded") === "false" || - NOT_READY_CLIP_STATUS.test( - (clipEl.getAttribute("data-status") || clipEl.getAttribute("data-state") || "").trim(), - ) - ) { - info.notReady = true; - } - if (clipEl.querySelector(".extend-failed-tile")) info.isAuxiliaryItem = true; - const busyChild = clipEl.querySelector( - '.processing-shimmer, .extend-loading-overlay, .split-pending-overlay, mat-progress-spinner, mat-spinner, [aria-busy="true"]', - ); - if (busyChild && (busyChild === clipEl || isVisibleOutsideNonComposer(busyChild))) { - info.notReady = true; - } - - const probeEls = [ - clipEl, - ...Array.from( - clipEl.querySelectorAll( - ".thumbnail-strip, [data-workflow-id], [data-clip-id], [data-media-id], [data-primary-media-id]", - ), - ).filter((el) => !el.closest(NON_CLIP_CONTROLS)), - ]; - for (const node of probeEls) { - recordClipToken(node.getAttribute("data-workflow-id"), info.workflowIds, info); - recordClipToken(node.getAttribute("data-media-id"), info.mediaIds, info); - recordClipToken(node.getAttribute("data-primary-media-id"), info.mediaIds, info); - recordClipToken(node.getAttribute("data-clip-id"), info.clipIds, info); - recordClipToken(node.getAttribute("id"), info.clipIds, info); - } - for (const slot of collectHostSlots(probeEls, clipEl)) { - if (slot instanceof Node) continue; - const stripClipId = readComponentInput(slot, "clipId"); - if (stripClipId.found) recordClipToken(stripClipId.value, info.clipIds, info); - inspectClipObject(slot, info); - for (const wrapKey of ["$implicit", "clip", "item", "data"]) { - const nested = readOwn(slot, wrapKey); - if (nested && typeof nested === "object") inspectClipObject(nested, info); - } - } - return info; -} - -/** Returns true when `info` exposes at least one clip, workflow, media, or placeholder identifier. */ -function hasAnyClipIdentifier(info: SceneClipInspection): boolean { - return ( - info.workflowIds.length > 0 || - info.clipIds.length > 0 || - info.mediaIds.length > 0 || - info.placeholderIds.length > 0 - ); -} - -/** Checks whether `info` matches `idStr` or `primaryStr` without workflow ID conflicts. */ -function clipIdentityMatches( - info: SceneClipInspection, - idStr: string, - primaryStr: string, -): { matches: boolean; exactAssetId: boolean } { - if (!idStr && !primaryStr) return { matches: false, exactAssetId: false }; - if (idStr && info.workflowIds.length > 0) { - const wfMatch = info.workflowIds.includes(idStr); - return { matches: wfMatch, exactAssetId: wfMatch }; - } - if ( - idStr && - (info.clipIds.some((t) => matchesClipIdToken(t, idStr)) || - info.mediaIds.some((t) => matchesClipIdToken(t, idStr)) || - info.placeholderIds.some((t) => matchesClipIdToken(t, idStr))) - ) { - return { matches: true, exactAssetId: true }; - } - if ( - primaryStr && - (info.mediaIds.some((t) => matchesClipIdToken(t, primaryStr)) || - info.clipIds.some((t) => matchesClipIdToken(t, primaryStr)) || - info.placeholderIds.some((t) => matchesClipIdToken(t, primaryStr))) - ) { - return { matches: true, exactAssetId: false }; - } - return { matches: false, exactAssetId: false }; -} - -/** Collects distinct visible timeline clip container elements inside `searchRoot`. */ -export function collectSceneClipElements(searchRoot: ParentNode): HTMLElement[] { - const candidates = Array.from( - searchRoot.querySelectorAll(CLIP_CONTAINER_SELECTOR), - ).filter((el) => isVisibleOutsideNonComposer(el) && !el.closest(NON_CLIP_CONTROLS)); - return candidates.filter( - (el) => !candidates.some((anc) => anc !== el && anc.contains(el)), - ); -} - -/** Matches timeline clip elements in `sb` against `idStr` and `primaryStr`. */ -function matchSceneClips(sb: ParentNode, idStr: string, primaryStr: string): MatchedSceneClips { - const timelineEl = sb.querySelector("flow-scene-timeline"); - const searchRoot = timelineEl || sb; - const allClips = collectSceneClipElements(searchRoot); - const timelineInput = readTimelineClipsInput(timelineEl); - const useIndexBinding = - timelineInput.found && timelineInput.items.length === allClips.length; - - const inspections = new Map(); - const exactReady: HTMLElement[] = []; - const primaryReady: HTMLElement[] = []; - const notReadyMatches: HTMLElement[] = []; - let anyReadableId = false; - - for (let idx = 0; idx < allClips.length; idx += 1) { - const clipEl = allClips[idx]; - const info = inspectSceneClipElement( - clipEl, - useIndexBinding ? timelineInput.items[idx] : undefined, - ); - inspections.set(clipEl, info); - if (hasAnyClipIdentifier(info)) anyReadableId = true; - const match = clipIdentityMatches(info, idStr, primaryStr); - if (!match.matches || info.isAuxiliaryItem) continue; - if (info.notReady) notReadyMatches.push(clipEl); - else if (match.exactAssetId) exactReady.push(clipEl); - else primaryReady.push(clipEl); - } - - let unreadable = false; - if (allClips.length === 0) { - const storeState = sceneStoreClipState(sb, timelineEl); - const explicitlyEmpty = - Boolean(searchRoot.querySelector(EMPTY_TIMELINE_SELECTOR)) || - (timelineEl?.classList.contains("is-empty") ?? false) || - (timelineInput.found && timelineInput.items.length === 0); - unreadable = - storeState === "has_clips" || - (timelineInput.found && timelineInput.items.length > 0) || - (storeState !== "empty" && !explicitlyEmpty); - } else if (!anyReadableId) { - unreadable = true; - } - - return { - allClips, - readyMatches: exactReady.length > 0 ? exactReady : primaryReady, - notReadyMatches, - unreadable, - inspections, - }; -} - -/** Returns true when a timeline clip container carries a positive DOM selection state. */ -function isClipElementSelectedInDom(el: HTMLElement): boolean { - if (el.getAttribute("aria-selected") === "false" || el.getAttribute("data-selected") === "false") { - return false; - } - if (el.querySelector(".unselected-mask")) return false; - return ( - el.classList.contains("selected") || - el.classList.contains("is-selected") || - el.classList.contains("active") || - el.getAttribute("aria-selected") === "true" || - el.getAttribute("aria-current") === "true" || - el.getAttribute("data-selected") === "true" || - el.hasAttribute("selected") - ); -} - -/** Verifies that `sb` selects `targetClip` and marks it ready for editing. */ -function verifySceneClipSelection( - sb: ParentNode, - targetClip: HTMLElement, - allClips: HTMLElement[], - inspections: Map, - idStr: string, - primaryStr: string, -): SceneClipSelectionResult { - const label = idStr || primaryStr; - if (!isVisibleOutsideNonComposer(targetClip)) { - return selectionFailure("scene_clip_not_selected", `Clip '${label}' is no longer visible in the scene timeline.`); - } - const targetInfo = inspections.get(targetClip) ?? inspectSceneClipElement(targetClip); - if (!clipIdentityMatches(targetInfo, idStr, primaryStr).matches) { - return selectionFailure("scene_clip_selection_mismatch", `Selected timeline element does not match clip '${label}'.`); - } - if (targetInfo.notReady) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); - } - if ( - targetClip.getAttribute("aria-selected") === "false" || - targetClip.getAttribute("data-selected") === "false" || - Boolean(targetClip.querySelector(".unselected-mask")) - ) { - return selectionFailure("scene_clip_not_selected", `Clip '${label}' is not selected in the scene timeline.`); - } - for (const other of allClips) { - if (other === targetClip || targetClip.contains(other) || other.contains(targetClip)) continue; - if (isClipElementSelectedInDom(other)) { - return selectionFailure("scene_clip_selection_mismatch", `Another timeline clip is selected instead of '${label}'.`); - } - } - - const domProvesSelected = isClipElementSelectedInDom(targetClip); - let componentProvesSelected = false; - const mediaSharedInTimeline = - Boolean(primaryStr) && - allClips.some((other) => { - if (other === targetClip) return false; - const otherInfo = inspections.get(other) ?? inspectSceneClipElement(other); - return ( - !otherInfo.isAuxiliaryItem && - (otherInfo.mediaIds.some((t) => matchesClipIdToken(t, primaryStr)) || - otherInfo.clipIds.some((t) => matchesClipIdToken(t, primaryStr))) - ); - }); - - const hostCandidates = [ - ...(sb instanceof Element ? [sb] : []), - ...Array.from( - sb.querySelectorAll(`flow-scene-timeline, ${EDIT_PROMPT_BOX_SELECTOR}, flow-base-prompt-box`), - ).filter((el) => !el.closest(NON_COMPOSER_PANELS)), - ]; - for (const slot of collectHostSlots(hostCandidates, sb)) { - const loadingInput = readComponentInput(slot, "isClipLoading"); - if (loadingInput.found && loadingInput.value === true) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the editor.`); - } - const disabledReason = readComponentInput(slot, "submitDisabledReason"); - if ( - disabledReason.found && - typeof disabledReason.value === "string" && - /finish loading/i.test(disabledReason.value) - ) { - return selectionFailure("scene_clip_not_loaded", disabledReason.value.trim()); - } - const placeholderInput = readComponentInput(slot, "placeholderText"); - if ( - placeholderInput.found && - typeof placeholderInput.value === "string" && - /select a clip to edit/i.test(placeholderInput.value) - ) { - return selectionFailure("scene_clip_not_selected", `Editor still prompts to select a clip instead of '${label}'.`); - } - - const selClip = readComponentInput(slot, "selectedClip"); - if (selClip.found) { - if (selClip.value === null || selClip.value === undefined) { - return selectionFailure("scene_clip_not_selected", `No clip is loaded in the edit composer for '${label}'.`); - } - if (typeof selClip.value === "object") { - const sc = selClip.value as object; - const scWf = String(readOwn(sc, "workflowId") || "").trim(); - const scId = String(readOwn(sc, "id") || readOwn(sc, "clipId") || "").trim(); - const scMedia = String(readOwn(sc, "primaryMediaId") || readOwn(sc, "mediaId") || "").trim(); - if (scId.startsWith("PLACEHOLDER_")) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the edit composer.`); - } - if (scWf && idStr && scWf !== idStr) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets workflow '${scWf}' instead of '${label}'.`); - } - if (scWf && idStr && scWf === idStr) componentProvesSelected = true; - for (const tok of [scMedia, scId].filter(Boolean)) { - const matchesKnown = - (Boolean(idStr) && matchesClipIdToken(tok, idStr)) || - (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr)) || - targetInfo.clipIds.some((c) => matchesClipIdToken(tok, c)) || - targetInfo.mediaIds.some((m) => matchesClipIdToken(tok, m)); - if ( - !matchesKnown && - (Boolean(primaryStr) || targetInfo.clipIds.length > 0 || targetInfo.mediaIds.length > 0) - ) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets clip '${tok}' instead of '${label}'.`); - } - if ( - matchesKnown && - !mediaSharedInTimeline && - ((Boolean(idStr) && matchesClipIdToken(tok, idStr)) || - (Boolean(primaryStr) && matchesClipIdToken(tok, primaryStr))) - ) { - componentProvesSelected = true; - } - } - } - } - - const selMedia = readComponentInput(slot, "selectedClipMediaId"); - if (selMedia.found) { - const sm = selMedia.value != null ? String(selMedia.value).trim() : ""; - if (!sm) { - return selectionFailure("scene_clip_not_selected", `Edit composer has no selected clip media ID for '${label}'.`); - } - const matchesMedia = - (Boolean(primaryStr) && sm === primaryStr) || - (Boolean(idStr) && sm === idStr) || - targetInfo.mediaIds.includes(sm); - if (!matchesMedia && (Boolean(primaryStr) || targetInfo.mediaIds.length > 0)) { - return selectionFailure("scene_clip_selection_mismatch", `Edit composer targets media '${sm}' instead of '${label}'.`); - } - if (!mediaSharedInTimeline && ((Boolean(primaryStr) && sm === primaryStr) || (Boolean(idStr) && sm === idStr))) { - componentProvesSelected = true; - } - } - } - - const tb = findTextbox(true); - if (tb) { - const ph = ( - tb.getAttribute("placeholder") || - tb.getAttribute("data-placeholder") || - tb.getAttribute("aria-placeholder") || - "" - ).trim(); - if (/select a clip to edit/i.test(ph)) { - return selectionFailure("scene_clip_not_selected", `Editor textbox still asks to select a clip instead of '${label}'.`); - } - } - - if (!domProvesSelected && !componentProvesSelected) { - return selectionFailure("scene_clip_selection_unverified", `Cannot verify selection of clip '${label}' in the scene timeline.`); - } - return { ok: true, selectedClipId: label }; -} - -/** Finds the unique matching clip in `sb` and verifies its active selection. */ -export function verifySelectedSceneClipInBuilder( - sb: ParentNode, - idStr: string, - primaryStr: string, -): SceneClipSelectionResult { - const label = idStr || primaryStr; - if (!label) { - return selectionFailure("scene_clip_id_required", "A clip ID is required to select a scene clip."); - } - const { allClips, readyMatches, notReadyMatches, unreadable, inspections } = - matchSceneClips(sb, idStr, primaryStr); - if (readyMatches.length === 0) { - if (notReadyMatches.length > 0) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); - } - if (unreadable) { - return selectionFailure("scene_timeline_unreadable", "Scene timeline clips could not be read from the current Flow UI."); - } - return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); - } - if (readyMatches.length > 1) { - return selectionFailure("scene_clip_ambiguous", `Multiple timeline clips match '${label}'.`); - } - return verifySceneClipSelection(sb, readyMatches[0], allClips, inspections, idStr, primaryStr); -} - -/** Captures Angular's LView registry map from `sb` when numeric `__ngContext__` slots are unresolved. */ -export async function ensureSceneBuilderLViewMap(sb: ParentNode): Promise { - const numericNodes = Array.from(sb.querySelectorAll("*")) - .slice(0, 60) - .filter((el) => typeof (el as NgContextCarrier).__ngContext__ === "number"); - if (numericNodes.length === 0) return; - if (runtimeState.ngLViewMap instanceof Map) { - const allResolved = numericNodes.every((el) => { - const idx = (el as NgContextCarrier).__ngContext__ as number; - const lv = runtimeState.ngLViewMap?.get(idx); - return isLiveLView(lv) && (!(lv[0] instanceof Node) || el === lv[0] || sb.contains(lv[0])); - }); - if (allResolved) return; - runtimeState.ngLViewMap = null; - } - await withLViewMapCapture(async () => { - const probes = Array.from( - sb.querySelectorAll("[mattooltip], [cdkoverlayorigin], button[aria-label], .clip"), - ) - .filter((el) => !el.closest(NON_COMPOSER_PANELS) && el.getClientRects().length > 0) - .slice(0, 8); - await hoverProbe(probes, 20); - }); -} - -/** Selects the matching clip ID in `flow-scene-builder`, opens clip edit mode, and proves selection. */ -export async function selectSceneClip( - sb: ParentNode, - idStr: string, - primaryStr: string, -): Promise { - const label = idStr || primaryStr; - if (!label) { - return selectionFailure("scene_clip_id_required", "A clip ID is required to select a scene clip."); - } - - await ensureSceneBuilderLViewMap(sb); - - let targetClip: HTMLElement | null = null; - let allClips: HTMLElement[] = []; - let inspections = new Map(); - let sawNotReadyMatch = false; - let sawAmbiguousMatch = false; - let sawUnreadable = false; - - for (let i = 0; i < 25; i += 1) { - await ensureSceneBuilderLViewMap(sb); - const matched = matchSceneClips(sb, idStr, primaryStr); - allClips = matched.allClips; - inspections = matched.inspections; - if (matched.readyMatches.length === 1) { - targetClip = matched.readyMatches[0]; - sawAmbiguousMatch = false; - break; - } - sawAmbiguousMatch = matched.readyMatches.length > 1; - sawNotReadyMatch = matched.notReadyMatches.length > 0; - sawUnreadable = matched.unreadable; - await delay(100); - } - - if (!targetClip) { - if (sawAmbiguousMatch) { - return selectionFailure("scene_clip_ambiguous", `Multiple timeline clips match '${label}'.`); - } - if (sawNotReadyMatch) { - return selectionFailure("scene_clip_not_loaded", `Clip '${label}' has not finished loading in the scene timeline.`); - } - if (sawUnreadable) { - return selectionFailure("scene_timeline_unreadable", "Scene timeline clips could not be read from the current Flow UI."); - } - return selectionFailure("scene_clip_not_found", `Clip '${label}' is not present in the scene timeline.`); - } - - let verified = verifySceneClipSelection(sb, targetClip, allClips, inspections, idStr, primaryStr); - if (!verified.ok) { - targetClip.scrollIntoView({ block: "nearest", inline: "center" }); - await withLViewMapCapture(async () => { - targetClip.click(); - await delay(150); - }); - for (let i = 0; i < 15; i += 1) { - verified = verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); - if (verified.ok) break; - await delay(100); - } - } - if (!verified.ok) return verified; - - if (readComposerAlert(false)) return verified; - - if (!findTextbox(true) || Boolean(document.querySelector(".is-extend-mode, .extend-composing"))) { - const editTrigger = Array.from( - sb.querySelectorAll('button, [role="button"], [role="tab"]'), - ).find((b): b is HTMLElement => { - if (!isVisibleEnabled(b) || b.closest(NON_COMPOSER_PANELS)) 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 /^(?:exit extend mode|edit(?:\s+(?:clip|video))?)$/i.test(lbl); - }); - if (editTrigger) { - editTrigger.click(); - await delay(300); - } - } - - return verifySelectedSceneClipInBuilder(sb, idStr, primaryStr); -} diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index cea8feb..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, @@ -16,8 +16,9 @@ import { 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 { @@ -218,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(); @@ -419,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") { @@ -444,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 5332790..d687746 100644 --- a/ts/submit_generation.ts +++ b/ts/submit_generation.ts @@ -8,8 +8,10 @@ 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"; @@ -17,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 { @@ -180,10 +170,7 @@ export async function submitGeneration(): Promise { 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 = disabledBtn; for (let depth = 0; depth < 6 && cur && !reason; depth += 1) { diff --git a/ts/types.ts b/ts/types.ts index 121a533..5a8c876 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -226,8 +226,6 @@ export interface FlowTile extends FlowMediaPayload { Eb?: FlowMediaPayload; /** Primary media container in build 20261120.00. */ Kb?: FlowMediaPayload; - /** Generated media variant history ordered from oldest to newest. */ - history?: FlowMediaPayload[]; /** Character preview fallback URL. */ ue?: string; /** Preview media identifier or fallback URL in build 20261120.00. */ @@ -300,33 +298,13 @@ export interface PromptTextSegment { content: string; } -/** Serialized prompt document accepted by `PromptStateController`. */ -export interface PromptDocumentPayload { - /** Prompt segments read by `PromptState.Gp` in build 20261120.00. */ - kf?: PromptTextSegment[]; - /** 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; @@ -341,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 = @@ -355,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 in build 20261129.06. */ 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 { @@ -413,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. */ @@ -440,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. */ @@ -454,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`. */ @@ -526,16 +454,6 @@ export interface DiscoverStoreResult { error?: string; } -/** Failed or canceled media variant entry recorded in asset history. */ -export interface SnapshotFailedVariant { - /** Variant media identifier or permutation-invariant fallback key. */ - id: string; - /** Lowercase failure status (`failed` or `canceled`). */ - status: string; - /** Extracted failure message when present. */ - error: string | null; -} - /** Asset entry normalized for `readStoreSnapshot`. */ export interface SnapshotAssetItem { /** Tile or clip workflow identifier. */ @@ -552,12 +470,8 @@ export interface SnapshotAssetItem { collection_id: string | null; /** Parent collection name. */ collection_name: string | null; - /** Parent scene identifier for scene-only clips. */ - scene_id: string | null; /** Primary media identifier. */ primary_media_id: string | null; - /** Failed or canceled variants recorded in tile or clip history. */ - failed_variants: SnapshotFailedVariant[]; /** Character personality notes. */ personality_notes: string | null; /** Assigned voice name or identifier. */ @@ -874,7 +788,6 @@ export interface FlowMcpRuntime { 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; 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