From aa864365acab66a08d5b312fd2b2f6d6068577b9 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 04:25:20 +0000 Subject: [PATCH] fix(flow): reconcile scene clips in store and timeline - Derive float scene aspect ratio and collection ID from clip 0 - Select target clip on flow-scene-timeline without video clicks - Reconcile active scene clips in place and keep store bound - Check scene and video IDs before mutations and confirm clips --- src/scenes.rs | 157 ++++++++++++---- ts/angular.ts | 113 ++++++++++- ts/project_store.ts | 8 +- ts/read_store_snapshot.ts | 146 +++++++++++---- ts/scene_ops.ts | 136 +++++++++++++- ts/video_ops.ts | 384 +++++++++++++++++++++++++++++++------- 6 files changed, 797 insertions(+), 147 deletions(-) diff --git a/src/scenes.rs b/src/scenes.rs index 4969fcc..d869fc0 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -137,6 +137,82 @@ fn clip_entered_error(asset: &FlowAsset, before: &HashMap) } } +/// Validates that each entry in `asset_ids` is non-empty and does not name a non-video asset or collection. +fn validate_video_asset_ids(snap: &Value, asset_ids: &[String]) -> Result> { + let collections = snap + .get("collections") + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]); + let assets = snap + .get("assets") + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]); + let mut cleaned = Vec::with_capacity(asset_ids.len()); + for raw_id in asset_ids { + let id = raw_id.trim(); + anyhow::ensure!(!id.is_empty(), "Video asset ID must not be empty"); + if collections + .iter() + .any(|c| c.get("id").and_then(Value::as_str) == Some(id)) + { + anyhow::bail!("Asset '{id}' is a collection, expected a video asset"); + } + if let Some(found) = assets + .iter() + .find(|a| a.get("id").and_then(Value::as_str) == Some(id)) + { + let kind = found + .get("kind") + .and_then(Value::as_str) + .unwrap_or("unknown"); + anyhow::ensure!( + kind == "video", + "Asset '{id}' has kind '{kind}', expected 'video'" + ); + } + cleaned.push(id.to_string()); + } + Ok(cleaned) +} + +/// Validates that `scene_id` names a live scene in `snap`. +fn validate_scene_target_id(snap: &Value, raw_scene_id: &str) -> Result { + let scene_id = raw_scene_id.trim(); + anyhow::ensure!(!scene_id.is_empty(), "Scene ID must not be empty"); + if snap + .get("collections") + .and_then(Value::as_array) + .is_some_and(|cols| { + cols.iter() + .any(|c| c.get("id").and_then(Value::as_str) == Some(scene_id)) + }) + { + anyhow::bail!("Target '{scene_id}' is a collection, expected a scene"); + } + let Some(found) = snap + .get("assets") + .and_then(Value::as_array) + .and_then(|assets| { + assets + .iter() + .find(|a| a.get("id").and_then(Value::as_str) == Some(scene_id)) + }) + else { + anyhow::bail!("Scene '{scene_id}' does not exist in the active project"); + }; + let kind = found + .get("kind") + .and_then(Value::as_str) + .unwrap_or("unknown"); + anyhow::ensure!( + kind == "scene", + "Target '{scene_id}' has kind '{kind}', expected 'scene'" + ); + Ok(scene_id.to_string()) +} + /// Parameters for `flow_scenes`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct ScenesParams { @@ -190,31 +266,36 @@ pub(crate) async fn handle_scenes( Ok(json!({ "count": scenes.len(), "scenes": scenes })) } "create" => { - let asset_ids = req.asset_ids.unwrap_or_default(); - let _ = read_snapshot(engine).await?; + let raw_asset_ids = req.asset_ids.unwrap_or_default(); + let snap = read_snapshot(engine).await?; + let asset_ids = validate_video_asset_ids(&snap, &raw_asset_ids)?; let payload = json!({ "action": "create", "asset_ids": asset_ids, "name": req.name, }); let res = engine.call_flow_async("sceneOp", json!([payload])).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + if res.get("ok").and_then(Value::as_bool) != Some(true) + || res.get("confirmed").and_then(Value::as_bool) != Some(true) + { anyhow::bail!( "Failed to create scene: {}", res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") + .and_then(Value::as_str) + .unwrap_or("scene clips not confirmed") ); } Ok(res) } "add_clips" => { - let scene_id = req.id.context("flow_scenes add_clips requires 'id'")?; - let asset_ids = req + let raw_scene_id = req.id.context("flow_scenes add_clips requires 'id'")?; + let raw_asset_ids = req .asset_ids .filter(|v| !v.is_empty()) .context("flow_scenes add_clips requires non-empty 'asset_ids'")?; - let _ = read_snapshot(engine).await?; + let snap = read_snapshot(engine).await?; + let scene_id = validate_scene_target_id(&snap, &raw_scene_id)?; + let asset_ids = validate_video_asset_ids(&snap, &raw_asset_ids)?; let payload = json!({ "action": "add_clips", "scene_id": scene_id, @@ -222,12 +303,14 @@ pub(crate) async fn handle_scenes( "position": req.position, }); let res = engine.call_flow_async("sceneOp", json!([payload])).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + if res.get("ok").and_then(Value::as_bool) != Some(true) + || res.get("confirmed").and_then(Value::as_bool) != Some(true) + { anyhow::bail!( "Failed to add clips to scene: {}", res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") + .and_then(Value::as_str) + .unwrap_or("scene clips not confirmed") ); } Ok(res) @@ -320,7 +403,7 @@ pub(crate) async fn run_video_extend( if let Some(nav_url) = res.get("need_navigate").and_then(|v| v.as_str()) { engine.navigate(nav_url).await?; tokio::time::sleep(Duration::from_millis(1200)).await; - let _ = ensure_flow_store(engine).await; + let _ = read_snapshot(engine).await; let retry_payload = json!({ "action": "prepare_extend", "asset_id": target.id, @@ -379,7 +462,14 @@ pub(crate) async fn run_video_extend( on_progress("extending video...".to_string()); } - if let Ok(cur_snap) = list_assets_with_project(engine).await { + let cur_snap = match list_assets_with_project(engine).await { + Ok(snap_ok) => Some(snap_ok), + Err(_) => { + let _ = ensure_flow_store(engine).await; + list_assets_with_project(engine).await.ok() + } + }; + if let Some(cur_snap) = cur_snap { for asset in &cur_snap.assets { if asset.kind == "video" && !clip_is_failed(asset) @@ -406,26 +496,27 @@ pub(crate) async fn run_video_extend( )); break; } - if !extending { - let fresh: Vec = cur_snap - .assets - .iter() - .filter(|a| { - a.kind == "video" - && a.url.is_some() - && before.get(&a.id).is_none_or(|prior| { - a.primary_media_id.as_deref().map_or_else( - || a.url != prior.url, - |media_id| prior.primary_media_id.as_deref() != Some(media_id), - ) - }) - }) - .cloned() - .collect(); - if !fresh.is_empty() { - new_assets = fresh; - break; - } + let fresh: Vec = cur_snap + .assets + .iter() + .filter(|a| { + a.kind == "video" + && !clip_is_failed(a) + && !matches!(a.media_status.as_deref(), Some("pending" | "scheduled")) + && a.url.is_some() + && (!extending || a.media_status.as_deref() == Some("success")) + && before.get(&a.id).is_none_or(|prior| { + a.primary_media_id.as_deref().map_or_else( + || !extending && a.url != prior.url, + |media_id| prior.primary_media_id.as_deref() != Some(media_id), + ) + }) + }) + .cloned() + .collect(); + if !fresh.is_empty() { + new_assets = fresh; + break; } } if Instant::now() >= deadline { diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..d409c1d 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -5,13 +5,17 @@ import { characterLookMedia, + collectionIdOf, delay, elText, fifeBase, + isTrashedTile, + legacyTile, normalizeFlowMediaUrl, + parentCollectionId, readMediaUrl, } from "./dom"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { frontendBuild, readBuildLabel, snapshotFormat } from "./frontend_builds"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -431,13 +435,112 @@ function sceneIds(tiles: Map | null | undefined): string[] { tile.type === "SCENE" && !tile.isPending ? [String(tile.id ?? id)] : []); } +/** Finds and normalizes the first clip tile that `workflowIds` names in `tiles`. */ +function findFirstClipTile( + tiles: Map | null | undefined, + workflowIds: string[], +): FlowTile | null { + const firstId = workflowIds[0]?.trim(); + if (!firstId || !(tiles instanceof Map)) return null; + const direct = tiles.get(firstId); + if (direct && !isTrashedTile(direct)) { + return legacyTile(direct) ?? null; + } + for (const tile of tiles.values()) { + if (!tile || isTrashedTile(tile)) continue; + if (String(tile.id ?? "") === firstId || String(tile.workflowId ?? "") === firstId) { + return legacyTile(tile) ?? null; + } + } + return null; +} + +/** Derives a float width-to-height aspect ratio (`0.5625` for `9:16`, `16/9` for `16:9` or empty scenes). */ +function deriveSceneAspectRatio(firstTile: FlowTile | null): number { + if (!firstTile) return 16 / 9; + const candidates = [ + firstTile.Kb?.aspectRatio, + firstTile.Fb?.aspectRatio, + firstTile.aspectRatio, + ]; + let ratio = candidates.find( + (v): v is number => typeof v === "number" && Number.isFinite(v) && v > 0, + ); + if (ratio === undefined) { + const width = + firstTile.Fb?.tc?.width ?? + firstTile.tc?.width ?? + firstTile.Fb?.width ?? + firstTile.width; + const height = + firstTile.Fb?.tc?.height ?? + firstTile.tc?.height ?? + firstTile.Fb?.height ?? + firstTile.height; + if ( + typeof width === "number" && + Number.isFinite(width) && + width > 0 && + typeof height === "number" && + Number.isFinite(height) && + height > 0 + ) { + ratio = width / height; + } + } + return ratio !== undefined && ratio < 1 ? 0.5625 : 16 / 9; +} + +/** Derives the parent collection ID for a new scene from clip `0` or the active `/collection/` route. */ +function deriveSceneCollectionId( + tiles: Map | null | undefined, + firstTile: FlowTile | null, +): string | undefined { + const collectionType = snapshotFormat()?.tileTypes.collection ?? "COLLECTION"; + const collectionIds = new Set(); + if (tiles instanceof Map) { + for (const [id, rawTile] of tiles.entries()) { + if ( + rawTile && + !isTrashedTile(rawTile) && + String(rawTile.type ?? "").toUpperCase() === collectionType + ) { + collectionIds.add(String(rawTile.id ?? id)); + } + } + } + const isCollectionId = (id: string): boolean => collectionIds.has(id); + const fromTile = collectionIdOf(firstTile, isCollectionId); + if (fromTile) return fromTile; + const directParent = firstTile ? parentCollectionId(firstTile) : null; + if (directParent && (!(tiles instanceof Map) || !tiles.has(directParent) || collectionIds.has(directParent))) { + return directParent; + } + const routeMatch = /\/project\/[^/?#]+\/collection\/([^/?#]+)/.exec(location.pathname || ""); + if (routeMatch?.[1]) { + try { + const routeCid = decodeURIComponent(routeMatch[1]).trim(); + if (routeCid && (!(tiles instanceof Map) || !tiles.has(routeCid) || collectionIds.has(routeCid))) { + return routeCid; + } + } catch { + // Ignore malformed URI components in location.pathname. + } + } + return undefined; +} + /** Creates a scene and waits for its ID from Flow. */ export async function createScene( helper: FlowStoreHandle, getMap: () => Map | null | undefined, workflowIds: string[], ): Promise<{ ok: boolean; id?: string; error?: string }> { - const before = new Set(sceneIds(getMap())); + const initialMap = getMap(); + const before = new Set(sceneIds(initialMap)); + const firstClip = findFirstClipTile(initialMap, workflowIds); + const aspectRatio = deriveSceneAspectRatio(firstClip); + const collectionId = deriveSceneCollectionId(initialMap, firstClip); const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa"; let confirmedId: string | undefined; let failure: string | undefined; @@ -451,9 +554,9 @@ export async function createScene( void Promise.resolve().then(() => helper.mutate({ type: "create_scene", rg: workflowIds, - Fc: undefined, - wc: undefined, - aspectRatio: 1, + Fc: collectionId, + wc: collectionId, + aspectRatio, De: completion, ve: completion, })).then((response) => { diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..e754e3e 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -342,10 +342,16 @@ export function findProjectStoreInView( for (const slot of view) { consider(slot); - if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot) || slot instanceof Map) { + continue; + } for (const key of format.componentSlots) { consider(Object.getOwnPropertyDescriptor(slot, key)?.value); } + const ownKeys = Object.getOwnPropertyNames(slot); + for (let i = 0; i < ownKeys.length && i < 48; i += 1) { + consider(Object.getOwnPropertyDescriptor(slot, ownKeys[i])?.value); + } } return matches; } diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..6106a1f 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -200,10 +200,11 @@ export function readStoreSnapshot(): StoreSnapshotResult { clearStore(); return { ok: false, error: "project_mismatch" }; } - if (!helper.isCurrent() || runtimeState.routePath !== location.pathname) { + if (!helper.isCurrent()) { clearStore(); return { ok: false, error: "route_changed" }; } + runtimeState.routePath = location.pathname; if (!helper.isReady()) { return { ok: false, error: "store_loading" }; } @@ -237,6 +238,10 @@ export function readStoreTiles(tileMap: Map): { const cols = new Map(); const counts = new Map(); const byId = new Map>(); + const videoByWorkflowId = new Map>(); + const initialPrimaryMediaIds = new WeakMap(); + const reconciledRank = new WeakMap(); + const activeRouteSceneId = /\/scene\/([^/?#]+)/.exec(location.pathname || "")?.[1] ?? null; const sceneTiles: FlowTile[] = []; const rawList: Omit[] = []; const env = getFifeEnv(); @@ -455,29 +460,42 @@ export function readStoreTiles(tileMap: Map): { }; rawList.push(topEntry); byId.set(tid, topEntry); + if (ttype === "VIDEO") { + initialPrimaryMediaIds.set(topEntry, topEntry.primary_media_id); + videoByWorkflowId.set(tid, topEntry); + if (t.workflowId) { + videoByWorkflowId.set(String(t.workflowId), topEntry); + } + } } for (const st of sceneTiles) { const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); + const activeWfIds = new Set(); const candidates: Array< [string, SceneClipItem | null, FlowMediaPayload | null] > = []; for (const clip of clips) { - const wfId = clip?.workflowId ? String(clip.workflowId) : null; + if (!clip) continue; + const wfId = clip.workflowId ? String(clip.workflowId) : null; if (!wfId) continue; + activeWfIds.add(wfId); const hist = history.get(wfId); - const primaryId = clip?.primaryMediaId + const primaryId = clip.primaryMediaId ? String(clip.primaryMediaId) : null; const mObj = Array.isArray(hist) - ? hist.find((x) => x && String(x.id || "") === primaryId) || - hist[0] || - null + ? primaryId + ? hist.find( + (x) => x && String(x.id ?? x.mediaId ?? "") === primaryId, + ) || null + : hist[0] || null : null; candidates.push([wfId, clip, mObj]); } for (const [wfId, hist] of history) { + if (activeWfIds.has(wfId)) continue; const mObj = Array.isArray(hist) ? hist[0] || null : null; candidates.push([wfId, null, mObj]); } @@ -490,21 +508,6 @@ export function readStoreTiles(tileMap: Map): { mObj?.Zc ?? cObj?.Zc ?? clip?.Zc ?? "", ).toLowerCase(); const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); - const existing = byId.get(wfId); - if (existing) { - 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 = mStatus === "pending" || mStatus === "scheduled" || @@ -533,6 +536,9 @@ export function readStoreTiles(tileMap: Map): { ? cachedClipVideoUrl : tileClipUrl || cachedClipVideoUrl || null; const clipUrl = mNotReady ? null : rawClipUrl; + const normalizedClipUrl = clipUrl + ? normalizeFlowMediaUrl(String(clipUrl), "video", env) + : null; const trimStartVal = typeof clip?.Ji === "number" ? clip.Ji : typeof mObj?.Jc === "number" ? mObj.Jc : @@ -569,6 +575,88 @@ export function readStoreTiles(tileMap: Map): { : mObj?.inputs?.prompt ? String(mObj.inputs.prompt) : null; + const widthVal = + typeof mObj?.width === "number" + ? mObj.width + : typeof mObj?.tc?.width === "number" + ? mObj.tc.width + : null; + const heightVal = + typeof mObj?.height === "number" + ? mObj.height + : typeof mObj?.tc?.height === "number" + ? mObj.tc.height + : null; + + const existing = byId.get(wfId) ?? videoByWorkflowId.get(wfId); + if (existing) { + if (clip !== null && existing.kind === "video") { + const initialPrimary = initialPrimaryMediaIds.get(existing); + const isActiveScene = Boolean( + activeRouteSceneId && String(st.id ?? "") === activeRouteSceneId, + ); + const histList = history.get(wfId); + const histIdx = + Array.isArray(histList) && clipPrimaryMediaId + ? histList.findIndex( + (x) => x && String(x.id ?? x.mediaId ?? "") === clipPrimaryMediaId, + ) + : -1; + const candidateRank = isActiveScene + ? 1_000_000 + : mStatus === "pending" || + mStatus === "scheduled" || + mStatus === "failed" || + mStatus === "canceled" || + Boolean(mError) + ? 100_000 + Math.max(0, histIdx) + : clipPrimaryMediaId && clipPrimaryMediaId !== initialPrimary + ? 1_000 + Math.max(0, histIdx) + : Math.max(0, histIdx); + const prevRank = reconciledRank.get(existing) ?? 0; + if (candidateRank >= prevRank) { + reconciledRank.set(existing, candidateRank); + const mediaChanged = Boolean( + clipPrimaryMediaId && clipPrimaryMediaId !== existing.primary_media_id, + ); + if (clipPrimaryMediaId) { + existing.primary_media_id = clipPrimaryMediaId; + } + if (mStatus === "pending" || mStatus === "scheduled") { + existing.media_status = mStatus; + existing.media_error = null; + existing.url = null; + } else if (mStatus === "failed" || mStatus === "canceled" || mError) { + existing.media_status = mStatus || existing.media_status; + if (mError) { + existing.media_error = mError; + } + if (mediaChanged) { + existing.url = null; + } + } else { + if (mStatus) { + existing.media_status = mStatus; + } + if (mediaChanged) { + existing.media_error = null; + } + if (normalizedClipUrl) { + existing.url = normalizedClipUrl; + } else if (mediaChanged) { + existing.url = null; + } + } + if (durVal !== null) existing.duration = durVal; + if (widthVal !== null) existing.width = widthVal; + if (heightVal !== null) existing.height = heightVal; + if (clipPrompt) existing.prompt = clipPrompt; + } + byId.set(wfId, existing); + } + continue; + } + const clipCreated = mObj?.hc instanceof Date ? mObj.hc.toISOString() @@ -584,7 +672,7 @@ export function readStoreTiles(tileMap: Map): { name: String((mObj as FlowTile | null)?.displayName || st.displayName || ""), kind: "video", prompt: clipPrompt, - url: clipUrl ? normalizeFlowMediaUrl(String(clipUrl), "video", env) : null, + url: normalizedClipUrl, collection_id: sceneCid, primary_media_id: clipPrimaryMediaId, personality_notes: null, @@ -593,18 +681,8 @@ export function readStoreTiles(tileMap: Map): { trim_end_seconds: trimEndVal, media_status: mStatus || null, media_error: mError, - width: - typeof mObj?.width === "number" - ? mObj.width - : typeof mObj?.tc?.width === "number" - ? mObj.tc.width - : null, - height: - typeof mObj?.height === "number" - ? mObj.height - : typeof mObj?.tc?.height === "number" - ? mObj.tc.height - : null, + width: widthVal, + height: heightVal, duration: durVal, created_at: clipCreated, }; diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index fc47fbb..9e07f96 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -4,11 +4,104 @@ // Create Google Flow scenes and append workflow clips via bound store state. import { createScene } from "./angular"; -import { delay } from "./dom"; +import { delay, isTrashedTile } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; +import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, SceneOpRequest } from "./types"; +/** Maximum time in milliseconds to confirm clip workflows in `sceneContents(tile).clips`. */ +const SCENE_CLIP_CONFIRM_MS = 6_000; + +/** Returns true when `id` names an active clip workflow inside any live `SCENE` tile. */ +function isActiveSceneClipWorkflow(tileMap: Map, id: string): boolean { + for (const tile of tileMap.values()) { + if (!tile || isTrashedTile(tile) || tile.isPending) continue; + if (String(tile.type ?? "").toUpperCase() !== "SCENE") continue; + const { clips } = sceneContents(tile); + if (clips.some((clip) => clip !== null && String(clip?.workflowId ?? "") === id)) { + return true; + } + } + return false; +} + +/** Finds a tile in `tileMap` by direct key, `tile.id`, or `tile.workflowId`. */ +function findTileByIdOrWorkflow( + tileMap: Map, + id: string, +): FlowTile | undefined { + const direct = tileMap.get(id); + if (direct) return direct; + for (const tile of tileMap.values()) { + if (String(tile?.id ?? "") === id || String(tile?.workflowId ?? "") === id) { + return tile; + } + } + return undefined; +} + +/** Checks that each entry in `rawIds` names a live `VIDEO` workflow and returns the workflow IDs. */ +function resolveVideoWorkflowIds( + tileMap: Map, + rawIds: string[], +): { ok: true; workflowIds: string[] } | { ok: false; error: string } { + const workflowIds: string[] = []; + for (const rawId of rawIds) { + const id = String(rawId ?? "").trim(); + if (!id) { + return { ok: false, error: "empty_video_asset_id" }; + } + const tile = findTileByIdOrWorkflow(tileMap, id); + if (tile) { + if (isTrashedTile(tile) || tile.isPending) { + return { ok: false, error: `video_asset_unavailable:${id}` }; + } + const tileType = String(tile.type ?? "").toUpperCase(); + if (tileType !== "VIDEO") { + return { ok: false, error: `non_video_asset:${id}:${tileType || "UNKNOWN"}` }; + } + workflowIds.push(String(tile.workflowId || tile.id || id)); + continue; + } + if (isActiveSceneClipWorkflow(tileMap, id)) { + workflowIds.push(id); + continue; + } + return { ok: false, error: `video_asset_not_found:${id}` }; + } + return { ok: true, workflowIds }; +} + +/** Polls `sceneContents(tile).clips` in `getMap()` for up to 6 seconds until all `workflowIds` appear. */ +async function confirmSceneClips( + getMap: () => Map | null | undefined, + sceneId: string, + workflowIds: string[], +): Promise<{ ok: true; clipsCount: number } | { ok: false }> { + const deadline = performance.now() + SCENE_CLIP_CONFIRM_MS; + while (performance.now() < deadline) { + const sceneTile = getMap()?.get(sceneId); + if ( + sceneTile && + !isTrashedTile(sceneTile) && + !sceneTile.isPending && + String(sceneTile.type ?? "").toUpperCase() === "SCENE" + ) { + const { clips } = sceneContents(sceneTile); + const activeClips = clips.filter((clip) => clip !== null); + const present = new Set( + activeClips.flatMap((clip) => (clip?.workflowId ? [String(clip.workflowId)] : [])), + ); + if (workflowIds.every((wfId) => present.has(wfId))) { + return { ok: true, clipsCount: activeClips.length }; + } + } + await delay(150); + } + return { ok: false }; +} + /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { if (!activeProjectStoreFormat()) { @@ -30,17 +123,23 @@ export async function sceneOp(req: SceneOpRequest): Promise { } const action = String(req?.action || "").toLowerCase(); - const resolveWfIds = (ids: string[]): string[] => - ids.map((id) => String(getMap()?.get(id)?.workflowId || id)); if (action === "create") { const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map(String) : []; - const created = await createScene(helper, getMap, resolveWfIds(assetIds)); + const resolved = resolveVideoWorkflowIds(tileMap, assetIds); + if (!resolved.ok) { + return resolved; + } + const created = await createScene(helper, getMap, resolved.workflowIds); if (!created?.ok || !created.id) { return created || { ok: false, error: "created_scene_id_not_found" }; } + const confirmed = await confirmSceneClips(getMap, created.id, resolved.workflowIds); + if (!confirmed.ok) { + return { ok: false, error: "scene_clips_not_confirmed", id: created.id }; + } if (req?.name && helper.rename) { try { await helper.rename(created.id, String(req.name)); @@ -54,8 +153,10 @@ export async function sceneOp(req: SceneOpRequest): Promise { } return { ok: true, + confirmed: true, id: created.id, name: req?.name ? String(req.name) : null, + clips_count: confirmed.clipsCount, }; } @@ -67,6 +168,19 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } + const sceneTile = tileMap.get(sceneId); + if (!sceneTile || isTrashedTile(sceneTile) || sceneTile.isPending) { + return { ok: false, error: `scene_not_found:${sceneId}` }; + } + const sceneType = String(sceneTile.type ?? "").toUpperCase(); + if (sceneType !== "SCENE") { + return { ok: false, error: `non_scene_target:${sceneId}:${sceneType || "UNKNOWN"}` }; + } + const resolved = resolveVideoWorkflowIds(tileMap, assetIds); + if (!resolved.ok) { + return resolved; + } + const { workflowIds } = resolved; let callbackErr: unknown = null; const completion = { resolve: () => {}, @@ -74,7 +188,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { callbackErr ??= err; }, }; - const workflowIds = resolveWfIds(assetIds); try { await helper.mutate({ type: "add_workflows_to_scene", @@ -100,8 +213,17 @@ export async function sceneOp(req: SceneOpRequest): Promise { error: callbackErr instanceof Error ? callbackErr.message : String(callbackErr), }; } - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; + const confirmed = await confirmSceneClips(getMap, sceneId, workflowIds); + if (!confirmed.ok) { + return { ok: false, error: "scene_clips_not_confirmed", scene_id: sceneId }; + } + return { + ok: true, + confirmed: true, + scene_id: sceneId, + added: workflowIds.length, + clips_count: confirmed.clipsCount, + }; } return { ok: false, error: `unknown_scene_action:${action}` }; diff --git a/ts/video_ops.ts b/ts/video_ops.ts index 0cc0e8c..cbed9bc 100644 --- a/ts/video_ops.ts +++ b/ts/video_ops.ts @@ -3,13 +3,169 @@ // Trim Flow videos and drive the scene builder extend workflow. -import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, withLViewMapCapture } from "./angular"; +import { + buildProjectUrl, + createScene, + findRouter, + navigateSpa, + pickerAssetMatches, + readAngularTooltip, + readOwn, + resolveLView, + withLViewMapCapture, +} from "./angular"; +import type { PickerMatchTarget } from "./angular"; import { findComposerWarning } from "./composer"; -import { delay, elText, hoverProbe, isDisabledProp, isVisibleEnabled, legacyTile, videoTrimBounds } from "./dom"; +import { discoverStore } from "./discover_store"; +import { + delay, + elText, + fifeBase, + hoverProbe, + isDisabledProp, + isTrashedTile, + isVisibleEnabled, + legacyTile, + pickTileUrl, + readMediaUrl, + videoTrimBounds, +} from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; +import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { FlowTile, VideoOpRequest } from "./types"; +import type { FlowTile, NgLView, VideoOpRequest } from "./types"; + +/** Returns true when `fn` is a zero-argument Angular signal getter. */ +function isSignalGetter(fn: Function): boolean { + return fn.length === 0 && Object.getOwnPropertySymbols(fn).length > 0; +} + +/** Returns visible `.clip` elements on `flow-scene-timeline`. */ +function timelineClipElements(): HTMLElement[] { + return Array.from(document.querySelectorAll("flow-scene-timeline .clip")).filter( + (el): el is HTMLElement => + el instanceof HTMLElement && + !el.classList.contains("pending-placeholder") && + el.getClientRects().length > 0, + ); +} + +/** Returns true when `clipEl` on `flow-scene-timeline` has an Ivy context that matches `target`. */ +function timelineClipMatches( + clipEl: Element, + timelineLv: NgLView | null, + target: PickerMatchTarget, +): boolean { + const seenLViews = new Set(); + const nodes = [clipEl, ...Array.from(clipEl.querySelectorAll("*"))]; + for (const node of nodes) { + const lv = resolveLView(node); + if (!Array.isArray(lv) || lv === timelineLv || seenLViews.has(lv)) continue; + if (lv[0] instanceof Element && lv[0] !== clipEl && !clipEl.contains(lv[0])) { + continue; + } + seenLViews.add(lv); + for (const cand of lv) { + if ( + !cand || + typeof cand !== "object" || + cand instanceof Node || + cand instanceof Error || + Array.isArray(cand) || + cand instanceof Map || + cand === window || + cand === document + ) { + continue; + } + if (pickerAssetMatches(cand, target)) return true; + for (const key of ["$implicit", "clip", "asset", "item", "workflow"]) { + const val = readOwn(cand, key); + if (pickerAssetMatches(val, target)) return true; + if (typeof val === "function" && val.length === 0) { + try { + if (pickerAssetMatches(val.call(cand), target)) return true; + } catch { + // Ignore unrelated methods. + } + } + } + const ownKeys = Object.getOwnPropertyNames(cand); + for (let i = 0; i < ownKeys.length && i < 24; i += 1) { + const val = Object.getOwnPropertyDescriptor(cand, ownKeys[i])?.value; + if (pickerAssetMatches(val, target)) return true; + if (typeof val === "function" && isSignalGetter(val)) { + try { + if (pickerAssetMatches(val.call(cand), target)) return true; + } catch { + // Ignore signal read errors. + } + } + } + } + } + return false; +} + +/** Resolves `assetId` and `sceneId` against the bound project tile map for timeline clip selection. */ +function resolveExtendClipTarget( + tileMap: Map | null | undefined, + sceneId: string | null, + assetId: string, +): { + workflowId: string; + clipIndex: number; + sceneClipsCount: number; + matchTarget: PickerMatchTarget; +} { + let assetTile: FlowTile | undefined = tileMap?.get(assetId); + if (!assetTile && tileMap instanceof Map && assetId) { + for (const tile of tileMap.values()) { + if (!tile || isTrashedTile(tile)) continue; + if (String(tile.id ?? "") === assetId || String(tile.workflowId ?? "") === assetId) { + assetTile = tile; + break; + } + } + } + const normalizedAsset = legacyTile(assetTile); + const workflowId = String(normalizedAsset?.workflowId || assetTile?.workflowId || assetId); + const sceneTile = sceneId && tileMap instanceof Map ? tileMap.get(sceneId) : undefined; + const { clips, history } = sceneTile ? sceneContents(sceneTile) : { clips: [], history: new Map() }; + const activeClips = clips.filter((clip) => clip !== null); + const clipIndex = activeClips.findIndex( + (clip) => + String(clip?.workflowId ?? "") === workflowId || + String(clip?.workflowId ?? "") === assetId || + (clip?.primaryMediaId != null && String(clip.primaryMediaId) === assetId), + ); + const matchedClip = clipIndex >= 0 ? activeClips[clipIndex] : null; + const histMedia = history.get(workflowId)?.[0] ?? null; + const primaryMediaId = + matchedClip?.primaryMediaId ?? + normalizedAsset?.primaryMediaId ?? + normalizedAsset?.Kb?.id ?? + normalizedAsset?.Fb?.id ?? + histMedia?.id ?? + null; + const url = + readMediaUrl(matchedClip) || + readMediaUrl(histMedia) || + pickTileUrl(normalizedAsset) || + null; + return { + workflowId, + clipIndex, + sceneClipsCount: activeClips.length, + matchTarget: { + id: workflowId, + primaryMediaId, + url, + fife: url ? fifeBase(url) : undefined, + }, + }; +} /** Checks whether an observed start trim bound matches the requested start time. */ function startBoundMatches( @@ -139,7 +295,8 @@ export async function videoOp(req: VideoOpRequest): Promise { if (action === "prepare_extend") { const id = String(req?.asset_id || "").trim(); - const activeScene = /\/scene\/([^/?#]+)/.exec(location.pathname)?.[1]; + const activeScene = /\/scene\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; + let currentSceneId = req?.scene_id ? String(req.scene_id).trim() : activeScene; if (!activeScene || (req.scene_id && activeScene !== req.scene_id)) { if (!activeProjectStoreFormat()) { clearStore(); @@ -157,13 +314,24 @@ export async function videoOp(req: VideoOpRequest): Promise { } let sceneId = req?.scene_id ? String(req.scene_id).trim() : null; if (!sceneId) { - const wfId = String(tileMap.get(id)?.workflowId || id); + const rawSource = tileMap.get(id); + if (rawSource) { + if (isTrashedTile(rawSource) || rawSource.isPending) { + return { ok: false, error: `video_asset_unavailable:${id}` }; + } + const sourceType = String(rawSource.type ?? "").toUpperCase(); + if (sourceType !== "VIDEO") { + return { ok: false, error: `non_video_asset:${id}:${sourceType || "UNKNOWN"}` }; + } + } + const wfId = String(rawSource?.workflowId || id); const created = await createScene(helper, getMap, [wfId]); if (!created?.ok || !created.id) { return { ok: false, error: created.error ?? "failed_to_create_scene_for_extend" }; } sceneId = created.id; } + currentSceneId = sceneId; const pm = /\/project\/([^/?#]+)/.exec(location.pathname || ""); const pid = pm ? pm[1] : helper?.projectId || null; const router = pid ? findRouter() : null; @@ -183,7 +351,12 @@ export async function videoOp(req: VideoOpRequest): Promise { } } if (navigatedSpa) { - clearStore(); + if (runtimeState.store?.isCurrent()) { + runtimeState.routePath = location.pathname; + } else { + clearStore(); + await discoverStore(); + } await delay(250); } else if (pid) { return { @@ -198,18 +371,24 @@ export async function videoOp(req: VideoOpRequest): Promise { scene_id: sceneId, }; } + } else if (!runtimeState.store?.isCurrent()) { + await discoverStore(); } - for (let i = 0; i < 40; i++) { - if ( - document.querySelector( - "flow-scene-timeline, .is-extend-mode, .extend-composing, button[aria-label='Add clip']", - ) - ) { - break; - } + const readCurrentMap = (): Map | null | undefined => + runtimeState.store?.getTileMap?.(); + for (let i = 0; i < 25; i++) { + if (!runtimeState.store || runtimeState.store.isReady()) break; await delay(100); } + if (currentSceneId) { + for (let i = 0; i < 20; i++) { + const st = readCurrentMap()?.get(currentSceneId); + if (st && sceneContents(st).clips.some((clip) => clip !== null)) break; + if (!runtimeState.store) break; + await delay(100); + } + } const inExtendMode = (): boolean => Boolean( @@ -218,6 +397,13 @@ export async function videoOp(req: VideoOpRequest): Promise { ), ); + const findAddClipBtn = (): HTMLElement | null => { + const btn = document.querySelector( + 'flow-scene-timeline button[aria-label="Add clip"], flow-scene-builder button[aria-label="Add clip"], button[aria-label="Add clip"]', + ); + return isVisibleEnabled(btn) ? btn : null; + }; + const findExtendBtn = (): HTMLElement | null => Array.from( document.querySelectorAll('button, [role="button"], [role="tab"]'), @@ -239,41 +425,89 @@ export async function videoOp(req: VideoOpRequest): Promise { ); }) || null; - if (!inExtendMode()) { - let extendBtn = findExtendBtn(); - if (!extendBtn) { - 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(250); - } - for (let i = 0; i < 15; i++) { - extendBtn = findExtendBtn(); - if (extendBtn) break; - await delay(100); + let clipTarget = resolveExtendClipTarget(readCurrentMap(), currentSceneId, id); + for (let i = 0; i < 150; i++) { + if (inExtendMode()) { + break; + } + const selectedRendered = Boolean( + document.querySelector("flow-scene-timeline .clip.selected"), + ); + const addClipRendered = Boolean(findAddClipBtn()); + if (selectedRendered || addClipRendered) { + clipTarget = resolveExtendClipTarget(readCurrentMap(), currentSceneId, id); + const clipsDom = timelineClipElements(); + const expectedCount = + clipTarget.clipIndex >= 0 ? clipTarget.clipIndex + 1 : Math.min(clipTarget.sceneClipsCount, 1); + if (clipsDom.length >= expectedCount || i >= 45) { + await delay(150); + if ( + inExtendMode() || + Boolean(document.querySelector("flow-scene-timeline .clip.selected")) || + Boolean(findAddClipBtn()) + ) { + break; + } } } - if (extendBtn) { - extendBtn.click(); - await delay(300); + await delay(100); + } + + if (!runtimeState.store?.isCurrent()) { + await discoverStore(); + } + clipTarget = resolveExtendClipTarget(readCurrentMap(), currentSceneId, id); + + const clipEls = timelineClipElements(); + if (clipEls.length > 0 && !(runtimeState.ngLViewMap instanceof Map)) { + await withLViewMapCapture(async () => { + await hoverProbe(clipEls.slice(0, 6), 25); + }); + } + + const timelineHost = document.querySelector("flow-scene-timeline"); + const timelineLv = timelineHost ? resolveLView(timelineHost) : null; + let matchedClip: HTMLElement | null = + (id ? clipEls.find((el) => timelineClipMatches(el, timelineLv, clipTarget.matchTarget)) : null) ?? + (clipTarget.clipIndex >= 0 && clipTarget.clipIndex < clipEls.length + ? clipEls[clipTarget.clipIndex] + : !id && clipEls.length === 1 + ? clipEls[0] + : null); + + if (id && !matchedClip && (clipEls.length > 0 || clipTarget.sceneClipsCount > 0)) { + return { ok: false, error: `scene_clip_not_found:${id}` }; + } + + if (matchedClip && !matchedClip.classList.contains("selected")) { + matchedClip.scrollIntoView({ block: "nearest", inline: "center" }); + await delay(40); + matchedClip.click(); + for (let i = 0; i < 20; i++) { + if (matchedClip.classList.contains("selected")) break; + if (i === 8) matchedClip.click(); + await delay(100); } - if (!inExtendMode()) { - const addClipBtn = document.querySelector( - 'flow-scene-builder button[aria-label="Add clip"], flow-scene-timeline button[aria-label="Add clip"], button[aria-label="Add clip"]', - ); - if (isVisibleEnabled(addClipBtn)) { - if (!(runtimeState.ngLViewMap instanceof Map)) { - await withLViewMapCapture(async () => { - addClipBtn.click(); - await delay(250); - }); - } else { + if (!matchedClip.classList.contains("selected")) { + return { ok: false, error: `scene_clip_select_failed:${clipTarget.workflowId}` }; + } + await delay(150); + } + + if (!inExtendMode()) { + const addClipBtn = findAddClipBtn(); + if (addClipBtn) { + if (!(runtimeState.ngLViewMap instanceof Map)) { + await withLViewMapCapture(async () => { addClipBtn.click(); - await delay(250); - } + await delay(200); + }); + } else { + addClipBtn.click(); + await delay(200); + } + let extendOpt: Element | undefined; + for (let i = 0; i < 15; i++) { // Angular renders the menu in an overlay outside the menu host. const menuScope = document.querySelector(".extend-menu-panel") ?? document; const optCandidates = Array.from( @@ -281,7 +515,7 @@ export async function videoOp(req: VideoOpRequest): Promise { '.extend-clip-option button, .extend-clip-option [role="menuitem"], flow-menu-item.extend-clip-option, button, [role="menuitem"], [role="button"]', ), ); - const extendOpt = optCandidates.find((el) => { + extendOpt = optCandidates.find((el) => { if (el.getClientRects().length === 0) return false; const aria = (el.getAttribute("aria-label") || "").trim(); const raw = elText(el); @@ -294,26 +528,38 @@ export async function videoOp(req: VideoOpRequest): Promise { Boolean(el.closest(".extend-clip-option")) ); }); - if (extendOpt) { - const innerBtn = - extendOpt.querySelector("button, [role='menuitem']") || extendOpt; - if (!isVisibleEnabled(innerBtn) || !isVisibleEnabled(extendOpt)) { - if (!(runtimeState.ngLViewMap instanceof Map)) { - await withLViewMapCapture(async () => { - await hoverProbe([extendOpt, innerBtn], 40); - }); - } - const reason = - readAngularTooltip(extendOpt) || - readAngularTooltip(innerBtn) || - "unavailable"; - return { ok: false, error: `extend_option_disabled:${reason}` }; - } - innerBtn.click(); - for (let i = 0; i < 20; i++) { - if (inExtendMode()) break; - await delay(100); + if (extendOpt) break; + await delay(100); + } + if (extendOpt) { + const innerBtn = + extendOpt.querySelector("button, [role='menuitem']") || extendOpt; + if (!isVisibleEnabled(innerBtn) || !isVisibleEnabled(extendOpt)) { + if (!(runtimeState.ngLViewMap instanceof Map)) { + await withLViewMapCapture(async () => { + await hoverProbe([extendOpt, innerBtn], 40); + }); } + const reason = + readAngularTooltip(extendOpt) || + readAngularTooltip(innerBtn) || + "unavailable"; + return { ok: false, error: `extend_option_disabled:${reason}` }; + } + innerBtn.click(); + for (let i = 0; i < 20; i++) { + if (inExtendMode()) break; + await delay(100); + } + } + } + if (!inExtendMode()) { + const extendBtn = findExtendBtn(); + if (extendBtn) { + extendBtn.click(); + for (let i = 0; i < 20; i++) { + if (inExtendMode()) break; + await delay(100); } } } @@ -459,7 +705,7 @@ export async function videoOp(req: VideoOpRequest): Promise { if (!submitBtn.contains(document.elementFromPoint(x, y))) { return { ok: false, error: "extend_submit_button_obscured" }; } - return { ok: true, submit_point: { x, y } }; + return { ok: true, submit_point: { x, y }, scene_id: currentSceneId }; } if (action === "poll_extend") { @@ -513,7 +759,11 @@ export async function videoOp(req: VideoOpRequest): Promise { } } const closed = !location.pathname.includes("/scene/"); - clearStore(); + if (runtimeState.store?.isCurrent()) { + runtimeState.routePath = location.pathname; + } else { + clearStore(); + } return { ok: true, closed }; }