diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..499a858 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -277,12 +277,14 @@ Apply non-destructive trims or queue a video extension job. | Parameter | Type | Required | Description | | :--- | :--- | :--- | :--- | | `action` | `string` | Yes | `"trim"` (immediate RPC update) or `"extend"` (queues a `JobQueue` job returning `JobView`). | -| `match` | `string` | Yes | Video asset ID, exact name, or case-insensitive substring. | +| `match` | `string` | Yes | Stand-alone video ID, `:` scene clip ID, exact name, or case-insensitive substring. | | `start_seconds` | `number` | No | Trim start timestamp in seconds for `"trim"` (`null` clears start bound). | | `end_seconds` | `number` | No | Trim end timestamp in seconds for `"trim"` (`null` clears end bound). | | `prompt` | `string` | No | Continuation prompt for `"extend"`. | | `scene_id` | `string` | No | Optional existing scene ID to extend inside. | +`"trim"` updates a stand-alone video tile or updates the matching `:` clip inside its parent scene. For `"extend"`, `flow-mcp` opens `scene_id` when you set `scene_id` or pass `:`. When you omit `scene_id` for a stand-alone video, `flow_video` returns to the project root first and creates a new scene for that clip. If a scene is open when `prepare_extend` runs (or `scene_id` names an existing scene), `prepare_extend` looks for the target clip in that scene and returns `scene_clip_not_found` when the clip is absent instead of reusing the open scene. + ### `flow_scenes` List, create, populate, rename, or trash Flow scene timelines. @@ -352,7 +354,7 @@ Open the target project workspace before you upload. Upload works from the proje } ``` -The result gives `project_id`, `count`, and `assets`. Each asset gives its `id`, `name`, `kind`, and `primary_media_id` when available. +The result gives `project_id`, `count`, and `assets`. Each asset gives its `id`, `name`, `kind`, and `primary_media_id` when available. Stand-alone tiles use their tile `id`, and scenes have `kind: "scene"` with ID ``. Active clips in a scene timeline also appear with `kind: "video"` and ID `:`. If the batch stops, the error gives the assets that Flow confirms before the failure. It also gives `file` if the tool can identify the file in progress. If you get `outcome_unknown`, check the project before you retry. @@ -364,7 +366,7 @@ Rename assets, characters, scenes, or collections in batches and confirm through | :--- | :--- | :--- | :--- | | `items` | `object[]` | Yes | Non-empty array of `{"id": "...", "name": "..."}` entries. | -For an image or video tile that the page shows, `flow-mcp` first uses the **Rename** item of the tile menu and types the new name into the rename control of the page. In all other cases it sends the store mutation. Each entry of `items` in the result has `method`: `menu:rename` or `mutation`. For collections, the tool confirms the result in a new read of the project store. +For an image or video tile that the page shows, `flow-mcp` first uses the **Rename** item of the tile menu and types the new name into the rename control of the page. In all other cases it sends the store mutation. For a `:` scene clip ID, `flow-mcp` renames the underlying stand-alone video tile when one exists, and returns `scene_clip_has_no_tile_to_rename` if the clip exists only in the scene. Each entry of `items` in the result has `method`: `menu:rename` or `mutation`. For collections, the tool confirms the result in a new read of the project store. ### `flow_collections` @@ -419,4 +421,4 @@ Move a matching asset, character, scene, or collection to trash in Google Flow. | :--- | :--- | :--- | :--- | | `match` | `string` | Yes | Case-insensitive asset or collection ID, name, or prompt substring. | -`flow-mcp` first uses **Move to trash** in the tile menu. It uses the project store if it cannot confirm the result from the menu. The store path requires a verified request format and confirms the result with a fresh read. On success, the result includes `method` and `confirmed`. For a collection, the tool uses the same deletion procedure as `flow_collections`. +`flow-mcp` first uses **Move to trash** in the tile menu. It uses the project store if it cannot confirm the result from the menu. The store path requires a verified request format and confirms the result with a fresh read. For a `:` scene clip ID, the store removes that clip from `` and keeps any stand-alone video tile intact. On success, the result includes `method` and `confirmed`. For a collection, the tool uses the same deletion procedure as `flow_collections`. diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index 559b074..bef526a 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -277,12 +277,14 @@ UI 編集トリガーまたは `/edit/` を通じて既存の画像または | パラメータ | 型 | 必須 | 説明 | | :--- | :--- | :--- | :--- | | `action` | `string` | はい | `"trim"`(即時 RPC 更新)または `"extend"`(`JobQueue` ジョブを登録して `JobView` を返す)。 | -| `match` | `string` | はい | 動画アセット ID、完全一致名、または大文字小文字を区別しない部分文字列。 | +| `match` | `string` | はい | 単体動画 ID、`:` シーンクリップ ID、完全一致名、または大文字小文字を区別しない部分文字列。 | | `start_seconds` | `number` | いいえ | `"trim"` 用の開始タイムスタンプ秒(`null` で開始境界をクリア)。 | | `end_seconds` | `number` | いいえ | `"trim"` 用の終了タイムスタンプ秒(`null` で終了境界をクリア)。 | | `prompt` | `string` | いいえ | `"extend"` 用の延長プロンプト。 | | `scene_id` | `string` | いいえ | 延長先とする任意の既存シーン ID。 | +`"trim"` は単体の動画タイル、または親シーン内の対応する `:` クリップを更新します。`"extend"` では、`scene_id` を指定するか `:` を渡すと該当シーンを開きます。単体動画で `scene_id` を省略した場合、`flow_video` はまずプロジェクトルートへ戻り、そのクリップ用の新しいシーンを作成します。`prepare_extend` の実行時にシーンが開いている場合(または既存の `scene_id` を指定した場合)、`prepare_extend` はそのシーン内で対象クリップを検索し、存在しない場合は開いているシーンを無関係な単体動画に再利用せず `scene_clip_not_found` を返します。 + ### `flow_scenes` Flow シーンタイムラインの一覧表示、作成、クリップ追加、名前変更、またはゴミ箱移動を行います。 @@ -352,7 +354,7 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 } ``` -結果には `project_id`、`count`、`assets` が含まれます。各アセットには `id`、`name`、`kind`、取得できる場合は `primary_media_id` が含まれます。 +結果には `project_id`、`count`、`assets` が含まれます。各アセットには `id`、`name`、`kind`、取得できる場合は `primary_media_id` が含まれます。単体タイルは自身のタイル `id` を使い、シーンは `kind: "scene"`(ID は ``)を持ちます。シーンタイムライン内の有効なクリップも `kind: "video"`、ID `:` として一覧に含まれます。 途中で失敗した場合、エラーには Flow が確認済みのアセットが含まれます。処理中のファイルを特定できる場合は `file` も返ります。`outcome_unknown` が返った場合は、再試行の前にプロジェクトを確認してください。 @@ -364,7 +366,7 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 | :--- | :--- | :--- | :--- | | `items` | `object[]` | はい | `{"id": "...", "name": "..."}` エントリの空でない配列。 | -ページに表示されている画像または動画のタイルでは、`flow-mcp` はまずタイルメニューの **Rename** 項目を使い、ページのリネーム用コントロールに新しい名前を入力します。それ以外の場合は store mutation を送信します。結果の `items` の各エントリには `method`(`menu:rename` または `mutation`)が含まれます。 コレクションの名前変更は、プロジェクトのデータを再取得して確認します。 +ページに表示されている画像または動画のタイルでは、`flow-mcp` はまずタイルメニューの **Rename** 項目を使い、ページのリネーム用コントロールに新しい名前を入力します。それ以外の場合は store mutation を送信します。`:` シーンクリップ ID の場合、対応する単体動画タイルが存在すればそのタイルをリネームし、シーン内にのみ存在するクリップには `scene_clip_has_no_tile_to_rename` を返します。結果の `items` の各エントリには `method`(`menu:rename` または `mutation`)が含まれます。 コレクションの名前変更は、プロジェクトのデータを再取得して確認します。 ### `flow_collections` @@ -419,4 +421,4 @@ Google Flow 内で一致するアセット、キャラクター、シーン、 | :--- | :--- | :--- | :--- | | `match` | `string` | はい | アセットまたはコレクションの ID、名前、またはプロンプトに一致する大文字小文字を区別しない部分文字列。 | -`flow-mcp` はまずタイルメニューの **Move to trash** を使います。メニューから結果を確認できない場合は、プロジェクトの store を使います。store には検証済みのリクエスト形式が必要です。結果はプロジェクトを再読み込みして確認し、成功時に `method` と `confirmed` を返します。コレクションの場合は `flow_collections` と同じ手順で削除します。 +`flow-mcp` はまずタイルメニューの **Move to trash** を使います。メニューから結果を確認できない場合は、プロジェクトの store を使います。store には検証済みのリクエスト形式が必要です。`:` シーンクリップ ID を指定した場合、store は `` からそのクリップのみを削除し、単体動画タイルは維持します。結果はプロジェクトを再読み込みして確認し、成功時に `method` と `confirmed` を返します。コレクションの場合は `flow_collections` と同じ手順で削除します。 diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..a178aaa 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -277,12 +277,14 @@ flow-mcp [OPTIONS] | 参数 | 类型 | 必填 | 说明 | | :--- | :--- | :--- | :--- | | `action` | `string` | 是 | `"trim"`(即时 RPC 更新)或 `"extend"`(在 `JobQueue` 入队任务并返回 `JobView`)。 | -| `match` | `string` | 是 | 视频资产 ID、精确名称或忽略大小写子串。 | +| `match` | `string` | 是 | 独立视频 ID、`:` 场景片段 ID、精确名称或忽略大小写子串。 | | `start_seconds` | `number` | 否 | `"trim"` 的起始时间戳(秒;`null` 清除起点边界)。 | | `end_seconds` | `number` | 否 | `"trim"` 的结束时间戳(秒;`null` 清除终点边界)。 | | `prompt` | `string` | 否 | `"extend"` 的续写提示词。 | | `scene_id` | `string` | 否 | 要在其中进行续写的可选既有场景 ID。 | +`"trim"` 会更新独立视频 tile,或在所属场景中更新匹配的 `:` 片段。对于 `"extend"`,指定 `scene_id` 或传入 `:` 时,`flow-mcp` 会打开对应场景;对独立视频省略 `scene_id` 时,`flow_video` 会先回到项目主页并为该片段创建新场景。若调用 `prepare_extend` 时已打开某个场景(或指定了既有 `scene_id`),`prepare_extend` 会在该场景中查找目标片段,找不到时返回 `scene_clip_not_found`,而不会将当前打开的场景复用于无关的独立视频。 + ### `flow_scenes` 列出、创建、填充、重命名或将 Flow 场景时间线移入回收站。 @@ -352,7 +354,7 @@ flow-mcp [OPTIONS] } ``` -返回 `project_id`、`count` 和 `assets`。每项包含 `id`、`name`、`kind`,并在可用时返回 `primary_media_id`。 +返回 `project_id`、`count` 和 `assets`。每项包含 `id`、`name`、`kind`,并在可用时返回 `primary_media_id`。独立 tile 使用其自身 `id`,场景条目为 `kind: "scene"`(ID 为 ``),场景时间线中的活动片段也会以 `kind: "video"`、ID `:` 列出。 批次中途失败时,错误包含 Flow 已确认的资源。若能确定处理到哪个文件,也会返回 `file`。收到 `outcome_unknown` 时,请检查项目后再重试。 @@ -364,7 +366,7 @@ flow-mcp [OPTIONS] | :--- | :--- | :--- | :--- | | `items` | `object[]` | 是 | 非空的 `{"id": "...", "name": "..."}` 对象数组。 | -对于页面上显示的图像或视频 tile,`flow-mcp` 先使用 tile 菜单的 **Rename** 项,并在页面的重命名控件中输入新名称。其他情况下发送 store mutation。结果中 `items` 的每一项都带有 `method`:`menu:rename` 或 `mutation`。 集合重命名通过重新读取项目 store 来核验。 +对于页面上显示的图像或视频 tile,`flow-mcp` 先使用 tile 菜单的 **Rename** 项,并在页面的重命名控件中输入新名称。其他情况下发送 store mutation。对于 `:` 场景片段 ID,若存在对应的独立视频 tile 则重命名该视频 tile;若片段仅存在于场景内则返回 `scene_clip_has_no_tile_to_rename`。结果中 `items` 的每一项都带有 `method`:`menu:rename` 或 `mutation`。 集合重命名通过重新读取项目 store 来核验。 ### `flow_collections` @@ -419,4 +421,4 @@ flow-mcp [OPTIONS] | :--- | :--- | :--- | :--- | | `match` | `string` | 是 | 匹配资产或集合 ID、名称或提示词的忽略大小写子串。 | -`flow-mcp` 先尝试使用素材菜单的 **Move to trash**。无法通过菜单确认结果时,工具使用项目存储。直接写入需要已验证的请求格式,并通过重新读取项目确认结果。成功结果包含 `method` 和 `confirmed`。收藏夹使用与 `flow_collections` 相同的删除流程。 +`flow-mcp` 先尝试使用素材菜单的 **Move to trash**。无法通过菜单确认结果时,工具使用项目存储。直接写入需要已验证的请求格式,并通过重新读取项目确认结果。传入 `:` 场景片段 ID 时,项目存储仅从 `` 移除该片段,保留独立视频 tile。成功结果包含 `method` 和 `confirmed`。收藏夹使用与 `flow_collections` 相同的删除流程。 diff --git a/src/assets.rs b/src/assets.rs index c3c8975..b1c6aed 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -280,26 +280,63 @@ pub(crate) fn match_asset<'a>( return None; } let lower = raw.to_lowercase(); + let has_colon = raw.contains(':'); assets .iter() .find(|a| a.id == raw) + .or_else(|| { + (!has_colon).then(|| { + assets.iter().find(|a| { + crate::scenes::split_scene_clip_id(&a.id).is_some_and(|(_, wf)| wf == raw) + }) + })? + }) + .or_else(|| { + assets + .iter() + .find(|a| !a.id.contains(':') && a.name.eq_ignore_ascii_case(raw)) + }) .or_else(|| assets.iter().find(|a| a.name.eq_ignore_ascii_case(raw))) + .or_else(|| { + assets + .iter() + .find(|a| !a.id.contains(':') && a.name.to_lowercase().contains(&lower)) + }) .or_else(|| { assets .iter() .find(|a| a.name.to_lowercase().contains(&lower)) }) + .or_else(|| { + (!has_colon).then(|| { + assets + .iter() + .find(|a| !a.id.contains(':') && a.id.to_lowercase().contains(&lower)) + })? + }) .or_else(|| assets.iter().find(|a| a.id.to_lowercase().contains(&lower))) .or_else(|| { if include_prompt { - assets.iter().find(|a| { - a.prompt - .as_deref() - .unwrap_or("") - .to_lowercase() - .contains(&lower) - }) + assets + .iter() + .find(|a| { + !a.id.contains(':') + && a.prompt + .as_deref() + .unwrap_or("") + .to_lowercase() + .contains(&lower) + }) + .or_else(|| { + assets.iter().find(|a| { + a.prompt + .as_deref() + .unwrap_or("") + .to_lowercase() + .contains(&lower) + }) + }) } else { None } diff --git a/src/scenes.rs b/src/scenes.rs index 4969fcc..fb3044d 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result}; use schemars::JsonSchema; use serde::Deserialize; use serde_json::{Value, json}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use tokio::time::{Duration, Instant}; use crate::assets::{ @@ -63,20 +63,13 @@ fn start_bound_matches(actual: Option, expected: Option) -> bool { } /// Checks whether an observed end trim bound matches the requested end time. -fn end_bound_matches( - actual: Option, - expected: Option, - before: Option, - duration: Option, -) -> bool { +fn end_bound_matches(actual: Option, expected: Option, duration: Option) -> bool { match expected { None => { actual.is_none() - || actual.zip(duration).is_some_and(|(act, dur)| { - dur > 0.0 - && before.is_none_or(|b| (b - dur).abs() > 0.01) - && (act - dur).abs() <= 0.01 - }) + || actual + .zip(duration) + .is_some_and(|(act, dur)| dur > 0.0 && (act - dur).abs() <= 0.01) } Some(exp) => actual.is_some_and(|act| (act - exp).abs() <= 0.01), } @@ -102,7 +95,6 @@ async fn confirm_trimmed_video( && end_bound_matches( video.trim_end_seconds, end_seconds, - before.trim_end_seconds, video.duration.or(before.duration), ) { @@ -137,6 +129,70 @@ fn clip_entered_error(asset: &FlowAsset, before: &HashMap) } } +/// Splits a `:` clip asset ID into its scene ID and workflow ID. +pub(crate) fn split_scene_clip_id(id: &str) -> Option<(&str, &str)> { + let (scene_id, wf_id) = id.split_once(':')?; + (!scene_id.is_empty() && !wf_id.is_empty() && !wf_id.contains(':')).then_some((scene_id, wf_id)) +} + +/// Returns `true` when `asset` is a settled video whose media ID or URL changed since `before`. +fn clip_updated_since(asset: &FlowAsset, before: &HashMap) -> bool { + if asset.kind != "video" + || clip_is_failed(asset) + || matches!(asset.media_status.as_deref(), Some("pending" | "scheduled")) + || (asset.url.is_none() && asset.primary_media_id.is_none()) + { + return false; + } + before.get(&asset.id).is_none_or(|prior| { + asset.primary_media_id.as_deref().map_or_else( + || asset.url.is_some() && asset.url != prior.url, + |media_id| prior.primary_media_id.as_deref() != Some(media_id), + ) + }) +} + +/// Collects updated video assets, prioritizing watched IDs and deduplicating by `primary_media_id`. +fn collect_extended_videos( + assets: &[FlowAsset], + before: &HashMap, + watched_ids: &[String], + opened_scene_id: Option<&str>, +) -> Vec { + let mut ordered: Vec<&FlowAsset> = Vec::new(); + for watched in watched_ids { + if let Some(asset) = assets.iter().find(|a| &a.id == watched) + && clip_updated_since(asset, before) + { + ordered.push(asset); + } + } + if let Some(prefix) = opened_scene_id.map(|sid| format!("{sid}:")) { + for asset in assets { + if watched_ids.iter().any(|w| w == &asset.id) || !clip_updated_since(asset, before) { + continue; + } + if asset.id.starts_with(&prefix) { + ordered.push(asset); + } + } + } + let mut seen_media = HashSet::new(); + let mut fresh = Vec::new(); + for asset in ordered { + if let Some(media_id) = asset + .primary_media_id + .as_deref() + .filter(|id| !id.is_empty()) + && !seen_media.insert(media_id.to_string()) + { + continue; + } + fresh.push(asset.clone()); + } + fresh +} + /// Parameters for `flow_scenes`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct ScenesParams { @@ -192,6 +248,7 @@ pub(crate) async fn handle_scenes( "create" => { let asset_ids = req.asset_ids.unwrap_or_default(); let _ = read_snapshot(engine).await?; + let _store_guard = engine.lock_project_store().await; let payload = json!({ "action": "create", "asset_ids": asset_ids, @@ -215,6 +272,7 @@ pub(crate) async fn handle_scenes( .filter(|v| !v.is_empty()) .context("flow_scenes add_clips requires non-empty 'asset_ids'")?; let _ = read_snapshot(engine).await?; + let _store_guard = engine.lock_project_store().await; let payload = json!({ "action": "add_clips", "scene_id": scene_id, @@ -302,19 +360,29 @@ pub(crate) async fn run_video_extend( ); let project_id = snap.project_id.clone(); + let (implied_scene_id, implied_wf_id) = split_scene_clip_id(&target.id) + .map(|(sid, wf)| (Some(sid), Some(wf))) + .unwrap_or((None, None)); + let requested_scene_id = scene_id.or(implied_scene_id); + on_progress(format!("opening extend editor for {}", target.id)); let req_payload = json!({ "action": "prepare_extend", "asset_id": target.id, - "scene_id": scene_id, + "scene_id": requested_scene_id, "prompt": prompt, }); let mut res = engine .call_flow_async("videoOp", json!([req_payload])) .await?; - let opened_scene_id = res + let mut opened_scene_id = res .get("scene_id") .and_then(|v| v.as_str()) + .map(str::to_string) + .or_else(|| requested_scene_id.map(str::to_string)); + let mut workflow_id = res + .get("workflow_id") + .and_then(|v| v.as_str()) .map(str::to_string); if let Some(nav_url) = res.get("need_navigate").and_then(|v| v.as_str()) { @@ -330,6 +398,12 @@ pub(crate) async fn run_video_extend( res = engine .call_flow_async("videoOp", json!([retry_payload])) .await?; + if let Some(sid) = res.get("scene_id").and_then(|v| v.as_str()) { + opened_scene_id = Some(sid.to_string()); + } + if let Some(wf) = res.get("workflow_id").and_then(|v| v.as_str()) { + workflow_id = Some(wf.to_string()); + } } if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { @@ -343,6 +417,17 @@ pub(crate) async fn run_video_extend( let point = res .get("submit_point") .context("Video extend did not return a submit point")?; + let target_wf_id = workflow_id + .or_else(|| implied_wf_id.map(str::to_string)) + .unwrap_or_else(|| target.id.clone()); + let mut watched_ids = vec![target.id.clone()]; + if let Some(ref sid) = opened_scene_id { + let clip_asset_id = format!("{sid}:{target_wf_id}"); + if !watched_ids.contains(&clip_asset_id) { + watched_ids.push(clip_asset_id); + } + } + // Scene creation can copy the input clip to a new workflow before submission. let prepared = list_assets_with_project(engine).await?; anyhow::ensure!( @@ -354,6 +439,9 @@ pub(crate) async fn run_video_extend( .iter() .map(|asset| (asset.id.clone(), ClipBaseline::from_asset(asset))) .collect(); + before + .entry(target.id.clone()) + .or_insert_with(|| ClipBaseline::from_asset(&target)); let mut net_rx = engine.subscribe_network().await?; engine.click_point(point).await?; @@ -390,11 +478,18 @@ pub(crate) async fn run_video_extend( prior.media_error = None; } } - if let Some(failed_tile) = cur_snap - .assets - .iter() - .find(|a| clip_entered_error(a, &before)) - { + let watched_failure = watched_ids.iter().find_map(|watched| { + cur_snap + .assets + .iter() + .find(|a| &a.id == watched && clip_entered_error(a, &before)) + }); + if let Some(failed_tile) = watched_failure.or_else(|| { + cur_snap + .assets + .iter() + .find(|a| clip_entered_error(a, &before)) + }) { extend_err = Some(anyhow::anyhow!( "Flow video extend failed on tile {}: {}", failed_tile.id, @@ -407,21 +502,12 @@ 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(); + let fresh = collect_extended_videos( + &cur_snap.assets, + &before, + &watched_ids, + opened_scene_id.as_deref(), + ); if !fresh.is_empty() { new_assets = fresh; break; diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..601c303 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -12,6 +12,11 @@ import { readMediaUrl, } from "./dom"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { + findVideoTileByIdOrWorkflow, + readSceneAspectRatio, + readSceneCollectionId, +} from "./scene_tiles"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -25,7 +30,7 @@ export interface NgContextCarrier { /** Reads an own or prototype property safely without triggering exceptions. */ export function readOwn(obj: unknown, key: string): unknown { - if (!obj || typeof obj !== "object") return undefined; + if (!obj || (typeof obj !== "object" && typeof obj !== "function")) return undefined; try { return Reflect.get(obj as object, key); } catch { @@ -437,7 +442,11 @@ export async function createScene( getMap: () => Map | null | undefined, workflowIds: string[], ): Promise<{ ok: boolean; id?: string; error?: string }> { - const before = new Set(sceneIds(getMap())); + const currentMap = getMap(); + const before = new Set(sceneIds(currentMap)); + const clip0 = findVideoTileByIdOrWorkflow(currentMap, workflowIds[0]); + const aspectRatio = readSceneAspectRatio(clip0); + const collectionId = readSceneCollectionId(clip0); const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa"; let confirmedId: string | undefined; let failure: string | undefined; @@ -451,13 +460,13 @@ 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) => { - completion.resolve(readOwn(response, resultField)); + completion.resolve(readOwn(response, resultField) ?? readOwn(response, "t6a")); }, completion.reject); while (performance.now() < deadline) { diff --git a/ts/asset_ops.ts b/ts/asset_ops.ts index 546e15a..79ef358 100644 --- a/ts/asset_ops.ts +++ b/ts/asset_ops.ts @@ -3,9 +3,11 @@ // Rename assets through the bound store. +import { isTrashedTile } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; +import { findVideoTileByIdOrWorkflow, sceneContents, splitSceneClipId } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { AssetRenameExtra } from "./types"; +import type { AssetRenameExtra, FlowTile } from "./types"; /** Renames one asset, character, or scene tile. */ export async function assetOps( @@ -31,13 +33,38 @@ export async function assetOps( return { ok: false, err: "store_not_bound" }; } - const tile = tileMap.get(id); - if (String(tile?.type || "").toUpperCase() === "COLLECTION") { + let targetId = id; + let tile: FlowTile | undefined; + const clipRef = splitSceneClipId(id); + if (clipRef) { + const sceneTile = tileMap.get(clipRef.sceneId); + if ( + !sceneTile || + isTrashedTile(sceneTile) || + String(sceneTile.type ?? "").toUpperCase() !== "SCENE" || + !sceneContents(sceneTile).clips.some( + (clip) => String(clip?.workflowId ?? "") === clipRef.workflowId, + ) + ) { + return { ok: false, err: "asset_not_found" }; + } + tile = findVideoTileByIdOrWorkflow(tileMap, clipRef.workflowId); + if (!tile) { + return { ok: false, err: "scene_clip_has_no_tile_to_rename" }; + } + targetId = String(tile.id ?? clipRef.workflowId); + } else { + tile = tileMap.get(id); + if (!tile || isTrashedTile(tile)) { + return { ok: false, err: "asset_not_found" }; + } + } + if (String(tile.type || "").toUpperCase() === "COLLECTION") { return { ok: false, err: "collection_path_required" }; } const newName = String(extra?.name ?? ""); - if (extra?.resetOld && tile) { + if (extra?.resetOld) { try { tile.displayName = `__tmp_${Date.now()}`; } catch { @@ -46,12 +73,12 @@ export async function assetOps( } try { if (helper.rename) { - await helper.rename(id, newName); + await helper.rename(targetId, newName); } else if (helper.mutate) { await helper.mutate({ type: "single_tile", - Xc: id, - Uc: id, + Xc: targetId, + Uc: targetId, Ve: { type: "set_display_name", displayName: newName }, }); } else { diff --git a/ts/asset_trash.ts b/ts/asset_trash.ts index 934b0e9..7fba95e 100644 --- a/ts/asset_trash.ts +++ b/ts/asset_trash.ts @@ -6,7 +6,7 @@ import { isTrashedTile } from "./dom"; import { assetTrashCompatibility } from "./frontend_compatibility"; import { mutateAndVerify, projectMutationPending, projectsToRefresh, projectStore, readProjectStore, refreshAfterUnknown } from "./project_store"; -import { sceneContents } from "./scene_tiles"; +import { sceneContents, splitSceneClipId } from "./scene_tiles"; import type { FlowTile } from "./types"; /** Returns true when a scene still refers to the clip workflow. */ @@ -19,6 +19,26 @@ function isSceneClip(tiles: Iterable, id: string): boolean { return false; } +/** Counts active clip entries in `scene` that match `workflowId`, and returns the last index. */ +function activeSceneClipState( + scene: FlowTile | undefined, + workflowId: string, +): { count: number; lastIndex: number } { + if (!scene || isTrashedTile(scene) || scene.isPending || scene.type !== "SCENE") { + return { count: 0, lastIndex: -1 }; + } + const { clips } = sceneContents(scene); + let count = 0; + let lastIndex = -1; + for (let i = 0; i < clips.length; i += 1) { + if (String(clips[i]?.workflowId ?? "") === workflowId) { + count += 1; + lastIndex = i; + } + } + return { count, lastIndex }; +} + /** Asset types that Flow can move to trash through the tile store. */ const TRASHABLE_TYPES = new Set(["IMAGE", "VIDEO", "CHARACTER", "SCENE", "TEXT_TILE"]); @@ -30,12 +50,49 @@ export async function trashAssetOp(projectId: string, session: string, id: strin const support = assetTrashCompatibility(); if (!support.ok) return support; if (projectMutationPending) return { ok: false, error: "project_mutation_pending" }; - if (projectsToRefresh.has(projectId) || !tiles.has(id)) { + const clipRef = splitSceneClipId(id); + const lookupId = clipRef ? clipRef.sceneId : id; + if (projectsToRefresh.has(projectId) || !tiles.has(lookupId)) { tiles = await refreshAfterUnknown(store); if (!tiles) return { ok: false, error: "project_refresh_failed", project_id: projectId }; } const { format } = support; + if (clipRef) { + let state = activeSceneClipState(tiles.get(clipRef.sceneId), clipRef.workflowId); + if (state.count === 0) return { ok: false, error: "asset_not_found", id }; + if (store.format.mutations?.clipIndex) { + const method = "scene_delete_clip_mutation"; + while (state.count > 0 && state.lastIndex >= 0) { + const expectedMax = state.count - 1; + const after = await mutateAndVerify( + store, + { + type: "single_tile", + Xc: clipRef.sceneId, + Ve: { type: "scene_delete_clip_mutation", ik: state.lastIndex }, + }, + (fresh) => + activeSceneClipState(fresh.get(clipRef.sceneId), clipRef.workflowId).count <= expectedMax, + ); + if (!after) { + return { ok: false, error: "outcome_unknown", stage: method, project_id: projectId, id }; + } + state = activeSceneClipState(after.get(clipRef.sceneId), clipRef.workflowId); + } + return { ok: true, method, confirmed: true }; + } + const method = "batch_delete_tiles:scene_clip"; + const after = await mutateAndVerify( + store, + { type: "batch_delete_tiles", [format.sceneWorkflows]: [clipRef.workflowId] }, + (fresh) => activeSceneClipState(fresh.get(clipRef.sceneId), clipRef.workflowId).count === 0, + ); + return after + ? { ok: true, method, confirmed: true } + : { ok: false, error: "outcome_unknown", stage: method, project_id: projectId, id }; + } + const tile = tiles.get(id); if (tile?.type === "COLLECTION") return { ok: false, error: "collection_path_required" }; if (tile && isTrashedTile(tile)) return { ok: true, method: "already_trashed", confirmed: true }; diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index c10c146..9208a61 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -8,6 +8,8 @@ import type { AgentExport } from "./agent_protocol"; import type { AgentWireFormat } from "./agent_wire"; import type { AgentSettingsExport } from "./agent_settings_protocol"; import type { MediaUploadExport } from "./project_upload"; +import type { SceneBuilderFormat, SceneTileFormat } from "./scene_tiles"; +export type { SceneBuilderFormat, SceneTileFormat }; /** Field names for the collection write requests of one build. */ export interface CollectionWriteFormat { @@ -330,18 +332,12 @@ export interface ProjectStoreFormat { lContextView: string; /** Field names of a scene tile and its workflow history. */ scene?: SceneTileFormat; + /** Native scene builder controller, timeline, and player signal names. */ + sceneBuilder?: SceneBuilderFormat; /** Native names for mutations that use the general store adapter. */ mutations?: ProjectMutationFormat; } -/** Fields that identify the contents of a scene tile. */ -export interface SceneTileFormat { - /** Clip array on a scene tile. */ - clips: string; - /** Workflow history map on a scene tile. */ - history: string; -} - /** Names of fields used by the general project mutations. */ export interface ProjectMutationFormat { /** Tile ID in a single-tile request. */ @@ -360,6 +356,12 @@ export interface ProjectMutationFormat { trimStart: string; /** End time in a video trim request. */ trimEnd: string; + /** Start time in a scene clip primary media update (`Ji`). */ + clipTrimStart: string; + /** End time in a scene clip primary media update (`Ci`). */ + clipTrimEnd: string; + /** Positional clip index in a scene clip mutation (`ik`). */ + clipIndex: string; } /** Project store format of build 20261117.10. */ @@ -412,10 +414,16 @@ const NOVEMBER_20_STORE: ProjectStoreFormat = { errorStream: "Da", componentSlots: ["fh", "ha", "Ew", "la", "ka"], lContextView: "zp", - scene: { clips: "Uc", history: "Cg" }, + scene: { clips: "Uc", history: "Cg", clipStart: "Ji", clipEnd: "Ci", clipDuration: "nc" }, + sceneBuilder: { + controller: "su", timeline: "B6", player: "Gc", playerReady: "Dx", + selectedClip: "la", clips: "Uc", extendDisabledReason: "Yo", + activeExtendClip: "TL", exitExtend: "rE", modelsQuery: "Od", + }, mutations: { tileId: "Xc", tileChange: "mf", sceneWorkflows: "ng", sceneCollection: "Dc", - sceneCreated: "t6a", sceneId: "yc", trimStart: "dh", trimEnd: "ug", + sceneCreated: "y6a", sceneId: "yc", trimStart: "dh", trimEnd: "ug", + clipTrimStart: "Ji", clipTrimEnd: "Ci", clipIndex: "ik", }, }; @@ -927,9 +935,16 @@ export function withMutationAliases(payload: Record): Record; if (format) { - const native = change.type === "set_video_trim_seconds" ? { - ...change, [format.trimStart]: change.Cg, [format.trimEnd]: change.Rf, - } : change; + let native: Record = change; + if (change.type === "set_video_trim_seconds") { + native = { ...change, [format.trimStart]: change.Cg, [format.trimEnd]: change.Rf }; + } else if (change.type === "set_scene_clip_primary_media") { + native = { ...change }; + if (typeof change.Ji === "number") native[format.clipTrimStart] = change.Ji; + if (typeof change.Ci === "number") native[format.clipTrimEnd] = change.Ci; + } else if (change.type === "scene_delete_clip_mutation") { + native = { ...change, [format.clipIndex]: change.ik }; + } return { ...payload, [format.tileId]: payload.Xc ?? payload.Uc, [format.tileChange]: native }; } const collectionWrite = build?.operations.collection_write; diff --git a/ts/frontend_compatibility.ts b/ts/frontend_compatibility.ts index 26f1f1a..5034963 100644 --- a/ts/frontend_compatibility.ts +++ b/ts/frontend_compatibility.ts @@ -18,6 +18,7 @@ import type { } from "./frontend_builds"; import { findProjectPage } from "./project_upload"; import { projectWriteChecks } from "./project_store"; +import { sceneBuilderChecks } from "./scene_tiles"; import { legacyTile, pickTileUrl } from "./dom"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, StoreProbeCheck, StoreProbeResult } from "./types"; @@ -441,6 +442,7 @@ export function probeStore(): StoreProbeResult { detail: views ? `${views.size} views` : "not captured", }, ...trashChecks, + ...sceneBuilderChecks(build), ]; const pageChecks = projectPageOperationChecks(build); const operations: Record< diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..b9d840f 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -11,6 +11,7 @@ import { type NgContextCarrier, } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; +import { splitSceneClipId } from "./scene_tiles"; import { clearStore } from "./state"; /** Navigates to `/edit/` using Angular Router or triggers an inline tile edit action. */ @@ -20,8 +21,11 @@ export async function openEditAsset( primaryMediaId: string | null, ): Promise { const idStr = String(assetId || "").trim(); + const clipRef = splitSceneClipId(idStr); const candidateIds = Array.from( - new Set([idStr, String(primaryMediaId || "").trim()].filter(Boolean)), + new Set( + [clipRef ? clipRef.workflowId : idStr, String(primaryMediaId || "").trim()].filter(Boolean), + ), ); function findVisibleTextbox(): Element | null { @@ -40,9 +44,20 @@ export async function openEditAsset( 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) { + if (router && pid && (clipRef || candidateIds.length > 0)) { let viewKind: string | null = null; - for (const candId of candidateIds) { + if (clipRef) { + await navigateSpa(router, ["/project", pid, "scene", clipRef.sceneId]); + for (let i = 0; i < 60; i += 1) { + const onScene = (location.pathname || "").includes(`/scene/${clipRef.sceneId}`); + if (onScene && document.querySelector("flow-scene-builder")) { + viewKind = "scene_builder"; + break; + } + await delay(100); + } + } + for (const candId of viewKind ? [] : candidateIds) { await navigateSpa(router, ["/project", pid, "edit", candId]); for (let i = 0; i < 60; i += 1) { const onRoute = (location.pathname || "").includes("/edit/"); @@ -187,7 +202,9 @@ export async function openEditAsset( if (pid && idStr) { return { opened: false, - edit_url: buildProjectUrl(pid, ["edit", idStr]), + edit_url: clipRef + ? buildProjectUrl(pid, ["scene", clipRef.sceneId]) + : buildProjectUrl(pid, ["edit", idStr]), method: "route_fallback_needed", }; } diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..d3d14b6 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -94,6 +94,11 @@ export function currentProjectStore(projectId: string): ProjectStore | null { return active?.projectId === projectId ? active : null; } +/** Returns the live bound store for the active session when present. */ +export function activeProjectStore(): ProjectStore | null { + return activeBoundStore(); +} + /** Finds the query by its full project key. */ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTileQuery | undefined { const tiles = readOwn(service, format.tilesService); @@ -435,12 +440,13 @@ function storeDispatcher({ service, format }: ProjectStore): unknown { /** Sends one mutation to the server with the bound project ID. */ async function submitProjectMutation( store: ProjectStore, - payload: Record, + rawPayload: Record, ): Promise { const dispatch = storeDispatcher(store); if (!isCurrent(store) || activeBoundStore() !== store || typeof dispatch !== "function") { throw new Error("project_store_changed"); } + const payload = withMutationAliases(rawPayload); await dispatch.call(readOwn(store.service, store.format.tilesService), store.projectId, payload); } @@ -469,6 +475,7 @@ export async function mutateAndVerify( store: ProjectStore, payload: Record, verified: (tiles: Map) => boolean, + onSubmitError?: (error: unknown) => void, ): Promise | null> { projectMutationPending = true; projectsToRefresh.add(store.projectId); @@ -482,8 +489,12 @@ export async function mutateAndVerify( }); const work = (async () => { try { + let submitFailed = false; // A request can reach Flow even if the response does not reach this page. - await submitProjectMutation(store, payload).catch(() => {}); + await submitProjectMutation(store, payload).catch((err: unknown) => { + submitFailed = true; + onSubmitError?.(err); + }); while (!timedOut && activeBoundStore() === store && isCurrent(store)) { const tiles = await refreshProjectStore(store).catch(() => null); if (timedOut) return null; @@ -491,6 +502,7 @@ export async function mutateAndVerify( projectsToRefresh.delete(store.projectId); return tiles; } + if (submitFailed && tiles) return null; await Promise.race([delay(MUTATION_CHECK_INTERVAL_MS), timeout]); } return null; diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..e040fb3 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -7,7 +7,7 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; import { currentProjectStore, projectInRoute } from "./project_store"; -import { sceneContents } from "./scene_tiles"; +import { readSceneClipBounds, sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, characterLookMedia, @@ -25,7 +25,6 @@ import { clearStore, runtimeState } from "./state"; import type { FlowMediaPayload, FlowTile, - SceneClipItem, SnapshotAssetItem, SnapshotCollectionItem, StoreSnapshotResult, @@ -237,6 +236,7 @@ export function readStoreTiles(tileMap: Map): { const cols = new Map(); const counts = new Map(); const byId = new Map>(); + const videoByWorkflow = new Map>(); const sceneTiles: FlowTile[] = []; const rawList: Omit[] = []; const env = getFifeEnv(); @@ -455,67 +455,81 @@ export function readStoreTiles(tileMap: Map): { }; rawList.push(topEntry); byId.set(tid, topEntry); + if (ttype === "VIDEO") { + videoByWorkflow.set(tid, topEntry); + const wfKey = t.workflowId ? String(t.workflowId) : ""; + if (wfKey) videoByWorkflow.set(wfKey, topEntry); + } } for (const st of sceneTiles) { + const sceneId = String(st.id ?? "").trim(); + if (!sceneId) continue; + const sceneGridEntry = byId.get(sceneId); const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); - const candidates: Array< - [string, SceneClipItem | null, FlowMediaPayload | null] - > = []; + for (const clip of clips) { - const wfId = clip?.workflowId ? String(clip.workflowId) : null; + const wfId = clip?.workflowId ? String(clip.workflowId).trim() : ""; if (!wfId) continue; + const clipAssetId = `${sceneId}:${wfId}`; const hist = history.get(wfId); - const primaryId = clip?.primaryMediaId + const requestedPrimaryId = clip?.primaryMediaId ? String(clip.primaryMediaId) : null; - const mObj = Array.isArray(hist) - ? hist.find((x) => x && String(x.id || "") === primaryId) || - hist[0] || - null + const rawMedia = Array.isArray(hist) + ? (requestedPrimaryId + ? hist.find( + (x) => + x && + (String(x.id ?? "") === requestedPrimaryId || + String(x.mediaId ?? "") === requestedPrimaryId), + ) ?? null + : hist[0] ?? null) : null; - candidates.push([wfId, clip, mObj]); - } - for (const [wfId, hist] of history) { - const mObj = Array.isArray(hist) ? hist[0] || null : null; - candidates.push([wfId, null, mObj]); - } - - for (const [wfId, clip, rawMedia] of candidates) { - if (!wfId) continue; const mObj = legacyMedia(rawMedia); const cObj = legacyMedia(clip as FlowMediaPayload | null); const mStatus = String( 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; - } + if ( + sceneGridEntry && + (mStatus === "failed" || mStatus === "canceled" || mError) + ) { + if ( + sceneGridEntry.media_status !== "failed" && + sceneGridEntry.media_status !== "canceled" + ) { + sceneGridEntry.media_status = mStatus || sceneGridEntry.media_status; + } + if (!sceneGridEntry.media_error && mError) { + sceneGridEntry.media_error = mError; } - continue; } + + const topVideo = videoByWorkflow.get(wfId); + const clipPrimaryMediaId = + requestedPrimaryId || + (mObj?.id ? String(mObj.id) : null) || + (mObj?.mediaId ? String(mObj.mediaId) : null) || + topVideo?.primary_media_id || + null; + const sameMediaAsTop = Boolean( + topVideo && + (!clipPrimaryMediaId || + topVideo.primary_media_id === clipPrimaryMediaId), + ); + const effectiveStatus = + mStatus || (sameMediaAsTop ? (topVideo?.media_status ?? "") : ""); + const effectiveError = + mError ?? (sameMediaAsTop ? (topVideo?.media_error ?? null) : null); const mNotReady = - 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; + effectiveStatus === "pending" || + effectiveStatus === "scheduled" || + effectiveStatus === "failed" || + effectiveStatus === "canceled" || + Boolean(effectiveError); const cachedClipVideoUrl = clipPrimaryMediaId ? asHttpOrDataUrl( runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, @@ -526,49 +540,48 @@ export function readStoreTiles(tileMap: Map): { readMediaUrl(clip, true) || readMediaUrl(mObj) || readMediaUrl(clip) || - null; + (sameMediaAsTop ? topVideo?.url ?? null : null); const rawClipUrl = isSignedUrlStr(tileClipUrl) ? tileClipUrl : isSignedUrlStr(cachedClipVideoUrl) ? cachedClipVideoUrl : tileClipUrl || cachedClipVideoUrl || null; const clipUrl = mNotReady ? null : rawClipUrl; + const clipBounds = readSceneClipBounds(clip); const trimStartVal = - typeof clip?.Ji === "number" ? clip.Ji : - typeof mObj?.Jc === "number" ? mObj.Jc : - typeof mObj?.Ac === "number" - ? mObj.Ac - : typeof mObj?.Cg === "number" - ? mObj.Cg - : typeof clip?.Mh === "number" - ? clip.Mh - : null; + clipBounds.start ?? + (typeof mObj?.Jc === "number" + ? mObj.Jc + : typeof mObj?.Ac === "number" + ? mObj.Ac + : typeof mObj?.Cg === "number" + ? mObj.Cg + : null); const trimEndVal = - typeof clip?.Ci === "number" ? clip.Ci : - typeof mObj?.Pc === "number" ? mObj.Pc : - typeof mObj?.Ic === "number" - ? mObj.Ic - : typeof mObj?.Rf === "number" - ? mObj.Rf - : typeof clip?.Eh === "number" - ? clip.Eh - : null; + clipBounds.end ?? + (typeof mObj?.Pc === "number" + ? mObj.Pc + : typeof mObj?.Ic === "number" + ? mObj.Ic + : typeof mObj?.Rf === "number" + ? mObj.Rf + : null); const durVal = - typeof clip?.nc === "number" ? clip.nc : - typeof clip?.rc === "number" - ? clip.rc - : typeof mObj?.durationSeconds === "number" - ? mObj.durationSeconds - : typeof mObj?.duration === "number" - ? mObj.duration - : typeof mObj?.Lf === "number" - ? mObj.Lf - : null; + clipBounds.duration ?? + (typeof mObj?.durationSeconds === "number" + ? mObj.durationSeconds + : typeof mObj?.duration === "number" + ? mObj.duration + : typeof mObj?.Lf === "number" + ? mObj.Lf + : sameMediaAsTop + ? (topVideo?.duration ?? null) + : null); const clipPrompt = mObj?.prompt ? String(mObj.prompt) : mObj?.inputs?.prompt ? String(mObj.inputs.prompt) - : null; + : topVideo?.prompt ?? null; const clipCreated = mObj?.hc instanceof Date ? mObj.hc.toISOString() @@ -578,10 +591,13 @@ export function readStoreTiles(tileMap: Map): { ? st.hc.toISOString() : st.hc ? String(st.hc) - : null; - const sceneEntry: Omit = { - id: wfId, - name: String((mObj as FlowTile | null)?.displayName || st.displayName || ""), + : topVideo?.created_at ?? null; + const clipName = String( + (mObj as FlowTile | null)?.displayName || topVideo?.name || "", + ); + const clipEntry: Omit = { + id: clipAssetId, + name: clipName, kind: "video", prompt: clipPrompt, url: clipUrl ? normalizeFlowMediaUrl(String(clipUrl), "video", env) : null, @@ -591,25 +607,30 @@ export function readStoreTiles(tileMap: Map): { voice: null, trim_start_seconds: trimStartVal, trim_end_seconds: trimEndVal, - media_status: mStatus || null, - media_error: mError, + media_status: effectiveStatus || null, + media_error: effectiveError, width: typeof mObj?.width === "number" ? mObj.width : typeof mObj?.tc?.width === "number" ? mObj.tc.width - : null, + : topVideo?.width ?? null, height: typeof mObj?.height === "number" ? mObj.height : typeof mObj?.tc?.height === "number" ? mObj.tc.height - : null, + : topVideo?.height ?? null, duration: durVal, created_at: clipCreated, }; - rawList.push(sceneEntry); - byId.set(wfId, sceneEntry); + const existingClipEntry = byId.get(clipAssetId); + if (existingClipEntry) { + Object.assign(existingClipEntry, clipEntry); + } else { + rawList.push(clipEntry); + byId.set(clipAssetId, clipEntry); + } } } diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index fc47fbb..a2664ad 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -4,11 +4,119 @@ // 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 { activeProjectStore, mutateAndVerify, refreshProjectStore } from "./project_store"; +import { sceneContents, splitSceneClipId } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, SceneOpRequest } from "./types"; +/** Counts occurrences of each workflow ID in `workflowIds`. */ +function countWorkflows(workflowIds: readonly string[]): Map { + const counts = new Map(); + for (const wfId of workflowIds) { + counts.set(wfId, (counts.get(wfId) ?? 0) + 1); + } + return counts; +} + +/** Checks that `tile` is a settled `SCENE` tile whose `Uc` clips include `expectedCounts`. */ +function sceneClipsContain( + tile: FlowTile | undefined, + minLength: number, + expectedCounts: ReadonlyMap, + expectedSlice?: { start: number; workflows: readonly string[] }, +): boolean { + if (!tile || isTrashedTile(tile) || tile.isPending === true) return false; + if (String(tile.type ?? "").toUpperCase() !== "SCENE") return false; + const clipWorkflows = sceneContents(tile) + .clips.map((clip) => String(clip?.workflowId ?? "").trim()) + .filter(Boolean); + if (clipWorkflows.length < minLength) return false; + const actualCounts = countWorkflows(clipWorkflows); + for (const [wfId, needed] of expectedCounts.entries()) { + if ((actualCounts.get(wfId) ?? 0) < needed) return false; + } + if (expectedSlice && clipWorkflows.length === minLength) { + const { start, workflows } = expectedSlice; + for (let i = 0; i < workflows.length; i++) { + if (clipWorkflows[start + i] !== workflows[i]) return false; + } + } + return true; +} + +/** Resolves one requested asset ID to a non-trashed `VIDEO` tile in `tiles`. */ +function lookupTileForClip( + tiles: Map, + rawId: string, +): { ok: true; tile: FlowTile } | { ok: false; error: string } { + const clipRef = !tiles.has(rawId) ? splitSceneClipId(rawId) : null; + const lookupKey = clipRef ? clipRef.workflowId : rawId; + if (clipRef) { + const sourceScene = tiles.get(clipRef.sceneId); + if ( + !sourceScene || + isTrashedTile(sourceScene) || + String(sourceScene.type ?? "").toUpperCase() !== "SCENE" || + !sceneContents(sourceScene).clips.some( + (clip) => String(clip?.workflowId ?? "") === lookupKey, + ) + ) { + return { ok: false, error: `asset_not_found:${rawId}` }; + } + } + + let matched = tiles.get(lookupKey); + if (!matched || isTrashedTile(matched)) { + matched = undefined; + for (const candidate of tiles.values()) { + if ( + candidate && + !isTrashedTile(candidate) && + (String(candidate.workflowId ?? "") === lookupKey || + String(candidate.id ?? "") === lookupKey) + ) { + matched = candidate; + break; + } + } + } + if (!matched || isTrashedTile(matched)) { + return { ok: false, error: `asset_not_found:${rawId}` }; + } + const tileType = String(matched.type ?? "").toUpperCase(); + if (tileType !== "VIDEO") { + return { ok: false, error: `asset_not_video:${rawId}:${tileType || "UNKNOWN"}` }; + } + if (matched.isPending === true) { + return { ok: false, error: `video_asset_pending:${rawId}` }; + } + return { ok: true, tile: matched }; +} + +/** Validates that every ID in `assetIds` resolves to a `VIDEO` workflow ID. */ +function resolveVerifiedVideoWorkflows( + tiles: Map, + assetIds: readonly string[], +): { ok: true; workflowIds: string[] } | { ok: false; error: string } { + const workflowIds: string[] = []; + for (const raw of assetIds) { + const trimmed = String(raw ?? "").trim(); + if (!trimmed) { + return { ok: false, error: "empty_asset_id" }; + } + const found = lookupTileForClip(tiles, trimmed); + if (!found.ok) return found; + const wfId = String(found.tile.workflowId || found.tile.id || "").trim(); + if (!wfId) { + return { ok: false, error: `video_workflow_id_missing:${trimmed}` }; + } + workflowIds.push(wfId); + } + return { ok: true, workflowIds }; +} + /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { if (!activeProjectStoreFormat()) { @@ -30,17 +138,43 @@ 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 = resolveVerifiedVideoWorkflows(tileMap, assetIds); + if (!resolved.ok) return resolved; + const { workflowIds } = resolved; + + const created = await createScene(helper, getMap, workflowIds); if (!created?.ok || !created.id) { return created || { ok: false, error: "created_scene_id_not_found" }; } + + const expectedCounts = countWorkflows(workflowIds); + const store = activeProjectStore(); + let confirmed = false; + for (let attempt = 0; attempt < 20; attempt++) { + const freshTiles = store + ? await refreshProjectStore(store).catch(() => null) + : getMap(); + if ( + freshTiles instanceof Map && + sceneClipsContain(freshTiles.get(created.id), workflowIds.length, expectedCounts, { + start: 0, + workflows: workflowIds, + }) + ) { + confirmed = true; + break; + } + await delay(250); + } + if (!confirmed) { + return { ok: false, error: "created_scene_clips_not_confirmed" }; + } + if (req?.name && helper.rename) { try { await helper.rename(created.id, String(req.name)); @@ -67,41 +201,75 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } - let callbackErr: unknown = null; + const sceneTile = tileMap.get(sceneId); + if (!sceneTile || isTrashedTile(sceneTile)) { + return { ok: false, error: `scene_not_found:${sceneId}` }; + } + const sceneType = String(sceneTile.type ?? "").toUpperCase(); + if (sceneType !== "SCENE") { + return { ok: false, error: `tile_not_scene:${sceneId}:${sceneType || "UNKNOWN"}` }; + } + if (sceneTile.isPending === true) { + return { ok: false, error: `scene_pending:${sceneId}` }; + } + + const resolved = resolveVerifiedVideoWorkflows(tileMap, assetIds); + if (!resolved.ok) return resolved; + const { workflowIds } = resolved; + + const store = activeProjectStore(); + if (!store) { + return { ok: false, error: "store_not_bound" }; + } + + const beforeWorkflows = sceneContents(sceneTile) + .clips.map((clip) => String(clip?.workflowId ?? "").trim()) + .filter(Boolean); + const insertPos = + typeof req.position === "number" && Number.isFinite(req.position) + ? Math.max(0, Math.min(Math.trunc(req.position), beforeWorkflows.length)) + : beforeWorkflows.length; + const expectedTotal = beforeWorkflows.length + workflowIds.length; + const expectedCounts = countWorkflows([...beforeWorkflows, ...workflowIds]); + + let submitErr: unknown = null; + const recordError = (err: unknown): void => { + submitErr ??= err; + }; const completion = { resolve: () => {}, - reject: (err: unknown) => { - callbackErr ??= err; - }, + reject: recordError, }; - const workflowIds = resolveWfIds(assetIds); - try { - await helper.mutate({ + const confirmedTiles = await mutateAndVerify( + store, + { type: "add_workflows_to_scene", Lc: sceneId, Ic: sceneId, rg: workflowIds, YWa: workflowIds, - position: typeof req.position === "number" ? req.position : undefined, + position: insertPos, Mh: undefined, Eh: undefined, De: completion, ve: completion, - }); - } catch (err) { - return { - ok: false, - error: err instanceof Error ? err.message : String(err ?? "add_workflows_failed"), - }; - } - if (callbackErr) { - return { - ok: false, - error: callbackErr instanceof Error ? callbackErr.message : String(callbackErr), - }; + }, + (freshTiles) => + sceneClipsContain(freshTiles.get(sceneId), expectedTotal, expectedCounts, { + start: insertPos, + workflows: workflowIds, + }), + recordError, + ); + if (!confirmedTiles) { + const rawMessage = submitErr + ? submitErr instanceof Error + ? submitErr.message + : String(submitErr) + : ""; + return { ok: false, error: rawMessage || "add_clips_not_confirmed" }; } - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; + return { ok: true, scene_id: sceneId, added: workflowIds.length }; } return { ok: false, error: `unknown_scene_action:${action}` }; diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..e051c52 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -1,11 +1,89 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Read clips and workflow history from the native scene tile. +// Read clips, workflow history, and verified scene builder state. -import { readOwn } from "./angular"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; -import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +import { findRouter, readOwn, resolveLView } from "./angular"; +import { findMediaContainer, isTrashedTile, legacyMedia, parentCollectionId } from "./dom"; +import { frontendBuild, readBuildLabel, snapshotFormat } from "./frontend_builds"; +import type { FlowMediaPayload, FlowTile, SceneClipItem, StoreProbeCheck } from "./types"; + +/** Parsed scene ID and clip workflow ID from a `:` clip asset ID. */ +export interface SceneClipId { + /** Identifier of the parent scene tile. */ + sceneId: string; + /** Workflow identifier of the clip inside the scene. */ + workflowId: string; +} + +/** Fields that identify the contents of a scene tile. */ +export interface SceneTileFormat { + /** Clip array on a scene tile. */ + clips: string; + /** Workflow history map on a scene tile. */ + history: string; + /** Start trim timestamp in seconds on a scene clip item (`Ji`). */ + clipStart?: string; + /** End trim timestamp in seconds on a scene clip item (`Ci`). */ + clipEnd?: string; + /** Total clip duration in seconds on a scene clip item (`nc`). */ + clipDuration?: string; +} + +/** Native scene builder and timeline descriptors for clip selection and extend checks. */ +export interface SceneBuilderFormat { + /** Exported `flow-scene-builder` component class (`su`). */ + controller: string; + /** `flow-scene-timeline` component class (`B6`). */ + timeline: string; + /** Scene player service field on the controller (`Gc`). */ + player: string; + /** Readiness method on the scene player (`Dx`). */ + playerReady: string; + /** Writable selected-clip signal on the scene player (`la`). */ + selectedClip: string; + /** Clip list signal on the controller (`Uc`). */ + clips: string; + /** Extend disabled reason signal on the controller (`Yo`). */ + extendDisabledReason: string; + /** Active extend-composing workflow signal on the controller (`TL`). */ + activeExtendClip: string; + /** Prototype method on the controller that exits extend-composing mode (`rE`). */ + exitExtend: string; + /** Models signal query on the controller (`Od`). */ + modelsQuery: string; +} + +/** Portrait `9:16` numeric aspect ratio expected by Flow's `create_scene` mutation. */ +const PORTRAIT_ASPECT_RATIO = 0.5625; + +/** Landscape `16:9` numeric aspect ratio expected by Flow's `create_scene` mutation. */ +const LANDSCAPE_ASPECT_RATIO = 16 / 9; + +/** Splits a `:` clip asset ID into its scene and workflow parts. */ +export function splitSceneClipId(id: string): SceneClipId | null { + const colonIdx = id.indexOf(":"); + if (colonIdx <= 0 || colonIdx >= id.length - 1) return null; + const sceneId = id.slice(0, colonIdx); + const workflowId = id.slice(colonIdx + 1); + if (workflowId.includes(":")) return null; + return { sceneId, workflowId }; +} + +/** Reads verified trim bounds and duration in seconds from one scene clip item. */ +export function readSceneClipBounds( + clip: SceneClipItem | undefined, +): { start: number | null; end: number | null; duration: number | null } { + const format = frontendBuild(readBuildLabel())?.projectStore.scene; + const rawStart = (format?.clipStart ? readOwn(clip, format.clipStart) : undefined) ?? clip?.Ji ?? clip?.Mh; + const rawEnd = (format?.clipEnd ? readOwn(clip, format.clipEnd) : undefined) ?? clip?.Ci ?? clip?.Eh; + const rawDur = (format?.clipDuration ? readOwn(clip, format.clipDuration) : undefined) ?? clip?.nc ?? clip?.rc; + return { + start: typeof rawStart === "number" ? rawStart : null, + end: typeof rawEnd === "number" ? rawEnd : null, + duration: typeof rawDur === "number" ? rawDur : null, + }; +} /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { @@ -20,3 +98,250 @@ export function sceneContents(tile: FlowTile) { history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), }; } + +/** Finds a top-level `VIDEO` tile in `tiles` by tile ID or workflow ID. */ +export function findVideoTileByIdOrWorkflow( + tiles: Map | null | undefined, + idOrWorkflowId: string | undefined, +): FlowTile | undefined { + if (!(tiles instanceof Map) || !idOrWorkflowId) return undefined; + const direct = tiles.get(idOrWorkflowId); + if ( + direct && + !isTrashedTile(direct) && + String(direct.type ?? "").toUpperCase() === "VIDEO" + ) { + return direct; + } + for (const tile of tiles.values()) { + if (!tile || isTrashedTile(tile) || String(tile.type ?? "").toUpperCase() !== "VIDEO") { + continue; + } + if (String(tile.workflowId ?? "") === idOrWorkflowId || String(tile.id ?? "") === idOrWorkflowId) { + return tile; + } + } + return undefined; +} + +/** Reads `0.5625` (`9:16`) or `16 / 9` (`16:9`) from verified `Kb.aspectRatio` or `Bc` dimensions on clip `0`. */ +export function readSceneAspectRatio(clip0: FlowTile | undefined): number { + if (!clip0) return LANDSCAPE_ASPECT_RATIO; + const media = findMediaContainer(clip0)?.[1]; + const rawRatio = media ? readOwn(media, "aspectRatio") : undefined; + if (typeof rawRatio === "number" && Number.isFinite(rawRatio) && rawRatio > 0) { + return rawRatio < 1 ? PORTRAIT_ASPECT_RATIO : LANDSCAPE_ASPECT_RATIO; + } + const dimsField = snapshotFormat()?.media.dimensions; + const rawDims = (media && dimsField ? readOwn(media, dimsField) : undefined) ?? legacyMedia(media)?.tc; + const width = typeof readOwn(rawDims, "width") === "number" + ? (readOwn(rawDims, "width") as number) + : clip0.width; + const height = typeof readOwn(rawDims, "height") === "number" + ? (readOwn(rawDims, "height") as number) + : clip0.height; + if (typeof width === "number" && width > 0 && typeof height === "number" && height > 0) { + return width < height ? PORTRAIT_ASPECT_RATIO : LANDSCAPE_ASPECT_RATIO; + } + return LANDSCAPE_ASPECT_RATIO; +} + +/** Reads the verified `Dc` collection ID on clip `0` when present. */ +export function readSceneCollectionId(clip0: FlowTile | undefined): string | undefined { + if (!clip0) return undefined; + const field = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCollection; + const mapped = field ? readOwn(clip0, field) : undefined; + if (typeof mapped === "string" && mapped) return mapped; + const fallback = parentCollectionId(clip0) ?? (typeof clip0.Fc === "string" ? clip0.Fc : null); + return fallback || undefined; +} + +/** Finds the timeline class in the global namespace or in the controller's Ivy dependencies. */ +function resolveTimelineClass( + namespace: unknown, + controllerClass: unknown, + timelineName: string, +): Function | null { + const direct = readOwn(namespace, timelineName); + if (typeof direct === "function") return direct; + const cmp = readOwn(controllerClass, "Ma") ?? readOwn(controllerClass, "ɵcmp"); + const rawDeps = readOwn(cmp, "dependencies"); + const deps: unknown = typeof rawDeps === "function" ? rawDeps.call(cmp) : rawDeps; + if (!Array.isArray(deps)) return null; + for (const dep of deps) { + if (typeof dep === "function" && dep.name === timelineName) return dep; + } + return null; +} + +/** Escapes regex metacharacters in `value`. */ +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** Returns true when `fnSource` accesses property `exportName` as an exact identifier. */ +function referencesExport(fnSource: string, exportName: string): boolean { + const escaped = escapeRegExp(exportName); + return new RegExp(`(?:\\.|\\[\\s*["'])${escaped}(?:["']\\s*\\]|(?![\\w$]))`).test(fnSource); +} + +/** Returns true when `controllerClass` defines `member` on its prototype or assigns `this.`. */ +function controllerDefinesMember( + controllerClass: Function, + classSource: string, + member: string, +): boolean { + if (typeof readOwn(controllerClass.prototype, member) === "function") return true; + const escaped = escapeRegExp(member); + return new RegExp(`\\bthis\\.${escaped}(?![\\w$])`).test(classSource); +} + +/** Checks whether the Angular router registers a lazy `scene/:sceneId` loader for `controllerName`. */ +function hasDeferredSceneRoute(routes: unknown, controllerName: string): boolean { + if (!Array.isArray(routes)) return false; + for (const route of routes) { + if (!route || typeof route !== "object") continue; + const path = readOwn(route, "path"); + if (typeof path === "string" && path.includes("scene/")) { + for (const loaderKey of ["mh", "loadComponent"]) { + const loader = readOwn(route, loaderKey); + if (typeof loader === "function" && referencesExport(Function.prototype.toString.call(loader), controllerName)) { + return true; + } + } + } + if (hasDeferredSceneRoute(readOwn(route, "children"), controllerName)) return true; + } + return false; +} + +/** Resolves the live `su` scene builder controller from `` via `resolveLView`. */ +export function resolveSceneBuilderController( + host: Element | null = document.querySelector("flow-scene-builder"), +): { controller: Record; format: SceneBuilderFormat } | null { + const format = frontendBuild(readBuildLabel())?.projectStore.sceneBuilder; + if (!format || !host) return null; + const view = resolveLView(host); + if (!Array.isArray(view)) return null; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const controllerClass = readOwn(namespace, format.controller); + for (const slot of view) { + if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + if (typeof controllerClass === "function" && slot instanceof controllerClass) { + return { controller: slot as Record, format }; + } + const player = readOwn(slot, format.player); + const modelsQuery = readOwn(slot, format.modelsQuery); + if ( + player && + typeof player === "object" && + typeof readOwn(player, format.playerReady) === "function" && + typeof readOwn(slot, format.clips) === "function" && + typeof readOwn(slot, format.extendDisabledReason) === "function" && + typeof readOwn(slot, format.activeExtendClip) === "function" && + typeof readOwn(slot, format.exitExtend) === "function" && + Boolean(modelsQuery && typeof readOwn(modelsQuery, "isPending") === "function") + ) { + return { controller: slot as Record, format }; + } + } + return null; +} + +/** Verifies the `sceneBuilder` descriptors of `build` for `probeStore()`. */ +export function sceneBuilderChecks(build: string | null): StoreProbeCheck[] { + const format = frontendBuild(build)?.projectStore.sceneBuilder; + if (!format) return []; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const controllerClass = readOwn(namespace, format.controller); + const host = document.querySelector("flow-scene-builder"); + + if (typeof controllerClass !== "function") { + const deferred = !host && hasDeferredSceneRoute(readOwn(findRouter(), "config"), format.controller); + return [{ + name: "scene_builder", + ok: deferred, + detail: deferred + ? `deferred route -> ${format.controller}` + : `missing export ${format.controller}`, + }]; + } + + const timelineClass = resolveTimelineClass(namespace, controllerClass, format.timeline); + const timelineCmp = timelineClass ? (readOwn(timelineClass, "Ma") ?? readOwn(timelineClass, "ɵcmp")) : undefined; + const timelineInputs = readOwn(timelineCmp, "inputs"); + const publicDisabledInput = readOwn(timelineInputs, "extendDisabledReason"); + const inputsOk = + !timelineInputs || + typeof timelineInputs !== "object" || + readOwn(timelineInputs, format.extendDisabledReason) !== undefined || + (Array.isArray(publicDisabledInput) && publicDisabledInput[0] === format.extendDisabledReason) || + publicDisabledInput === format.extendDisabledReason; + if (!timelineClass || !inputsOk) { + return [{ + name: "scene_builder", + ok: false, + detail: !timelineClass + ? `missing timeline ${format.timeline}` + : `missing input ${format.extendDisabledReason} on ${format.timeline}`, + }]; + } + + const classSource = Function.prototype.toString.call(controllerClass); + if (typeof readOwn(controllerClass.prototype, format.exitExtend) !== "function") { + return [{ + name: "scene_builder", + ok: false, + detail: `missing method ${format.exitExtend} on ${format.controller}`, + }]; + } + const requiredFields = [ + format.player, + format.clips, + format.extendDisabledReason, + format.activeExtendClip, + format.modelsQuery, + ]; + const missingField = requiredFields.find( + (field) => !controllerDefinesMember(controllerClass, classSource, field), + ); + if (missingField) { + return [{ + name: "scene_builder", + ok: false, + detail: `missing member ${missingField} on ${format.controller}`, + }]; + } + + if (!host) { + return [{ + name: "scene_builder", + ok: true, + detail: `${format.controller}+${format.timeline} verified`, + }]; + } + + const resolved = resolveSceneBuilderController(host); + const controller = resolved?.controller; + const player = controller ? readOwn(controller, format.player) : undefined; + const selectedSignal = player ? readOwn(player, format.selectedClip) : undefined; + const modelsQuery = controller ? readOwn(controller, format.modelsQuery) : undefined; + const liveOk = Boolean( + controller && + player && + typeof player === "object" && + typeof readOwn(player, format.playerReady) === "function" && + typeof readOwn(selectedSignal, "set") === "function" && + typeof readOwn(controller, format.clips) === "function" && + typeof readOwn(controller, format.extendDisabledReason) === "function" && + typeof readOwn(controller, format.activeExtendClip) === "function" && + typeof readOwn(controller, format.exitExtend) === "function" && + modelsQuery && + typeof readOwn(modelsQuery, "isPending") === "function", + ); + return [{ + name: "scene_builder", + ok: liveOk, + detail: liveOk ? "live controller verified" : "live controller signals missing", + }]; +} diff --git a/ts/video_ops.ts b/ts/video_ops.ts index 0cc0e8c..e0ff751 100644 --- a/ts/video_ops.ts +++ b/ts/video_ops.ts @@ -3,13 +3,29 @@ // Trim Flow videos and drive the scene builder extend workflow. -import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, withLViewMapCapture } from "./angular"; +import { + buildProjectUrl, + createScene, + findRouter, + isNgLViewMap, + navigateSpa, + readAngularTooltip, + readOwn, + withLViewMapCapture, +} from "./angular"; import { findComposerWarning } from "./composer"; -import { delay, elText, hoverProbe, isDisabledProp, isVisibleEnabled, legacyTile, videoTrimBounds } from "./dom"; +import { delay, elText, hoverProbe, isDisabledProp, isTrashedTile, isVisibleEnabled, legacyMedia, legacyTile, videoTrimBounds } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; +import { + findVideoTileByIdOrWorkflow, + readSceneClipBounds, + resolveSceneBuilderController, + sceneContents, + splitSceneClipId, +} from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { FlowTile, VideoOpRequest } from "./types"; +import type { FlowTile, SceneClipItem, VideoOpRequest } from "./types"; /** Checks whether an observed start trim bound matches the requested start time. */ function startBoundMatches( @@ -26,7 +42,6 @@ function startBoundMatches( function endBoundMatches( actual: number | null, expected: number | null, - before: number | null, duration: number | null, ): boolean { if (expected === null) { @@ -35,13 +50,29 @@ function endBoundMatches( typeof actual === "number" && typeof duration === "number" && duration > 0 && - (before === null || Math.abs(before - duration) > 0.01) && Math.abs(actual - duration) <= 0.01 ); } return typeof actual === "number" && Math.abs(actual - expected) <= 0.01; } +/** Finds the last active clip in `scene` whose `workflowId` equals `workflowId`. */ +function findLastSceneClip( + scene: FlowTile | undefined, + workflowId: string, +): SceneClipItem | undefined { + if (!scene || isTrashedTile(scene) || String(scene.type ?? "").toUpperCase() !== "SCENE") { + return undefined; + } + const { clips } = sceneContents(scene); + for (let i = clips.length - 1; i >= 0; i -= 1) { + if (String(clips[i]?.workflowId ?? "") === workflowId) { + return clips[i]; + } + } + return undefined; +} + /** Trims video clip timestamps or orchestrates scene-builder video extension. */ export async function videoOp(req: VideoOpRequest): Promise { const helper = runtimeState.store; @@ -65,10 +96,98 @@ export async function videoOp(req: VideoOpRequest): Promise { return { ok: false, error: "store_not_bound" }; } const id = String(req?.asset_id || "").trim(); + const startSec = + typeof req.start_seconds === "number" ? req.start_seconds : null; + const endSec = typeof req.end_seconds === "number" ? req.end_seconds : null; + const clipRef = splitSceneClipId(id); + if (clipRef) { + const rawScene = tileMap.get(clipRef.sceneId); + const clip = findLastSceneClip(rawScene, clipRef.workflowId); + if (!rawScene || !clip) { + return { ok: false, error: `video_asset_not_found:${id}` }; + } + const mediaId = String(clip.primaryMediaId ?? "").trim(); + if (!mediaId) { + return { ok: false, error: `video_media_id_missing:${id}` }; + } + const initialBounds = readSceneClipBounds(clip); + const hist = sceneContents(rawScene).history.get(clipRef.workflowId); + const rawHistMedia = Array.isArray(hist) + ? hist.find((m) => String(m?.id ?? "") === mediaId) ?? hist[0] + : undefined; + const histMedia = legacyMedia(rawHistMedia); + const topTile = legacyTile(findVideoTileByIdOrWorkflow(tileMap, clipRef.workflowId)); + const duration = + initialBounds.duration ?? + (typeof histMedia?.durationSeconds === "number" + ? histMedia.durationSeconds + : typeof histMedia?.duration === "number" + ? histMedia.duration + : typeof histMedia?.Lf === "number" + ? histMedia.Lf + : typeof topTile?.durationSeconds === "number" + ? topTile.durationSeconds + : typeof topTile?.duration === "number" + ? topTile.duration + : typeof topTile?.Fb?.Lf === "number" + ? topTile.Fb.Lf + : null); + const resolvedEnd = endSec ?? duration; + const change: Record = { + type: "set_scene_clip_primary_media", + workflowId: clipRef.workflowId, + primaryMediaId: mediaId, + Ji: startSec ?? 0, + }; + if (typeof resolvedEnd === "number") { + change.Ci = resolvedEnd; + } + await helper.mutate({ + type: "single_tile", + Xc: clipRef.sceneId, + Uc: clipRef.sceneId, + Ve: change, + }); + const matchesSceneClip = ( + cand: { start: number | null; end: number | null; duration: number | null }, + ): boolean => + startBoundMatches(cand.start, startSec) && + endBoundMatches(cand.end, endSec, cand.duration ?? duration); + await delay(300); + for (let i = 0; i < 30; i++) { + const currentClip = findLastSceneClip( + getMap()?.get(clipRef.sceneId), + clipRef.workflowId, + ); + if (currentClip) { + const bounds = readSceneClipBounds(currentClip); + if (matchesSceneClip(bounds)) { + await delay(200); + const settledClip = findLastSceneClip( + getMap()?.get(clipRef.sceneId), + clipRef.workflowId, + ); + const settled = readSceneClipBounds(settledClip); + if (settledClip && matchesSceneClip(settled)) { + return { + ok: true, + confirmed: true, + asset_id: id, + media_id: mediaId, + start_seconds: settled.start, + end_seconds: settled.end, + }; + } + } + } + await delay(200); + } + return { ok: false, error: "trim_not_confirmed" }; + } + const rawTile = tileMap.get(id); if (!rawTile) return { ok: false, error: `video_asset_not_found:${id}` }; const tile = legacyTile(rawTile); - const before = videoTrimBounds(tile); const mediaId = String( tile?.primaryMediaId || tile?.Fb?.id || @@ -77,9 +196,6 @@ export async function videoOp(req: VideoOpRequest): Promise { tile?.mediaId || id, ); - const startSec = - typeof req.start_seconds === "number" ? req.start_seconds : null; - const endSec = typeof req.end_seconds === "number" ? req.end_seconds : null; await helper.mutate({ type: "single_tile", Xc: String(tile?.id ?? id), @@ -111,7 +227,7 @@ export async function videoOp(req: VideoOpRequest): Promise { cand: { start: number | null; end: number | null }, ): boolean => startBoundMatches(cand.start, startSec) && - endBoundMatches(cand.end, endSec, before.end, duration); + endBoundMatches(cand.end, endSec, duration); await delay(300); for (let i = 0; i < 30; i++) { const current = getMap()?.get(id); @@ -138,9 +254,21 @@ 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]; - if (!activeScene || (req.scene_id && activeScene !== req.scene_id)) { + const rawId = String(req?.asset_id || "").trim(); + const clipRef = splitSceneClipId(rawId); + const impliedSceneId = clipRef ? clipRef.sceneId : null; + const rawTargetId = clipRef ? clipRef.workflowId : rawId; + let sceneId = req?.scene_id ? String(req.scene_id).trim() : impliedSceneId; + const matchedTile = findVideoTileByIdOrWorkflow(tileMap, rawTargetId); + const targetWfId = matchedTile + ? String(matchedTile.workflowId || matchedTile.id || rawTargetId) + : rawTargetId; + + // When a scene is already open and no different scene_id is requested, + // prepare_extend inspects the open scene and fails with scene_clip_not_found + // if targetWfId is absent rather than reusing that scene for an unrelated video. + const activeScene = /\/scene\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; + if (!activeScene || (sceneId && activeScene !== sceneId)) { if (!activeProjectStoreFormat()) { clearStore(); return { ok: false, error: "unsupported_front_end" }; @@ -155,10 +283,14 @@ export async function videoOp(req: VideoOpRequest): Promise { if (!(tileMap instanceof Map) || !helper.mutate) { return { ok: false, error: "store_not_bound" }; } - let sceneId = req?.scene_id ? String(req.scene_id).trim() : null; if (!sceneId) { - const wfId = String(tileMap.get(id)?.workflowId || id); - const created = await createScene(helper, getMap, [wfId]); + if (!rawTargetId) { + return { ok: false, error: "video_asset_required" }; + } + if (!matchedTile) { + return { ok: false, error: `video_asset_not_found:${rawTargetId}` }; + } + const created = await createScene(helper, getMap, [targetWfId]); if (!created?.ok || !created.id) { return { ok: false, error: created.error ?? "failed_to_create_scene_for_extend" }; } @@ -190,6 +322,7 @@ export async function videoOp(req: VideoOpRequest): Promise { ok: false, need_navigate: buildProjectUrl(pid, ["scene", sceneId]), scene_id: sceneId, + workflow_id: targetWfId || undefined, }; } else { return { @@ -198,17 +331,152 @@ export async function videoOp(req: VideoOpRequest): Promise { scene_id: sceneId, }; } + } else { + sceneId ||= activeScene; + } + + let capturedMap = false; + let resolved = resolveSceneBuilderController(); + for (let i = 0; i < 80 && !resolved; i++) { + const host = document.querySelector("flow-scene-builder"); + if (host && !(runtimeState.ngLViewMap instanceof Map) && !capturedMap) { + capturedMap = true; + await withLViewMapCapture( + async () => { + const targets = Array.from( + document.querySelectorAll( + "flow-scene-builder, flow-scene-timeline, button[aria-label], [mattooltip]", + ), + ); + await hoverProbe(targets.slice(0, 8), 25); + }, + (map) => { + if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(map)) { + runtimeState.ngLViewMap = map; + } + }, + ); + } + resolved = resolveSceneBuilderController(); + if (resolved) break; + await delay(100); + } + if (!resolved) { + return { ok: false, error: "scene_builder_controller_not_found" }; + } + + let playerReady = false; + for (let i = 0; i < 120; i++) { + resolved = resolveSceneBuilderController() ?? resolved; + const player = readOwn(resolved.controller, resolved.format.player); + const readyFn = readOwn(player, resolved.format.playerReady); + if (typeof readyFn === "function" && Boolean(readyFn.call(player))) { + playerReady = true; + break; + } + await delay(100); + } + if (!playerReady) { + return { ok: false, error: "scene_player_not_ready" }; } for (let i = 0; i < 40; i++) { - if ( - document.querySelector( - "flow-scene-timeline, .is-extend-mode, .extend-composing, button[aria-label='Add clip']", - ) - ) { + if (document.querySelector("flow-scene-timeline")) break; + await delay(100); + } + + resolved = resolveSceneBuilderController() ?? resolved; + const { controller, format: sbFormat } = resolved; + const clipsFn = readOwn(controller, sbFormat.clips); + const rawClips: unknown = typeof clipsFn === "function" ? clipsFn.call(controller) : null; + const clips = Array.isArray(rawClips) ? rawClips : []; + const targetClip = targetWfId + ? clips.find((clip) => { + const wf = String(readOwn(clip, "workflowId") ?? ""); + return ( + wf === targetWfId || + (rawTargetId !== "" && + (wf === rawTargetId || + String(readOwn(clip, "id") ?? "") === rawTargetId || + String(readOwn(clip, "primaryMediaId") ?? "") === rawTargetId)) + ); + }) + : clips[clips.length - 1]; + if (!targetClip) { + return { + ok: false, + error: targetWfId ? `scene_clip_not_found:${targetWfId}` : "scene_has_no_clips", + }; + } + const selectedWfId = String(readOwn(targetClip, "workflowId") ?? targetWfId); + const clipIndex = clips.indexOf(targetClip); + const activeExtendFn = readOwn(controller, sbFormat.activeExtendClip); + const exitExtendFn = readOwn(controller, sbFormat.exitExtend); + const modelsQuery = readOwn(controller, sbFormat.modelsQuery); + const isModelsPending = readOwn(modelsQuery, "isPending"); + if ( + typeof activeExtendFn !== "function" || + typeof exitExtendFn !== "function" || + typeof isModelsPending !== "function" + ) { + return { ok: false, error: "scene_builder_signals_missing" }; + } + const activeExtendWf: unknown = activeExtendFn.call(controller); + if ( + typeof activeExtendWf === "string" && + activeExtendWf && + activeExtendWf !== selectedWfId + ) { + exitExtendFn.call(controller); + } + + const player = readOwn(controller, sbFormat.player); + const selectedSignal = readOwn(player, sbFormat.selectedClip); + const setSelected = readOwn(selectedSignal, "set"); + if (typeof setSelected !== "function") { + return { ok: false, error: "scene_selected_clip_signal_missing" }; + } + setSelected.call(selectedSignal, selectedWfId); + await delay(50); + + let selectedClipEl: Element | null = null; + for (let i = 0; i < 25; i++) { + const signalMatches = + typeof selectedSignal !== "function" || + String(selectedSignal.call(player) ?? "") === selectedWfId; + const timelineClips = Array.from( + document.querySelectorAll( + "flow-scene-timeline .clip:not(.extend-composing):not(.pending-placeholder)", + ), + ); + const candidateEl = + timelineClips.length === clips.length && clipIndex >= 0 + ? timelineClips[clipIndex] + : document.querySelector("flow-scene-timeline .clip.selected"); + if (signalMatches && candidateEl?.classList.contains("selected")) { + selectedClipEl = candidateEl; break; } + setSelected.call(selectedSignal, selectedWfId); + await delay(80); + } + if (!selectedClipEl) { + return { ok: false, error: `scene_clip_selection_not_confirmed:${selectedWfId}` }; + } + + const readDisabledReason = (): string | null => { + const fn = readOwn(controller, sbFormat.extendDisabledReason); + const value: unknown = typeof fn === "function" ? fn.call(controller) : null; + return typeof value === "string" && value ? value : null; + }; + let disabledReason = readDisabledReason(); + for (let i = 0; i < 15 && disabledReason === "no-extension-model"; i++) { + if (!Boolean(isModelsPending.call(modelsQuery))) break; await delay(100); + disabledReason = readDisabledReason(); + } + if (disabledReason) { + return { ok: false, error: `extend_option_disabled:${disabledReason}` }; } const inExtendMode = (): boolean => @@ -240,30 +508,19 @@ 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); - } - } + const extendBtn = findExtendBtn(); if (extendBtn) { extendBtn.click(); await delay(300); } 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"]', - ); + const addClipBtn = + selectedClipEl.querySelector( + 'button[aria-label="Add clip"], .add-clip-button', + ) || + document.querySelector( + 'flow-scene-timeline .clip.selected button[aria-label="Add clip"], flow-scene-timeline .clip.selected .add-clip-button, flow-scene-timeline button[aria-label="Add clip"], flow-scene-timeline .add-clip-button, flow-scene-builder button[aria-label="Add clip"], button[aria-label="Add clip"]', + ); if (isVisibleEnabled(addClipBtn)) { if (!(runtimeState.ngLViewMap instanceof Map)) { await withLViewMapCapture(async () => { @@ -289,8 +546,8 @@ export async function videoOp(req: VideoOpRequest): Promise { return false; } return ( - /^(?:extend|prompt to extend)$/i.test(aria) || - /^(?:extend|prompt to extend)$/i.test(raw) || + /^(?:extend(?:\s+with\b.*)?|prompt to extend)$/i.test(aria) || + /^(?:extend(?:\s+with\b.*)?|prompt to extend)$/i.test(raw) || Boolean(el.closest(".extend-clip-option")) ); }); @@ -298,6 +555,10 @@ export async function videoOp(req: VideoOpRequest): Promise { const innerBtn = extendOpt.querySelector("button, [role='menuitem']") || extendOpt; if (!isVisibleEnabled(innerBtn) || !isVisibleEnabled(extendOpt)) { + const signalReason = readDisabledReason(); + if (signalReason) { + return { ok: false, error: `extend_option_disabled:${signalReason}` }; + } if (!(runtimeState.ngLViewMap instanceof Map)) { await withLViewMapCapture(async () => { await hoverProbe([extendOpt, innerBtn], 40); @@ -459,7 +720,12 @@ 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: sceneId, + workflow_id: selectedWfId, + }; } if (action === "poll_extend") {