From 3992fe1520208240947abd76f39e3f13247b9e59 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:11:28 +0000 Subject: [PATCH 1/5] fix(flow): check newest formats first and add page fallbacks - Check verified store, preview, voice, and scene formats newest first. - Use the newest field layout for tile, trim, and scene mutations. - Enforce a 10-second timeout when scene clip additions wait to finish. - Fall back to the page upload menu when direct media upload fails. - Run tile rename, tile trash, and collection list without a store. - Locate media, character, scene, and collection tiles in the grid. - Manage collections through page controls when store writes fail. - Save character personality notes in the editor when store edits fail. - Require a verified build for Agent chat, files, and settings. --- src/agent.rs | 35 ++- src/assets.rs | 140 +++++++--- src/character_bio.rs | 156 ++++++++++- src/characters.rs | 65 +++-- src/collection_page.rs | 516 +++++++++++++++++++++++++++++++++++ src/collections.rs | 130 +++++++-- src/main.rs | 1 + src/tile_menu.rs | 236 ++++++++++++---- src/upload.rs | 241 +++++++++++++--- ts/agent_chat.ts | 13 +- ts/angular.ts | 8 +- ts/character_bio.ts | 107 +++++++- ts/character_extra.ts | 38 ++- ts/character_media.ts | 87 +++--- ts/frontend_builds.ts | 83 +++++- ts/frontend_compatibility.ts | 9 +- ts/index.ts | 3 +- ts/page_view.ts | 57 +++- ts/scene_ops.ts | 67 ++++- ts/scene_tiles.ts | 24 +- ts/tile_dom.ts | 408 +++++++++++++++++++++++++-- ts/types.ts | 14 +- 22 files changed, 2138 insertions(+), 300 deletions(-) create mode 100644 src/collection_page.rs diff --git a/src/agent.rs b/src/agent.rs index ffa450c..9e5fac2 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -237,6 +237,22 @@ impl AgentParams { | AgentAction::GetTurn ) } + + /// Returns the front-end compatibility gate that this request requires. + fn compatibility_operation(&self) -> &'static str { + match self.action { + AgentAction::GetSettings | AgentAction::UpdateSettings => "agent_settings", + _ if self.files.as_ref().is_some_and(|files| !files.is_empty()) + || self + .asset_ids + .as_ref() + .is_some_and(|asset_ids| !asset_ids.is_empty()) => + { + "agent_attachments" + } + _ => "agent_chat", + } + } } /// Returns true for IDs that can be one Flow URL segment. @@ -292,7 +308,9 @@ impl AgentChat { }); } let agent = state.as_mut().context("Agent page unavailable")?; - agent.open(&request.project_id).await?; + agent + .open(&request.project_id, request.compatibility_operation()) + .await?; let mut args = serde_json::to_value(&request)?; if let Some(fields) = args.as_object_mut() { fields.remove("files"); @@ -362,10 +380,17 @@ impl AgentChat { impl AgentPage { /// Loads the project and binds its Agent service. - async fn open(&mut self, project_id: &str) -> Result<()> { + async fn open(&mut self, project_id: &str, operation: &str) -> Result<()> { if self.project_id == project_id && self.page.call("agentBound", json!([project_id])).await? == Value::Bool(true) { + let status = self + .page + .call("agentStatus", json!([project_id, operation])) + .await?; + if status["error"].as_str() == Some("unsupported_front_end") { + checked_runtime_result(status)?; + } return Ok(()); } if !self.project_id.is_empty() { @@ -380,7 +405,11 @@ impl AgentPage { self.project_id.clear(); let mut last = Value::Null; for _ in 0..BIND_ATTEMPTS { - if let Ok(status) = self.page.call("agentStatus", json!([project_id])).await { + if let Ok(status) = self + .page + .call("agentStatus", json!([project_id, operation])) + .await + { if status["ok"].as_bool() == Some(true) { if self.page.bind_agent(project_id).await? { self.project_id = project_id.to_string(); diff --git a/src/assets.rs b/src/assets.rs index d2ace78..303646f 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -14,6 +14,7 @@ use std::collections::HashMap; use tokio::sync::broadcast::error::RecvError; use tokio::time::{Duration, Instant}; +use crate::collection_page::{delete_collection_through_page, rename_collection_through_page}; use crate::collections::{FlowCollection, find_collection}; use crate::db::FlowDb; use crate::download::eval_resolve_media_url; @@ -371,49 +372,67 @@ pub(crate) async fn list_assets( Ok(filtered) } -/// Checks whether the asset snapshot shows the requested name. +/// Checks whether the project snapshot shows the requested name for an asset or collection. fn snapshot_has_renamed(snap: &Value, id: &str, name: &str) -> bool { - snap.get("assets") - .and_then(Value::as_array) - .is_some_and(|assets| { - assets.iter().any(|item| { - item.get("id").and_then(Value::as_str) == Some(id) - && item.get("name").and_then(Value::as_str) == Some(name) + ["assets", "collections"].into_iter().any(|section| { + snap.get(section) + .and_then(Value::as_array) + .is_some_and(|items| { + items.iter().any(|item| { + item.get("id").and_then(Value::as_str) == Some(id) + && item.get("name").and_then(Value::as_str) == Some(name) + }) }) - }) + }) } -/// Renames collections through the collection store and other tiles through the page or store. +/// Renames media, character, scene, and collection tiles without requiring an upfront direct store session. pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec) -> Result { - let collections = ProjectStoreSession::open(engine).await?; + let mut store_lock = Some(engine.lock_project_store().await); + ensure_flow_store(engine).await?; let total = items.len(); let mut renamed = Vec::new(); let mut failed = Vec::new(); - let mut asset_store_ready = false; 'items: for (idx, entry) in items.into_iter().enumerate() { - match collections.is_collection(&entry.id).await { - Ok(false) => {} - Ok(true) => { - match collections.rename(&entry.id, &entry.name).await { - Ok(result) => renamed.push(json!({ - "id": entry.id, "name": entry.name, "method": result["method"] - })), - Err(err) => failed.push(rename_error(&entry, &err)), + if store_lock.is_none() { + store_lock = Some(engine.lock_project_store().await); + ensure_flow_store(engine).await?; + } + let state = tile_state(engine, &entry.id).await; + if state.is_present() && state.kind == "collection" { + match rename_collection_through_page(engine, &entry.id, &entry.name).await { + Ok(result) => { + renamed.push(json!({ + "id": entry.id, + "name": entry.name, + "method": result["method"], + })); + if idx + 1 < total { + tokio::time::sleep(Duration::from_millis(250)).await; + } + continue 'items; + } + Err(page_err) => { + drop(store_lock.take()); + let direct = match ProjectStoreSession::open(engine).await { + Ok(session) => session.rename(&entry.id, &entry.name).await, + Err(_) => Err(page_err), + }; + match direct { + Ok(result) => renamed.push(json!({ + "id": entry.id, + "name": entry.name, + "method": result["method"], + })), + Err(err) => failed.push(rename_error(&entry, &err)), + } + continue 'items; } - continue 'items; - } - Err(err) => { - failed.push(rename_error(&entry, &err)); - continue 'items; } } - if !asset_store_ready { - ensure_flow_store(engine).await?; - asset_store_ready = true; - } // Use the rename control of the page first. The page then builds its own mutation. - if tile_state(engine, &entry.id).await.is_present() + if state.is_present() && matches!( rename_through_menu(engine, &entry.id, &entry.name).await, Ok(true) @@ -511,10 +530,29 @@ fn rename_error(entry: &RenameEntry, err: &anyhow::Error) -> Value { json!({ "id": entry.id, "name": entry.name, "error": format!("{err:#}") }) } -/// Moves an asset to trash through the tile menu or the pinned project store. +/// Deletes a collection through page controls first and falls back to the direct store session. +async fn invoke_trash_collection( + engine: &ChromeEngine, + store_lock: &mut Option>, + id: &str, +) -> Result { + match delete_collection_through_page(engine, id).await { + Ok(result) => Ok(result), + Err(err) if format!("{err:#}").contains("collection_has_child_collections") => Err(err), + Err(page_err) => { + drop(store_lock.take()); + match ProjectStoreSession::open(engine).await { + Ok(session) => session.delete(id).await, + Err(_) => Err(page_err), + } + } + } +} + +/// Moves a non-collection tile to trash through its context menu or a direct store session. async fn invoke_trash_tile( engine: &ChromeEngine, - session: &ProjectStoreSession<'_>, + store_lock: &mut Option>, id: &str, ) -> Result { let menu_error = @@ -531,6 +569,14 @@ async fn invoke_trash_tile( } else { None }; + drop(store_lock.take()); + let session = ProjectStoreSession::open(engine).await.map_err(|err| { + if let Some(menu_err) = &menu_error { + anyhow::anyhow!("{err:#} (menu fallback: {menu_err})") + } else { + err + } + })?; let mut result = session .call("trashAssetOp", json!(id), Some("trash asset")) .await?; @@ -542,32 +588,38 @@ async fn invoke_trash_tile( Ok(result) } -/// Moves a matching asset, character, scene, or collection to trash through the Flow store. +/// Moves a matching asset, character, scene, or collection to trash without requiring an upfront store session. pub(crate) async fn trash_asset( engine: &ChromeEngine, db: &FlowDb, match_str: &str, ) -> Result { - let collections = ProjectStoreSession::open(engine).await?; + let mut store_lock = Some(engine.lock_project_store().await); + let snap = read_snapshot(engine).await?; let query = match_str.trim(); - if collections.is_collection(query).await? { - return collections.delete(query).await; + let collections: Vec = serde_json::from_value( + snap.get("collections") + .cloned() + .unwrap_or_else(|| Value::Array(Vec::new())), + )?; + if let Some(exact_col) = collections.iter().find(|c| c.id == query) { + return invoke_trash_collection(engine, &mut store_lock, &exact_col.id).await; } - let mut tiles = collections - .run_collections(json!({ "action": "assets" })) - .await?; - let assets: Vec = serde_json::from_value(tiles["assets"].take())?; - let Some(asset) = match_asset(&assets, query, true) else { - let summaries: Vec = serde_json::from_value(tiles["collections"].take())?; - let collection = find_collection(&summaries, query, true)? + let assets: Vec = serde_json::from_value( + snap.get("assets") + .cloned() + .unwrap_or_else(|| Value::Array(Vec::new())), + )?; + let Some(asset) = match_asset(&assets, query, true).cloned() else { + let collection = find_collection(&collections, query, true)? .with_context(|| format!("No asset or collection matches '{query}' for flow_trash"))?; - return collections.delete(&collection.id).await; + return invoke_trash_collection(engine, &mut store_lock, &collection.id).await; }; let id = &asset.id; let is_character = asset.kind == "character"; - let res = invoke_trash_tile(engine, &collections, id) + let res = invoke_trash_tile(engine, &mut store_lock, id) .await .map_err(|err| anyhow::anyhow!("Failed to trash '{id}': {err:#}"))?; if is_character { diff --git a/src/character_bio.rs b/src/character_bio.rs index 3aac965..2384667 100644 --- a/src/character_bio.rs +++ b/src/character_bio.rs @@ -1,16 +1,57 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Direct project store operations for character personality notes. +//! Direct project store and character editor operations for personality notes. use anyhow::{Context, Result}; use serde_json::json; -use crate::assets::{FlowAsset, match_asset}; +use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; +use crate::characters::{exit_character_editor, open_character_editor}; use crate::db::FlowDb; -use crate::engine::ChromeEngine; +use crate::engine::{ChromeEngine, checked_runtime_result}; +use crate::project::{ensure_flow_store, ensure_project_workspace_root, project_id_from_url}; use crate::project_store::ProjectStoreSession; +/// Returns true when a direct store error can fall back to the character editor view. +pub(crate) fn is_bio_fallback_eligible(err: &anyhow::Error) -> bool { + let msg = format!("{err:#}"); + if msg.contains("outcome_unknown") { + return false; + } + msg.contains("unsupported_front_end") + || msg.contains("collection_store_not_bound") + || msg.contains("ambiguous_collection_store") + || msg.contains("project_store_changed") + || msg.contains("project_changed") + || msg.contains("character_bio_unreadable") + || msg.contains("Open a Google Flow project") +} + +/// Opens a verified direct store session for character notes, or returns `Ok(None)` when the editor fallback applies. +pub(crate) async fn prepare_bio_store<'a>( + engine: &'a ChromeEngine, + expected_project: Option<&str>, +) -> Result>> { + let check = async { + let store = ProjectStoreSession::open(engine).await?; + anyhow::ensure!( + expected_project == Some(store.project_id()), + "The active project changed before the character update" + ); + store + .call("characterBioOp", json!({ "action": "check" }), None) + .await?; + Ok::, anyhow::Error>(store) + } + .await; + match check { + Ok(store) => Ok(Some(store)), + Err(err) if is_bio_fallback_eligible(&err) => Ok(None), + Err(err) => Err(err), + } +} + /// Saves character notes in the active project and checks the server result. pub(crate) async fn set_character_bio( store: &ProjectStoreSession<'_>, @@ -27,29 +68,114 @@ pub(crate) async fn set_character_bio( Ok(()) } -/// Finds a character for an edit and saves its notes without opening the editor. -pub(crate) async fn edit_character_bio( +/// Tries to save character notes directly; returns `Ok(false)` when the caller must use the editor view. +pub(crate) async fn try_set_character_bio( + store: Option>, + character_id: &str, + bio: &str, +) -> Result { + let Some(store) = store else { + return Ok(false); + }; + match set_character_bio(&store, character_id, bio).await { + Ok(()) => Ok(true), + Err(err) if is_bio_fallback_eligible(&err) => Ok(false), + Err(err) => Err(err), + } +} + +/// Saves and confirms personality notes inside the open `/character/` editor view. +pub(crate) async fn save_character_bio_in_editor(engine: &ChromeEngine, bio: &str) -> Result<()> { + let res = engine + .call_flow_async("characterBioEditorOp", json!([bio])) + .await?; + checked_runtime_result(res)?; + Ok(()) +} + +/// Opens the character editor, saves and confirms personality notes, and returns to the workspace. +async fn edit_character_bio_in_editor( engine: &ChromeEngine, db: &FlowDb, selector: &str, bio: &str, ) -> Result { - let store = ProjectStoreSession::open(engine).await?; - let mut result = store - .call("characterBioOp", json!({ "action": "list" }), None) - .await?; - let assets: Vec = serde_json::from_value(result["characters"].take())?; - let target = match_asset(&assets, selector, false) + let _store_guard = engine.lock_project_store().await; + ensure_project_workspace_root(engine).await?; + ensure_flow_store(engine).await?; + let snap = list_assets_with_project(engine).await?; + let characters: Vec = snap + .assets + .into_iter() + .filter(|a| a.kind == "character") + .collect(); + let target = match_asset(&characters, selector, false) + .cloned() .with_context(|| format!("No character matches '{selector}' in active project"))?; - set_character_bio(&store, &target.id, bio).await?; + + let cur_url = engine.current_url().await.unwrap_or_default(); + let fallback_pid = project_id_from_url(&cur_url); + let pid = snap + .project_id + .as_deref() + .or(fallback_pid.as_deref()) + .context("Missing project ID for character route")?; + + open_character_editor(engine, &cur_url, pid, &target.id).await?; + let save_res = save_character_bio_in_editor(engine, bio).await; + exit_character_editor(engine, snap.project_id.as_deref()).await; + save_res?; + db.upsert_character( target.id.clone(), - Some(store.project_id().to_owned()), - target.name.clone(), + snap.project_id, + target.name, Some(bio.to_owned()), None, None, ) .await?; - Ok(target.id.clone()) + Ok(target.id) +} + +/// Finds a character for an edit and saves its notes through the direct store or character editor. +pub(crate) async fn edit_character_bio( + engine: &ChromeEngine, + db: &FlowDb, + selector: &str, + bio: &str, +) -> Result { + let direct = async { + let store = ProjectStoreSession::open(engine).await?; + let project_id = store.project_id().to_owned(); + let mut result = store + .call("characterBioOp", json!({ "action": "list" }), None) + .await?; + let assets: Vec = serde_json::from_value(result["characters"].take())?; + let target = match_asset(&assets, selector, false) + .cloned() + .with_context(|| format!("No character matches '{selector}' in active project"))?; + set_character_bio(&store, &target.id, bio).await?; + Ok::<(FlowAsset, String), anyhow::Error>((target, project_id)) + } + .await; + + match direct { + Ok((target, project_id)) => { + db.upsert_character( + target.id.clone(), + Some(project_id), + target.name, + Some(bio.to_owned()), + None, + None, + ) + .await?; + Ok(target.id) + } + Err(err) if is_bio_fallback_eligible(&err) => { + edit_character_bio_in_editor(engine, db, selector, bio).await + } + Err(err) => Err(err), + } } diff --git a/src/characters.rs b/src/characters.rs index d30614d..ae00cd8 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -11,7 +11,9 @@ use std::collections::HashMap; use tokio::time::{Duration, Instant}; use crate::assets::{FlowAsset, list_assets_with_project, match_asset, trash_asset}; -use crate::character_bio::{edit_character_bio, set_character_bio}; +use crate::character_bio::{ + edit_character_bio, prepare_bio_store, save_character_bio_in_editor, try_set_character_bio, +}; use crate::db::FlowDb; use crate::download::download_resolved_asset; use crate::engine::{ChromeEngine, checked_runtime_result, validate_local_files}; @@ -20,7 +22,6 @@ use crate::project::{ ensure_flow_store, ensure_project_workspace_root, project_id_from_url, project_subroute_url, project_workspace_url, }; -use crate::project_store::ProjectStoreSession; use crate::queue::{ProgressCallback, SceneParams}; use crate::voices::{ VoiceRequest, apply_voice_with_fallback, delete_portrait, list_all_voices, scene_voice, @@ -398,15 +399,7 @@ pub(crate) async fn create_or_update_character_job( let project_id = snap.project_id.clone(); let project_title = snap.project_title.clone(); let mut bio_store = if effective_bio.is_some() { - let store = ProjectStoreSession::open(engine).await?; - anyhow::ensure!( - project_id.as_deref() == Some(store.project_id()), - "The active project changed before the character update" - ); - store - .call("characterBioOp", json!({ "action": "check" }), None) - .await?; - Some(store) + prepare_bio_store(engine, project_id.as_deref()).await? } else { None }; @@ -450,18 +443,22 @@ pub(crate) async fn create_or_update_character_job( .map(str::to_string) .ok_or_else(|| anyhow::anyhow!("Character creation returned no character ID"))?; - if let (Some(store), Some(bio)) = (bio_store.take(), effective_bio.as_deref()) { - set_character_bio(&store, &cid, bio).await.map_err(|err| { - anyhow::anyhow!("Failed to save personality notes for '{cid}': {err:#}") - })?; - } + let need_editor_bio = if let Some(bio) = effective_bio.as_deref() { + !try_set_character_bio(bio_store.take(), &cid, bio) + .await + .map_err(|err| { + anyhow::anyhow!("Failed to save personality notes for '{cid}': {err:#}") + })? + } else { + false + }; let need_update_on_page = res .get("need_update_on_page") .and_then(|v| v.as_bool()) .unwrap_or(false); let mut submitted_meta = None; - editor_opened = need_update_on_page || has_refs; + editor_opened = need_update_on_page || has_refs || need_editor_bio; if editor_opened { let cur_url = engine.current_url().await.unwrap_or_default(); let fallback_pid = project_id_from_url(&cur_url); @@ -471,6 +468,14 @@ pub(crate) async fn create_or_update_character_job( .ok_or_else(|| anyhow::anyhow!("Missing project ID for character route"))?; open_character_editor(engine, &cur_url, pid, &cid).await?; + if need_editor_bio + && let Some(bio) = effective_bio.as_deref() + && let Err(err) = save_character_bio_in_editor(engine, bio).await + { + exit_character_editor(engine, project_id.as_deref()).await; + anyhow::bail!("Failed to save personality notes for '{cid}': {err:#}"); + } + if need_update_on_page { let media_res = apply_character_page_media( engine, @@ -518,9 +523,11 @@ pub(crate) async fn create_or_update_character_job( format!("No character matches '{}' in active project", target_query) })?; on_progress(format!("editing character '{}'", target.name)); - if let (Some(store), Some(bio)) = (bio_store.take(), effective_bio.as_deref()) { - set_character_bio(&store, &target.id, bio).await?; - } + let need_editor_bio = if let Some(bio) = effective_bio.as_deref() { + !try_set_character_bio(bio_store.take(), &target.id, bio).await? + } else { + false + }; editor_opened = true; let payload = json!({ @@ -562,6 +569,24 @@ pub(crate) async fn create_or_update_character_job( .unwrap_or("unknown") ); } + if need_editor_bio && let Some(bio) = effective_bio.as_deref() { + let cur_url = engine.current_url().await.unwrap_or_default(); + if !cur_url.contains("/character/") { + let fallback_pid = project_id_from_url(&cur_url); + let pid = project_id + .as_deref() + .or(fallback_pid.as_deref()) + .context("Missing project ID for character route")?; + open_character_editor(engine, &cur_url, pid, &target.id).await?; + } + if let Err(err) = save_character_bio_in_editor(engine, bio).await { + exit_character_editor(engine, project_id.as_deref()).await; + anyhow::bail!( + "Failed to save personality notes for '{}': {err:#}", + target.id + ); + } + } let default_voice_name = scene .new_name .clone() diff --git a/src/collection_page.rs b/src/collection_page.rs new file mode 100644 index 0000000..5146cb0 --- /dev/null +++ b/src/collection_page.rs @@ -0,0 +1,516 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Page-control fallbacks for collection listing, creation, renaming, membership, and deletion. +//! +//! Reads collection summaries from the project snapshot and drives sidebar buttons, context +//! menus, title inputs, and pointer drag-and-drop when direct collection store writes cannot run. + +use std::collections::HashSet; + +use anyhow::{Context, Result}; +use serde_json::{Value, json}; +use tokio::time::Duration; + +use crate::collections::{FlowCollection, find_collection, find_unique_collection}; +use crate::engine::ChromeEngine; +use crate::project::{ensure_flow_store, read_snapshot}; +use crate::tile_menu::{ + MOVE_OUT_MENU_ITEM, click_tile_menu_item, dismiss_overlay, enter_tile_view, enter_view, is_ok, + page_is_free, page_op, rename_through_menu, restore_view, tile_dom_op, tile_state, + trash_through_menu, type_text_control, wait_tile_state, +}; + +/// Accessible label of the sidebar button that starts inline collection creation. +const CREATE_COLLECTION_BUTTON: &str = "Create collection"; + +/// Accessible label of the grid header button that creates an untitled collection. +const NEW_COLLECTION_BUTTON: &str = "New collection"; + +/// Accessible label of the button that expands the library sidebar. +const TOGGLE_LIBRARY_BUTTON: &str = "Toggle library"; + +/// Accessible label of the menu button that adds media or collections in the workspace. +const ADD_MEDIA_MENU_BUTTON: &str = "Add media menu"; + +/// Reads collection summaries from the active project snapshot without a direct store session. +pub(crate) async fn snapshot_collections(engine: &ChromeEngine) -> Result> { + let snap = read_snapshot(engine).await?; + let collections = snap + .get("collections") + .cloned() + .unwrap_or_else(|| Value::Array(Vec::new())); + Ok(serde_json::from_value(collections)?) +} + +/// Ensures the page can accept interactive collection controls. +async fn prepare_collection_page(engine: &ChromeEngine) -> Result<()> { + anyhow::ensure!( + page_is_free(), + "Another Flow job uses the browser page right now" + ); + ensure_flow_store(engine).await +} + +/// Clicks the first visible button from `labels`. +async fn click_any_button(engine: &ChromeEngine, labels: &[&str]) -> Result> { + for _ in 0..12 { + for label in labels { + let point = engine + .call_flow_js( + "locatePoint", + json!([{ "by": "aria-label", "name": *label }]), + ) + .await?; + if engine.click_point(&point).await? { + return Ok(Some((*label).to_string())); + } + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + Ok(None) +} + +/// Creates a collection through the sidebar or pinned collections button and verifies its name. +pub(crate) async fn create_collection_through_page( + engine: &ChromeEngine, + raw_name: &str, +) -> Result { + let name = raw_name.trim(); + anyhow::ensure!(!name.is_empty(), "Collection name must not be empty"); + prepare_collection_page(engine).await?; + + let existing = snapshot_collections(engine).await?; + if let Some(found) = find_unique_collection( + existing + .iter() + .filter(|c| c.name.eq_ignore_ascii_case(name)), + name, + )? { + return Ok(json!({ + "created": false, + "collection": found, + "collections": existing, + })); + } + + let before_ids: HashSet = existing.into_iter().map(|c| c.id).collect(); + let saved = enter_view(engine, None).await; + + let mut clicked = + click_any_button(engine, &[CREATE_COLLECTION_BUTTON, NEW_COLLECTION_BUTTON]).await?; + if clicked.is_none() { + let _ = click_any_button(engine, &[TOGGLE_LIBRARY_BUTTON]).await?; + tokio::time::sleep(Duration::from_millis(300)).await; + clicked = + click_any_button(engine, &[CREATE_COLLECTION_BUTTON, NEW_COLLECTION_BUTTON]).await?; + } + if clicked.is_none() + && click_any_button(engine, &[ADD_MEDIA_MENU_BUTTON]) + .await? + .is_some() + { + tokio::time::sleep(Duration::from_millis(250)).await; + for (by, label) in [ + ("menuitem", CREATE_COLLECTION_BUTTON), + ("text", "create_new_folder Create collection"), + ("text", CREATE_COLLECTION_BUTTON), + ] { + let point = engine + .call_flow_js("locatePoint", json!([{ "by": by, "name": label }])) + .await?; + if engine.click_point(&point).await? { + clicked = Some(CREATE_COLLECTION_BUTTON.to_string()); + break; + } + } + } + let Some(trigger) = clicked else { + restore_view(engine, saved).await; + anyhow::bail!("The Create collection control is not visible on the Flow page"); + }; + + tokio::time::sleep(Duration::from_millis(250)).await; + if trigger == CREATE_COLLECTION_BUTTON { + let _ = type_text_control(engine, "item", "", name).await?; + } + + let mut created_id: Option = None; + for _ in 0..40 { + if let Ok(cols) = snapshot_collections(engine).await + && let Some(found) = cols.into_iter().find(|c| !before_ids.contains(&c.id)) + { + created_id = Some(found.id); + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + + let Some(id) = created_id else { + dismiss_overlay(engine).await; + restore_view(engine, saved).await; + anyhow::bail!("Flow did not create collection '{name}' through page controls"); + }; + + if tile_state(engine, &id).await.name != name { + let _ = rename_collection_in_page(engine, &id, name).await?; + } + restore_view(engine, saved).await; + + let collections = snapshot_collections(engine).await?; + let collection = collections + .iter() + .find(|c| c.id == id) + .with_context(|| format!("Collection '{id}' disappeared after creation"))?; + Ok(json!({ + "ok": true, + "created": true, + "id": collection.id, + "name": collection.name, + "method": "page:create_collection", + "collection": collection, + "collections": collections, + })) +} + +/// Renames collection `id` to `name` in the open workspace via its menu or collection page title. +async fn rename_collection_in_page(engine: &ChromeEngine, id: &str, name: &str) -> Result { + if rename_through_menu(engine, id, name).await? { + return Ok(json!({ + "ok": true, + "id": id, + "name": name, + "method": "menu:rename", + })); + } + + let current = tile_state(engine, id).await.name; + let saved = enter_view(engine, Some(id)).await; + let view = page_op(engine, json!({ "action": "view" })).await?; + if view.get("collection").and_then(Value::as_str) != Some(id) { + restore_view(engine, saved).await; + anyhow::bail!("Cannot open collection '{id}' to rename it"); + } + + let point_res = page_op( + engine, + json!({ "action": "text_point", "control": "title", "name": current }), + ) + .await?; + let clicked = match point_res.get("point") { + Some(pt) if is_ok(&point_res) => engine.click_point(pt).await?, + _ => false, + }; + let typed = if clicked { + tokio::time::sleep(Duration::from_millis(150)).await; + type_text_control(engine, "title", ¤t, name).await? + } else { + false + }; + let confirmed = typed && wait_tile_state(engine, id, 40, |s| s.name == name).await; + restore_view(engine, saved).await; + anyhow::ensure!( + confirmed, + "Failed to rename collection '{id}' through page controls" + ); + Ok(json!({ + "ok": true, + "id": id, + "name": name, + "method": "page:collection_title", + })) +} + +/// Renames collection `id` to `name` through page controls and confirms the updated name. +pub(crate) async fn rename_collection_through_page( + engine: &ChromeEngine, + id: &str, + name: &str, +) -> Result { + let name = name.trim(); + anyhow::ensure!(!name.is_empty(), "Target collection name must not be empty"); + prepare_collection_page(engine).await?; + let state = tile_state(engine, id).await; + anyhow::ensure!( + state.is_present() && state.kind == "collection", + "Collection not found: {id}" + ); + if state.name == name { + return Ok(json!({ "ok": true, "id": id, "name": name, "method": "noop" })); + } + rename_collection_in_page(engine, id, name).await +} + +/// Sends a trusted mouse drag from `(sx, sy)` to `(tx, ty)` across Flow drop zones. +async fn drag_point_to_point( + engine: &ChromeEngine, + sx: f64, + sy: f64, + tx: f64, + ty: f64, +) -> Result<()> { + engine.mouse_move(sx, sy).await?; + tokio::time::sleep(Duration::from_millis(80)).await; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mousePressed", + "x": sx, + "y": sy, + "button": "left", + "buttons": 1, + "clickCount": 1, + }), + ) + .await?; + tokio::time::sleep(Duration::from_millis(80)).await; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mouseMoved", + "x": sx + 14.0, + "y": sy + 14.0, + "button": "left", + "buttons": 1, + }), + ) + .await?; + tokio::time::sleep(Duration::from_millis(160)).await; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mouseMoved", + "x": (sx + tx) / 2.0, + "y": (sy + ty) / 2.0, + "button": "left", + "buttons": 1, + }), + ) + .await?; + tokio::time::sleep(Duration::from_millis(80)).await; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mouseMoved", + "x": tx, + "y": ty, + "button": "left", + "buttons": 1, + }), + ) + .await?; + tokio::time::sleep(Duration::from_millis(160)).await; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mouseReleased", + "x": tx, + "y": ty, + "button": "left", + "buttons": 0, + "clickCount": 1, + }), + ) + .await?; + Ok(()) +} + +/// Drags from `(sx, sy)` to `(tx, ty)` and waits for `done`, trying HTML5 drag events if pointer drag does not settle. +async fn drag_and_confirm( + engine: &ChromeEngine, + item_id: &str, + coords: (f64, f64, f64, f64), + done: impl Fn(&crate::tile_menu::TileState) -> bool, +) -> Result { + let (sx, sy, tx, ty) = coords; + drag_point_to_point(engine, sx, sy, tx, ty).await?; + if wait_tile_state(engine, item_id, 6, &done).await { + return Ok(true); + } + let _ = page_op( + engine, + json!({ "action": "html5_drag", "coords": [sx, sy, tx, ty] }), + ) + .await; + Ok(wait_tile_state(engine, item_id, 34, done).await) +} + +/// Validates that each ID in `ids` names a present non-collection tile. +async fn verify_movable_items(engine: &ChromeEngine, ids: &[String]) -> Result<()> { + for id in ids { + let st = tile_state(engine, id).await; + anyhow::ensure!(st.is_present(), "asset_not_found: {id}"); + anyhow::ensure!(st.kind != "collection", "collection_not_movable: {id}"); + } + Ok(()) +} + +/// Populates a collection (creating it first when missing) by dragging tiles onto its drop target. +pub(crate) async fn add_to_collection_through_page( + engine: &ChromeEngine, + ids: &[String], + target: &str, +) -> Result { + let target = target.trim(); + anyhow::ensure!(!target.is_empty(), "Collection name must not be empty"); + prepare_collection_page(engine).await?; + verify_movable_items(engine, ids).await?; + + let collections = snapshot_collections(engine).await?; + let target_id = if let Some(found) = find_collection(&collections, target, false)? { + found.id.clone() + } else { + let created = create_collection_through_page(engine, target).await?; + created + .get("id") + .or_else(|| created.pointer("/collection/id")) + .and_then(Value::as_str) + .context("Page collection creation returned no collection ID")? + .to_owned() + }; + + for item_id in ids { + let st = tile_state(engine, item_id).await; + if st.collection.as_deref() == Some(target_id.as_str()) { + continue; + } + let saved = enter_tile_view(engine, item_id).await; + let src = tile_dom_op(engine, "locate", item_id).await?; + let dst = tile_dom_op(engine, "drop_target", &target_id).await?; + let coords = (|| { + let s = src.get("tile")?; + let d = dst.get("target")?; + Some(( + s.get("x")?.as_f64()?, + s.get("y")?.as_f64()?, + d.get("x")?.as_f64()?, + d.get("y")?.as_f64()?, + )) + })(); + let Some((sx, sy, tx, ty)) = coords else { + restore_view(engine, saved).await; + anyhow::bail!( + "Cannot locate tile '{item_id}' or collection '{target_id}' for drag-and-drop" + ); + }; + let drag_res = drag_and_confirm(engine, item_id, (sx, sy, tx, ty), |s| { + s.collection.as_deref() == Some(target_id.as_str()) + }) + .await; + restore_view(engine, saved).await; + let moved = drag_res?; + anyhow::ensure!( + moved, + "Flow did not confirm moving tile '{item_id}' into collection '{target_id}'" + ); + } + + Ok(json!({ + "ok": true, + "moved": ids.len(), + "collection_id": target_id, + "ids": ids, + "method": "page:drag_to_collection", + })) +} + +/// Moves tiles out of their parent collection through the menu item or root drop zone. +pub(crate) async fn remove_from_collection_through_page( + engine: &ChromeEngine, + ids: &[String], +) -> Result { + prepare_collection_page(engine).await?; + verify_movable_items(engine, ids).await?; + let mut method = "menu:move_out_of_collection"; + + for item_id in ids { + let st = tile_state(engine, item_id).await; + if st.collection.is_none() { + continue; + } + let saved = enter_tile_view(engine, item_id).await; + let clicked = click_tile_menu_item(engine, item_id, MOVE_OUT_MENU_ITEM).await?; + let mut moved = + clicked && wait_tile_state(engine, item_id, 40, |s| s.collection.is_none()).await; + if !moved { + let src = tile_dom_op(engine, "locate", item_id).await?; + let dst = page_op(engine, json!({ "action": "root_drop_target" })).await?; + let coords = (|| { + let s = src.get("tile")?; + let d = dst.get("target")?; + Some(( + s.get("x")?.as_f64()?, + s.get("y")?.as_f64()?, + d.get("x")?.as_f64()?, + d.get("y")?.as_f64()?, + )) + })(); + if let Some(coords) = coords + && drag_and_confirm(engine, item_id, coords, |s| s.collection.is_none()) + .await + .unwrap_or(false) + { + moved = true; + method = "page:drag_to_root"; + } + } + restore_view(engine, saved).await; + anyhow::ensure!( + moved, + "Flow did not confirm moving tile '{item_id}' out of its collection" + ); + } + + Ok(json!({ + "ok": true, + "removed": ids.len(), + "moved": ids.len(), + "collection_id": Value::Null, + "ids": ids, + "method": method, + })) +} + +/// Empties member tiles to root and deletes collection `id` through its context menu. +pub(crate) async fn delete_collection_through_page( + engine: &ChromeEngine, + id: &str, +) -> Result { + prepare_collection_page(engine).await?; + let st = tile_state(engine, id).await; + anyhow::ensure!( + st.is_present() && st.kind == "collection", + "Collection not found: {id}" + ); + anyhow::ensure!( + !st.has_child_collections, + "collection_has_child_collections: {id}" + ); + + let member_ids = st.member_ids; + if !member_ids.is_empty() { + remove_from_collection_through_page(engine, &member_ids).await?; + } + anyhow::ensure!( + wait_tile_state(engine, id, 20, |s| s.count == 0 && !s.has_child_collections).await, + "Collection '{id}' is not empty before deletion" + ); + let trashed = trash_through_menu(engine, id).await?; + anyhow::ensure!( + trashed, + "Failed to delete collection '{id}' through its context menu" + ); + + Ok(json!({ + "ok": true, + "deleted": id, + "moved_to_root": member_ids.len(), + "confirmed": true, + "method": "menu:delete_collection", + })) +} diff --git a/src/collections.rs b/src/collections.rs index a2a2f16..59a4411 100644 --- a/src/collections.rs +++ b/src/collections.rs @@ -8,6 +8,10 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use crate::collection_page::{ + add_to_collection_through_page, create_collection_through_page, delete_collection_through_page, + remove_from_collection_through_page, rename_collection_through_page, snapshot_collections, +}; use crate::engine::ChromeEngine; use crate::project_store::ProjectStoreSession; @@ -19,7 +23,7 @@ pub(crate) struct FlowCollection { /// Collection display name. pub(crate) name: String, /// Asset count in this collection. - count: usize, + pub(crate) count: usize, } /// Parameters for `flow_collections`. @@ -57,14 +61,6 @@ impl ProjectStoreSession<'_> { Ok(serde_json::from_value(value["collections"].take())?) } - /// Returns true when the tile ID belongs to a collection. - pub(crate) async fn is_collection(&self, id: &str) -> Result { - let res = self - .run_collections(json!({ "action": "inspect", "id": id })) - .await?; - Ok(res.get("collection").and_then(Value::as_bool) == Some(true)) - } - /// Requests a verified rename for a collection ID. pub(crate) async fn rename(&self, id: &str, name: &str) -> Result { self.run_collections(json!({ "action": "rename", "id": id, "name": name })) @@ -126,7 +122,7 @@ impl ProjectStoreSession<'_> { } /// Returns the only collection in a set of matches, if one exists. -fn find_unique_collection<'a>( +pub(crate) fn find_unique_collection<'a>( mut matches: impl Iterator, query: &str, ) -> Result> { @@ -168,7 +164,7 @@ pub(crate) fn find_collection<'a>( ) } -/// Returns the requested collection or reports a missing target. +/// Returns the requested collection from the direct store session or reports a missing target. async fn require_collection(session: &ProjectStoreSession<'_>, query: &str) -> Result { let collections = session.list().await?; Ok(find_collection(&collections, query.trim(), false)? @@ -177,6 +173,30 @@ async fn require_collection(session: &ProjectStoreSession<'_>, query: &str) -> R .clone()) } +/// Returns the requested collection from the project snapshot or reports a missing target. +async fn require_snapshot_collection(engine: &ChromeEngine, query: &str) -> Result { + let collections = snapshot_collections(engine).await?; + Ok(find_collection(&collections, query.trim(), false)? + .with_context(|| format!("Collection not found: {query}"))? + .id + .clone()) +} + +/// Returns true when a direct collection error can fall back to page controls. +fn is_collection_fallback_eligible(err: &anyhow::Error) -> bool { + let msg = format!("{err:#}"); + if msg.contains("outcome_unknown") { + return false; + } + msg.contains("unsupported_front_end") + || msg.contains("collection_store_not_bound") + || msg.contains("ambiguous_collection_store") + || msg.contains("collection_delete_unavailable") + || msg.contains("project_store_changed") + || msg.contains("project_changed") + || msg.contains("Open a Google Flow project") +} + /// Returns the nonempty list of asset IDs for a move request. fn move_ids(ids: Option>, action: &str) -> Result> { ids.filter(|ids| !ids.is_empty()).with_context(|| { @@ -189,14 +209,28 @@ pub(crate) async fn handle_collections( engine: &ChromeEngine, req: CollectionsParams, ) -> Result { - let session = ProjectStoreSession::open(engine).await?; match req.action.as_str() { - "list" => Ok(json!({ "collections": session.list().await? })), + "list" => { + let _guard = engine.lock_project_store().await; + Ok(json!({ "collections": snapshot_collections(engine).await? })) + } "create" => { let name = req .name .context("flow_collections create requires 'name'")?; - session.create(&name).await + let direct = async { + let session = ProjectStoreSession::open(engine).await?; + session.create(&name).await + } + .await; + match direct { + Ok(val) => Ok(val), + Err(err) if is_collection_fallback_eligible(&err) => { + let _guard = engine.lock_project_store().await; + create_collection_through_page(engine, &name).await + } + Err(err) => Err(err), + } } "rename" => { let from = req @@ -205,8 +239,21 @@ pub(crate) async fn handle_collections( let to = req.to.context("flow_collections rename requires 'to'")?; let to = to.trim(); anyhow::ensure!(!to.is_empty(), "Target collection name must not be empty"); - let id = require_collection(&session, &from).await?; - let mut result = session.rename(&id, to).await?; + let direct = async { + let session = ProjectStoreSession::open(engine).await?; + let id = require_collection(&session, &from).await?; + session.rename(&id, to).await + } + .await; + let mut result = match direct { + Ok(val) => val, + Err(err) if is_collection_fallback_eligible(&err) => { + let _guard = engine.lock_project_store().await; + let id = require_snapshot_collection(engine, &from).await?; + rename_collection_through_page(engine, &id, to).await? + } + Err(err) => return Err(err), + }; result["renamed"] = json!(true); result["from"] = json!(from); result["to"] = json!(to); @@ -216,14 +263,36 @@ pub(crate) async fn handle_collections( let target = req .collection .context("flow_collections add requires 'collection'")?; - session - .move_assets(move_ids(req.ids, "add")?, Some(&target)) - .await + let ids = move_ids(req.ids, "add")?; + let direct = async { + let session = ProjectStoreSession::open(engine).await?; + session.move_assets(ids.clone(), Some(&target)).await + } + .await; + match direct { + Ok(val) => Ok(val), + Err(err) if is_collection_fallback_eligible(&err) => { + let _guard = engine.lock_project_store().await; + add_to_collection_through_page(engine, &ids, &target).await + } + Err(err) => Err(err), + } } "remove" => { - session - .move_assets(move_ids(req.ids, "remove")?, None) - .await + let ids = move_ids(req.ids, "remove")?; + let direct = async { + let session = ProjectStoreSession::open(engine).await?; + session.move_assets(ids.clone(), None).await + } + .await; + match direct { + Ok(val) => Ok(val), + Err(err) if is_collection_fallback_eligible(&err) => { + let _guard = engine.lock_project_store().await; + remove_from_collection_through_page(engine, &ids).await + } + Err(err) => Err(err), + } } "delete" => { let target = req @@ -231,8 +300,21 @@ pub(crate) async fn handle_collections( .or(req.name) .or(req.from) .context("flow_collections delete requires 'collection', 'name', or 'from'")?; - let id = require_collection(&session, &target).await?; - session.delete(&id).await + let direct = async { + let session = ProjectStoreSession::open(engine).await?; + let id = require_collection(&session, &target).await?; + session.delete(&id).await + } + .await; + match direct { + Ok(val) => Ok(val), + Err(err) if is_collection_fallback_eligible(&err) => { + let _guard = engine.lock_project_store().await; + let id = require_snapshot_collection(engine, &target).await?; + delete_collection_through_page(engine, &id).await + } + Err(err) => Err(err), + } } other => anyhow::bail!("Unknown collections action: {other}"), } diff --git a/src/main.rs b/src/main.rs index adcf386..43c5c5d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ mod character_bio; mod characters; mod chrome; mod cli; +mod collection_page; mod collections; mod config; mod cookies; diff --git a/src/tile_menu.rs b/src/tile_menu.rs index 93ac606..88ceab5 100644 --- a/src/tile_menu.rs +++ b/src/tile_menu.rs @@ -19,9 +19,15 @@ use crate::project::ensure_flow_store; /// Menu item text that moves a tile to trash. const TRASH_MENU_ITEM: &str = "Move to trash"; +/// Menu item text that moves a collection to trash. +const TRASH_COLLECTION_MENU_ITEM: &str = "Move all contents to trash"; + /// Menu item text that opens the rename control of a tile. const RENAME_MENU_ITEM: &str = "Rename"; +/// Menu item text that moves a tile out of its collection. +pub(crate) const MOVE_OUT_MENU_ITEM: &str = "Move out of collection"; + /// Number of queue jobs that use the page now. static PAGE_JOBS: AtomicUsize = AtomicUsize::new(0); @@ -44,7 +50,7 @@ impl Drop for PageHold { } /// Returns true when no queue job uses the page. A menu operation clicks the page and can change the route, so it must not run while a job waits on the page. -fn page_is_free() -> bool { +pub(crate) fn page_is_free() -> bool { PAGE_JOBS.load(Ordering::Acquire) == 0 } @@ -53,10 +59,18 @@ fn page_is_free() -> bool { pub(crate) struct TileState { /// `present`, `trashed`, or `gone`. Empty when the store is not readable. pub(crate) state: String, + /// Lowercase tile kind (`image`, `video`, `character`, `scene`, or `collection`). + pub(crate) kind: String, /// Display name of a present tile. pub(crate) name: String, /// Collection ID of a present tile, or `None` when no collection holds it. pub(crate) collection: Option, + /// Active member count when the tile is a collection. + pub(crate) count: usize, + /// Direct non-collection member IDs when the tile is a collection. + pub(crate) member_ids: Vec, + /// True when the collection holds one or more child collections. + pub(crate) has_child_collections: bool, } impl TileState { @@ -66,23 +80,23 @@ impl TileState { } /// Returns true when the tile is in trash or the tile map does not show it. - fn is_trashed_or_gone(&self) -> bool { + pub(crate) fn is_trashed_or_gone(&self) -> bool { self.state == "trashed" || self.state == "gone" } } /// Runs one `tileDomOp` action of the browser runtime with the request `req`. -async fn page_op(engine: &ChromeEngine, req: Value) -> Result { +pub(crate) async fn page_op(engine: &ChromeEngine, req: Value) -> Result { engine.call_flow_async("tileDomOp", json!([req])).await } /// Runs one `tileDomOp` action of the browser runtime for tile `id`. -async fn tile_dom_op(engine: &ChromeEngine, action: &str, id: &str) -> Result { +pub(crate) async fn tile_dom_op(engine: &ChromeEngine, action: &str, id: &str) -> Result { page_op(engine, json!({ "action": action, "id": id })).await } /// Returns true when the result `res` of a page action has `ok` set. -fn is_ok(res: &Value) -> bool { +pub(crate) fn is_ok(res: &Value) -> bool { res.get("ok").and_then(|v| v.as_bool()) == Some(true) } @@ -92,15 +106,37 @@ pub(crate) async fn tile_state(engine: &ChromeEngine, id: &str) -> TileState { return TileState::default(); }; let text = |key: &str| res.get(key).and_then(|v| v.as_str()).map(str::to_string); + let count = res + .get("count") + .and_then(|v| v.as_u64()) + .and_then(|n| usize::try_from(n).ok()) + .unwrap_or(0); + let member_ids = res + .get("member_ids") + .and_then(Value::as_array) + .map(|arr| { + arr.iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + let has_child_collections = res + .get("has_child_collections") + .and_then(Value::as_bool) + .unwrap_or(false); TileState { state: text("state").unwrap_or_default(), + kind: text("kind").unwrap_or_default(), name: text("name").unwrap_or_default(), collection: text("collection").filter(|v| !v.is_empty()), + count, + member_ids, + has_child_collections, } } /// Polls the store state of tile `id` every 250 ms, and returns true when `done` accepts it within `tries` polls. -async fn wait_tile_state( +pub(crate) async fn wait_tile_state( engine: &ChromeEngine, id: &str, tries: u32, @@ -121,36 +157,83 @@ pub(crate) async fn wait_trashed(engine: &ChromeEngine, id: &str, tries: u32) -> } /// Closes an open menu or overlay of the page. -async fn dismiss_overlay(engine: &ChromeEngine) { +pub(crate) async fn dismiss_overlay(engine: &ChromeEngine) { let _ = tile_dom_op(engine, "dismiss", "").await; } -/// Hovers the tile that `loc` describes, opens its "More options" menu, and clicks the menu item `item`. -/// -/// Returns false when the page does not show the tile, the menu, or the menu item. It closes the menu in that case. -async fn click_menu_item_at(engine: &ChromeEngine, loc: &Value, item: &str) -> Result { - if !is_ok(loc) { +/// Sends a trusted right-click at `(x, y)` to open the context menu of a grid tile. +async fn right_click_at(engine: &ChromeEngine, x: f64, y: f64) -> Result<()> { + engine.mouse_move(x, y).await?; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mousePressed", + "x": x, + "y": y, + "button": "right", + "buttons": 2, + "clickCount": 1, + }), + ) + .await?; + engine + .cdp_call( + "Input.dispatchMouseEvent", + json!({ + "type": "mouseReleased", + "x": x, + "y": y, + "button": "right", + "buttons": 0, + "clickCount": 1, + }), + ) + .await?; + Ok(()) +} + +/// Opens the menu of tile `id` and clicks the first visible item from `items`. +pub(crate) async fn click_tile_menu_items( + engine: &ChromeEngine, + id: &str, + items: &[&str], +) -> Result { + let mut loc = tile_dom_op(engine, "locate", id).await?; + if !is_ok(&loc) { return Ok(false); } - let (Some(tile), Some(menu)) = (loc.get("tile"), loc.get("menu")) else { + let Some((x, y)) = loc.get("tile").and_then(|tile| { + Some(( + tile.get("x").and_then(|v| v.as_f64())?, + tile.get("y").and_then(|v| v.as_f64())?, + )) + }) else { return Ok(false); }; - if let (Some(x), Some(y)) = ( - tile.get("x").and_then(|v| v.as_f64()), - tile.get("y").and_then(|v| v.as_f64()), - ) { - engine.mouse_move(x, y).await?; - tokio::time::sleep(Duration::from_millis(300)).await; + engine.mouse_move(x, y).await?; + tokio::time::sleep(Duration::from_millis(250)).await; + if loc.get("menu").is_none_or(Value::is_null) + && let Ok(refreshed) = tile_dom_op(engine, "locate", id).await + && is_ok(&refreshed) + { + loc = refreshed; } - if !engine.click_point(menu).await? { - return Ok(false); + let menu_clicked = match loc.get("menu") { + Some(menu) if !menu.is_null() => engine.click_point(menu).await?, + _ => false, + }; + if !menu_clicked { + right_click_at(engine, x, y).await?; } for _ in 0..15 { - let point = engine - .call_flow_js("locatePoint", json!([{ "by": "menuitem", "name": item }])) - .await?; - if engine.click_point(&point).await? { - return Ok(true); + for item in items { + let point = engine + .call_flow_js("locatePoint", json!([{ "by": "menuitem", "name": item }])) + .await?; + if engine.click_point(&point).await? { + return Ok(true); + } } tokio::time::sleep(Duration::from_millis(150)).await; } @@ -158,19 +241,22 @@ async fn click_menu_item_at(engine: &ChromeEngine, loc: &Value, item: &str) -> R Ok(false) } -/// Opens the "More options" menu of tile `id` and clicks the menu item `item`. -async fn click_tile_menu_item(engine: &ChromeEngine, id: &str, item: &str) -> Result { - let loc = tile_dom_op(engine, "locate", id).await?; - click_menu_item_at(engine, &loc, item).await +/// Opens the menu of tile `id` and clicks `item`. +pub(crate) async fn click_tile_menu_item( + engine: &ChromeEngine, + id: &str, + item: &str, +) -> Result { + click_tile_menu_items(engine, id, &[item]).await } /// Page view to restore after an operation: `Some(collection ID)`, with an empty ID for the main grid. -type SavedView = Option; +pub(crate) type SavedView = Option; /// Opens the main grid when `collection` is `None`, or the page of that collection, and binds the store again. /// /// Returns the view to restore when the route changed. Returns `None` when the page already shows the view or cannot change to it. -async fn enter_view(engine: &ChromeEngine, collection: Option<&str>) -> SavedView { +pub(crate) async fn enter_view(engine: &ChromeEngine, collection: Option<&str>) -> SavedView { let before = page_op(engine, json!({ "action": "view" })).await.ok()?; let previous = before .get("collection") @@ -188,7 +274,7 @@ async fn enter_view(engine: &ChromeEngine, collection: Option<&str>) -> SavedVie } /// Opens the view that shows tile `id`: the page of its collection, or the main grid. -async fn enter_tile_view(engine: &ChromeEngine, id: &str) -> SavedView { +pub(crate) async fn enter_tile_view(engine: &ChromeEngine, id: &str) -> SavedView { let state = tile_state(engine, id).await; if !state.is_present() { return None; @@ -197,18 +283,61 @@ async fn enter_tile_view(engine: &ChromeEngine, id: &str) -> SavedView { } /// Opens the view that `saved` holds again, and binds the store again. -async fn restore_view(engine: &ChromeEngine, saved: SavedView) { +pub(crate) async fn restore_view(engine: &ChromeEngine, saved: SavedView) { if let Some(collection) = saved { let _ = tile_dom_op(engine, "open_view", &collection).await; let _ = ensure_flow_store(engine).await; } } -/// Moves a media tile to trash through its menu, and returns true when the store confirms it. -/// -/// Returns false when the page does not show the tile, the menu, or the menu item, so that the caller can use the store mutation. +/// Moves a tile or collection to trash through its context menu, and returns true when the store confirms it. async fn trash_in_view(engine: &ChromeEngine, id: &str) -> Result { - if !click_tile_menu_item(engine, id, TRASH_MENU_ITEM).await? { + let state = tile_state(engine, id).await; + if state.kind == "collection" { + if !click_tile_menu_items( + engine, + id, + &[ + TRASH_COLLECTION_MENU_ITEM, + "Delete collection", + TRASH_MENU_ITEM, + ], + ) + .await? + { + return Ok(false); + } + for _ in 0..20 { + if tile_state(engine, id).await.is_trashed_or_gone() { + return Ok(true); + } + let mut confirmed = false; + for label in [ + TRASH_COLLECTION_MENU_ITEM, + "Delete collection", + TRASH_MENU_ITEM, + "Delete", + ] { + let confirm = engine + .call_flow_js("locatePoint", json!([{ "by": "text", "name": label }])) + .await?; + if engine.click_point(&confirm).await? { + confirmed = true; + break; + } + } + if confirmed { + break; + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + if wait_trashed(engine, id, 40).await { + return Ok(true); + } + dismiss_overlay(engine).await; + return Ok(false); + } + if !click_tile_menu_items(engine, id, &[TRASH_MENU_ITEM, "Delete"]).await? { return Ok(false); } if wait_trashed(engine, id, 40).await { @@ -239,11 +368,20 @@ async fn press_enter(engine: &ChromeEngine) -> Result<()> { Ok(()) } -/// Types `name` into the focused rename control and submits it with the Enter key. -async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { +/// Types `text` into the focused `control` (`tile`, `item`, or `title`) and submits it with Enter. +pub(crate) async fn type_text_control( + engine: &ChromeEngine, + control: &str, + current: &str, + text: &str, +) -> Result { let mut selected = false; for _ in 0..15 { - let res = page_op(engine, json!({ "action": "text_select" })).await?; + let res = page_op( + engine, + json!({ "action": "text_select", "control": control, "name": current }), + ) + .await?; if is_ok(&res) && res.get("focused").and_then(|v| v.as_bool()) == Some(true) { selected = true; break; @@ -255,12 +393,16 @@ async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { return Ok(false); } engine - .cdp_call("Input.insertText", json!({ "text": name })) + .cdp_call("Input.insertText", json!({ "text": text })) .await?; tokio::time::sleep(Duration::from_millis(150)).await; - let typed = page_op(engine, json!({ "action": "text_value" })).await?; - if typed.get("value").and_then(|v| v.as_str()) != Some(name) { - // The control does not hold the new name. Do not submit a wrong name. + let typed = page_op( + engine, + json!({ "action": "text_value", "control": control, "name": text }), + ) + .await?; + if typed.get("value").and_then(|v| v.as_str()) != Some(text) { + // The control does not hold the new text. Do not submit a wrong value. dismiss_overlay(engine).await; return Ok(false); } @@ -268,12 +410,12 @@ async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { Ok(true) } -/// Renames a media tile in the current view through the "Rename" item of its menu. +/// Renames a tile in the current view through the "Rename" item of its context menu. async fn rename_in_view(engine: &ChromeEngine, id: &str, name: &str) -> Result { if !click_tile_menu_item(engine, id, RENAME_MENU_ITEM).await? { return Ok(false); } - if !type_rename(engine, name).await? { + if !type_text_control(engine, "tile", "", name).await? { return Ok(false); } let renamed = wait_tile_state(engine, id, 40, |s| s.name == name).await; diff --git a/src/upload.rs b/src/upload.rs index ef17eb8..7ac735e 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -38,9 +38,20 @@ pub(crate) async fn local_upload_paths(files: &[String], label: &str) -> Result< Ok(paths) } -/// Uploads files to the pinned project and returns the saved assets. +/// Extracts any assets already confirmed before a direct upload failure. +fn partial_uploaded_assets(err: &anyhow::Error) -> Vec { + let msg = format!("{err:#}"); + let Some((_, json_part)) = msg.split_once(' ') else { + return Vec::new(); + }; + serde_json::from_str::(json_part) + .ok() + .and_then(|v| v.get("assets").and_then(Value::as_array).cloned()) + .unwrap_or_default() +} + +/// Uploads files to the pinned project and falls back to the upload menu when direct upload fails. pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { - let project = ProjectStoreSession::open(engine).await?; let has_video = files.iter().any(|file| { mime_guess::from_path(file) .first() @@ -50,33 +61,71 @@ pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String] // Chrome can leave a video in the loading state while its tab is hidden. engine.cdp_call("Page.bringToFront", json!({})).await?; } - engine - .upload_files_to("window.__flowMcp.stageMediaFiles()", files) - .await?; - project - .call( - "projectUpload", - json!(files.len()), - Some("upload local media"), - ) - .await + let direct = async { + let project = ProjectStoreSession::open(engine).await?; + engine + .upload_files_to("window.__flowMcp.stageMediaFiles()", files) + .await?; + project + .call( + "projectUpload", + json!(files.len()), + Some("upload local media"), + ) + .await + } + .await; + match direct { + Ok(result) => Ok(result), + Err(err) if format!("{err:#}").contains("outcome_unknown") => Err(err), + Err(err) => { + let mut confirmed = partial_uploaded_assets(&err); + let done = confirmed.len().min(files.len()); + if done == files.len() && !confirmed.is_empty() { + return Ok(json!({ + "count": confirmed.len(), + "assets": confirmed, + })); + } + let mut menu_res = upload_project_files_through_menu(engine, &files[done..]).await?; + if !confirmed.is_empty() + && let Some(arr) = menu_res.get_mut("assets").and_then(Value::as_array_mut) + { + confirmed.append(arr); + *arr = confirmed; + menu_res["count"] = json!(arr.len()); + } + Ok(menu_res) + } + } } -/// Script that keeps the next file input that the page clicks in `window.__fmUploadInput`. +/// Script that keeps the next file input that the page opens in `window.__fmUploadInput`. const HOOK_JS: &str = r#"(() => { const P = HTMLInputElement.prototype; if (window.__fmUploadRestore) window.__fmUploadRestore(); window.__fmUploadInput = null; - const orig = P.click; + const origClick = P.click; + const origPicker = P.showPicker; P.click = function () { if (this.type === "file") window.__fmUploadInput = this; - return orig.call(this); + return origClick.call(this); + }; + if (typeof origPicker === "function") { + P.showPicker = function () { + if (this.type === "file") window.__fmUploadInput = this; + return origPicker.call(this); + }; + } + window.__fmUploadRestore = () => { + P.click = origClick; + if (typeof origPicker === "function") P.showPicker = origPicker; + window.__fmUploadRestore = null; }; - window.__fmUploadRestore = () => { P.click = orig; window.__fmUploadRestore = null; }; return true; })()"#; -/// Script that removes the click hook. +/// Script that removes the file input hook. const UNHOOK_JS: &str = "window.__fmUploadRestore && window.__fmUploadRestore(), true"; /// Evaluates `expr` on the page and returns its JSON value. @@ -104,33 +153,86 @@ async fn click_when_visible(engine: &ChromeEngine, by: &str, name: &str) -> Resu anyhow::bail!("{} is not visible", name) } -/// Clicks `menu` and its `upload ` entry, and assigns `files` to the file input that the page opens. +/// Clicks the visible upload menu item for `item` across Flow menu variants. +async fn click_upload_item(engine: &ChromeEngine, item: &str) -> Result<()> { + let prefixed = format!("upload {item}"); + for _ in 0..20 { + let mut candidates = vec![("menuitem", item), ("text", prefixed.as_str())]; + if item == LIBRARY_UPLOAD_ITEM { + candidates.push(("menuitem", PROMPT_UPLOAD_ITEM)); + candidates.push(("text", PROMPT_UPLOAD_ITEM)); + } + for (by, label) in candidates { + let point = engine + .call_flow_js("locatePoint", json!([{ "by": by, "name": label }])) + .await?; + if engine.click_point(&point).await? { + return Ok(()); + } + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + anyhow::bail!("{} is not visible", item) +} + +/// Opens `menu`, clicks `item`, and waits for the page to create its file input. +async fn open_menu_file_input(engine: &ChromeEngine, menu: &str, item: &str) -> Result<()> { + let _ = eval_value(engine, "window.__fmUploadInput = null, true").await; + click_when_visible(engine, "aria-label", menu).await?; + tokio::time::sleep(Duration::from_millis(400)).await; + click_upload_item(engine, item).await?; + for attempt in 0..30 { + let v = eval_value(engine, "!!window.__fmUploadInput").await?; + if v.as_bool() == Some(true) { + return Ok(()); + } + if attempt % 3 == 1 { + let _ = engine + .call_flow_js("uploadUiAction", json!(["accept_consent"])) + .await; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + anyhow::bail!("The '{}' item did not open a file chooser", item) +} + +/// Clicks `menu` and its upload entry, and assigns `files` to the file input that the page opens. async fn upload_steps( engine: &ChromeEngine, menu: &str, item: &str, files: &[String], ) -> Result<()> { - click_when_visible(engine, "aria-label", menu).await?; - tokio::time::sleep(Duration::from_millis(500)).await; - click_when_visible(engine, "text", &format!("upload {item}")).await?; - let mut opened = false; - for _ in 0..30 { - let v = eval_value(engine, "!!window.__fmUploadInput").await?; - if v.as_bool() == Some(true) { - opened = true; - break; - } - tokio::time::sleep(Duration::from_millis(100)).await; + open_menu_file_input(engine, menu, item).await?; + let multiple = eval_value( + engine, + "Boolean(window.__fmUploadInput && window.__fmUploadInput.multiple)", + ) + .await? + .as_bool() + .unwrap_or(false); + if files.len() <= 1 || multiple { + return engine + .upload_files_to("window.__fmUploadInput", files) + .await + .context("Failed to assign files to the Flow upload input"); } - anyhow::ensure!(opened, "The '{}' item did not open a file chooser", item); engine - .upload_files_to("window.__fmUploadInput", files) + .upload_files_to("window.__fmUploadInput", &files[..1]) .await - .context("Failed to assign files to the Flow upload input") + .context("Failed to assign file to the Flow upload input")?; + for file in &files[1..] { + tokio::time::sleep(Duration::from_millis(300)).await; + open_menu_file_input(engine, menu, item).await?; + engine + .upload_files_to("window.__fmUploadInput", std::slice::from_ref(file)) + .await + .context("Failed to assign file to the Flow upload input")?; + } + Ok(()) } -/// Uploads `files` through the `menu` button and its `upload ` entry. +/// Uploads `files` through the `menu` button and its upload entry. pub(crate) async fn upload_through_menu( engine: &ChromeEngine, menu: &str, @@ -163,6 +265,79 @@ const LIBRARY_MEDIA_MENU: &str = "Add media menu"; /// Menu item text (without the icon name) that uploads files into the project library. const LIBRARY_UPLOAD_ITEM: &str = "Upload"; +/// Uploads images and videos through the workspace menu and returns metadata for saved assets. +async fn upload_project_files_through_menu( + engine: &ChromeEngine, + files: &[String], +) -> Result { + let _store_guard = engine.lock_project_store().await; + crate::project::ensure_project_workspace_root(engine).await?; + crate::project::ensure_flow_store(engine).await?; + let before_snap = crate::assets::list_assets_with_project(engine).await?; + let initial_project_id = before_snap.project_id; + let before: HashSet = before_snap.assets.into_iter().map(|a| a.id).collect(); + + upload_through_menu(engine, LIBRARY_MEDIA_MENU, LIBRARY_UPLOAD_ITEM, files).await?; + + let mut ready_count = 0usize; + for attempt in 0..120 { + let wait_ms = if attempt < 10 { 500 } else { 1000 }; + tokio::time::sleep(Duration::from_millis(wait_ms)).await; + let _ = engine + .call_flow_js("uploadUiAction", json!(["accept_consent"])) + .await; + let snap = crate::assets::list_assets_with_project(engine).await?; + let mut ready = Vec::new(); + for asset in snap.assets { + if before.contains(&asset.id) || !matches!(asset.kind.as_str(), "image" | "video") { + continue; + } + if asset.media_status.as_deref() == Some("failed") || asset.media_error.is_some() { + let detail = asset + .media_error + .unwrap_or_else(|| "upload failed".to_string()); + anyhow::bail!("Menu upload failed for asset '{}': {}", asset.id, detail); + } + if !matches!( + asset.media_status.as_deref(), + Some("pending" | "scheduled" | "canceled") + ) && (asset.primary_media_id.is_some() || asset.url.is_some()) + { + ready.push(asset); + } + } + ready_count = ready.len(); + if ready_count >= files.len() { + let assets: Vec = ready + .into_iter() + .map(|a| { + json!({ + "id": a.id, + "primary_media_id": a.primary_media_id, + "name": a.name, + "kind": a.kind, + "url": a.url, + "width": a.width, + "height": a.height, + "duration": a.duration, + }) + }) + .collect(); + return Ok(json!({ + "project_id": snap.project_id.or(initial_project_id), + "count": assets.len(), + "method": "menu:upload", + "assets": assets, + })); + } + } + anyhow::bail!( + "Uploaded {} of {} files through the Flow menu within 120 seconds", + ready_count, + files.len() + ) +} + /// Returns the IDs of all tiles in the active project. async fn project_tile_ids(engine: &ChromeEngine) -> Result> { let snap = crate::assets::list_assets_with_project(engine).await?; diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 6984ee5..3d1262a 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -21,7 +21,11 @@ import type { import { agentSettingsOp, settingsWritePending } from "./agent_settings"; import type { AgentInjector } from "./agent_settings"; import { adaptAgentWire } from "./agent_wire"; -import { agentChatCompatibility } from "./frontend_compatibility"; +import { + agentAttachmentCompatibility, + agentChatCompatibility, + agentSettingsCompatibility, +} from "./frontend_compatibility"; import { readBuildLabel } from "./frontend_builds"; import type { AgentChatFormat } from "./frontend_builds"; @@ -141,9 +145,10 @@ export function agentBusy(projectId: string): boolean { } /** Checks the frontend build and verifies the native Agent exports. */ -export function agentStatus(projectId: string) { - if (!onProject(projectId) || readBuildLabel() === null) - return failure("agent_page_not_ready"); +export function agentStatus(projectId: string, operation?: "agent_chat" | "agent_settings" | "agent_attachments") { + if (!onProject(projectId) || readBuildLabel() === null) return failure("agent_page_not_ready"); + const extra = operation === "agent_settings" ? agentSettingsCompatibility() : operation === "agent_attachments" ? agentAttachmentCompatibility() : null; + if (extra && !extra.ok) return extra; const compatibility = agentChatCompatibility(); if (!compatibility.ok) return compatibility; const ns = namespace(); diff --git a/ts/angular.ts b/ts/angular.ts index 671b201..385bab7 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -4,7 +4,7 @@ // Shared Angular Ivy LView traversal, router lookup, and scene creation helpers. import { delay, elText, fifeBase } from "./dom"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { projectMutationFormat } from "./frontend_builds"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -232,7 +232,7 @@ export async function createScene( workflowIds: string[], ): Promise<{ ok: boolean; id?: string; error?: string }> { const before = new Set(sceneIds(getMap())); - const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa"; + const resultField = projectMutationFormat()?.sceneCreated ?? "VWa"; let confirmedId: string | undefined; let failure: string | undefined; const completion = { @@ -251,7 +251,9 @@ export async function createScene( De: completion, ve: completion, })).then((response) => { - completion.resolve(readOwn(response, resultField)); + completion.resolve( + readOwn(response, resultField) ?? readOwn(response, "t6a") ?? readOwn(response, "VWa"), + ); }, completion.reject); while (performance.now() < deadline) { diff --git a/ts/character_bio.ts b/ts/character_bio.ts index eaacd4e..c5dd84a 100644 --- a/ts/character_bio.ts +++ b/ts/character_bio.ts @@ -4,7 +4,7 @@ // Write and confirm character personality notes in the project store. import { readOwn } from "./angular"; -import { isTrashedTile } from "./dom"; +import { delay, findSnackbarMatch, isTrashedTile, setNativeValue } from "./dom"; import { characterBioCompatibility } from "./frontend_compatibility"; import { mutateAndVerify, @@ -14,6 +14,7 @@ import { readProjectStore, refreshAfterUnknown, } from "./project_store"; +import { runtimeState } from "./state"; import type { FlowTile } from "./types"; /** Arguments for an operation on character personality notes. */ @@ -103,3 +104,107 @@ export async function characterBioOp( ? { ok: true } : { ok: false, error: "outcome_unknown", stage: "set_character_bio", project_id: projectId, id }; } + +/** Finds the rendered personality notes textarea in the open character editor. */ +function findPersonalityTextarea(): HTMLTextAreaElement | null { + const candidates = Array.from( + document.querySelectorAll( + 'textarea[aria-label="Character personality"], flow-character-form textarea', + ), + ); + return ( + candidates.find((el) => { + const r = el.getBoundingClientRect(); + return r.width > 0 && r.height > 0 && !el.disabled && !el.closest("[inert]"); + }) ?? null + ); +} + +/** Reads personality notes from a store tile across protobuf and flat fields. */ +function readTilePersonalityNotes(tile: FlowTile | undefined): string | null { + if (!tile) return null; + const fromProto = characterPersonalityNotes(tile); + if (fromProto !== null) return fromProto; + if (typeof tile.personalityNotes === "string") return tile.personalityNotes; + if (typeof tile.Mv === "string") return tile.Mv; + return null; +} + +/** Returns true when the discovered store queue still holds pending mutations. */ +function storeQueuePending(): boolean { + const svc = runtimeState.lService; + const getters = [svc?.lc?.ka, svc?._ap?.lc?.ka, svc?.ha?.lc?.ka]; + for (const ka of getters) { + if (typeof ka !== "function") continue; + try { + const q = ka(); + if (Array.isArray(q?.items) && q.items.length > 0) return true; + } catch { + // Ignore unreadable queue handles. + } + } + return false; +} + +/** Saves and confirms character personality notes through the open character editor view. */ +export async function characterBioEditorOp(bio: string): Promise { + let textarea: HTMLTextAreaElement | null = null; + for (let i = 0; i < 25; i++) { + textarea = findPersonalityTextarea(); + if (textarea) break; + await delay(200); + } + if (!textarea) { + return { ok: false, error: "character_bio_editor_not_found" }; + } + + const expected = bio.trim(); + const routeCharId = /\/character\/([^/?#]+)/.exec(location.pathname || "")?.[1] ?? null; + textarea.scrollIntoView({ block: "center" }); + textarea.focus(); + setNativeValue(textarea, bio, true); + + let blurFired = false; + const onBlur = (): void => { + blurFired = true; + }; + textarea.addEventListener("blur", onBlur, { once: true }); + textarea.blur(); + textarea.removeEventListener("blur", onBlur); + if (!blurFired) { + textarea.dispatchEvent(new FocusEvent("blur", { bubbles: false })); + textarea.dispatchEvent(new FocusEvent("focusout", { bubbles: true })); + } + + await delay(400); + for (let i = 0; i < 24; i++) { + const snackErr = findSnackbarMatch(/failed|error|unable|couldn't/i); + if (snackErr) { + return { ok: false, error: "character_bio_save_failed", detail: snackErr }; + } + const live = findPersonalityTextarea() ?? textarea; + if (live.value.trim() !== expected) { + await delay(200); + continue; + } + if (storeQueuePending()) { + await delay(250); + continue; + } + const tileMap = runtimeState.store?.getTileMap?.(); + const tile = routeCharId && tileMap instanceof Map ? tileMap.get(routeCharId) : undefined; + const stored = readTilePersonalityNotes(tile); + if (stored !== null) { + if (stored.trim() === expected) { + return { ok: true, confirmed: true, bio: live.value }; + } + await delay(250); + continue; + } + if (i >= 2) { + return { ok: true, confirmed: true, bio: live.value }; + } + await delay(250); + } + return { ok: false, error: "character_bio_not_confirmed" }; +} diff --git a/ts/character_extra.ts b/ts/character_extra.ts index edabbba..b7d8c12 100644 --- a/ts/character_extra.ts +++ b/ts/character_extra.ts @@ -13,7 +13,12 @@ import { isVisibleEnabled, setNativeValue, } from "./dom"; -import { frontendBuild, readBuildLabel, type VoiceConfirmationFormat } from "./frontend_builds"; +import { + frontendBuild, + readBuildLabel, + voiceConfirmationFormats, + type VoiceConfirmationFormat, +} from "./frontend_builds"; import type { CharacterExtraOpRequest } from "./types"; import { bindCustomVoiceReceipt, bindVoiceConfirmation } from "./voice_confirmation"; @@ -198,7 +203,7 @@ function paneButton(pane: Element, re: RegExp): HTMLElement | null { async function saveCustomVoice( pane: Element, { sample, performance, name, deadline }: CustomVoiceInput, - format?: VoiceConfirmationFormat, + formats: readonly VoiceConfirmationFormat[], ): Promise { const sampleEl = field(pane, /hi there/i); const perfEl = field(pane, /performance style/i); @@ -228,7 +233,11 @@ async function saveCustomVoice( const oldRows = new Set(renderedRows(voicePane() ?? pane) .filter((row) => row.custom && row.name === savedName) .map((row) => row.el)); - const receipt = format && bindCustomVoiceReceipt(voicePane() ?? pane, format); + let receipt: ReturnType; + for (const format of formats) { + receipt = bindCustomVoiceReceipt(voicePane() ?? pane, format); + if (receipt) break; + } try { save.click(); // Flow can keep Add to character active for the base voice during the save. @@ -290,11 +299,20 @@ async function applyVoice( const custom = Boolean(sample || performance); if (custom && sample.length > 120) return { ok: false, error: "voice_sample_over_120_characters" }; - const format = frontendBuild(readBuildLabel())?.voiceConfirmation; - let pane = format ? await withLViewMapCapture(openDialog) : await openDialog(); + const formats = voiceConfirmationFormats(); + const requireConfirmation = Boolean(frontendBuild(readBuildLabel())?.voiceConfirmation); + let pane = formats.length > 0 ? await withLViewMapCapture(openDialog) : await openDialog(); if (!pane) return { ok: false, error: "voice_dialog_not_available" }; - const confirm = format && bindVoiceConfirmation(format); - if (format && !confirm) { + let confirm: ReturnType; + let activeFormats = formats; + for (const candidate of formats) { + confirm = bindVoiceConfirmation(candidate); + if (confirm) { + activeFormats = [candidate]; + break; + } + } + if (requireConfirmation && !confirm) { await dismissOverlay(); return { ok: false, error: "voice_confirmation_unavailable" }; } @@ -310,7 +328,11 @@ async function applyVoice( let expected = base; let expectedId: string | undefined; if (custom) { - const result = await saveCustomVoice(voicePane() ?? pane, { sample, performance, name, deadline }, format); + const result = await saveCustomVoice( + voicePane() ?? pane, + { sample, performance, name, deadline }, + activeFormats, + ); if ("error" in result) { await dismissOverlay(); return { ok: false, ...result }; diff --git a/ts/character_media.ts b/ts/character_media.ts index c52e5b3..7701916 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -24,7 +24,11 @@ import { pickTileUrl, setNativeValue, } from "./dom"; -import { frontendBuild, readBuildLabel, type CharacterPreviewFormat } from "./frontend_builds"; +import { + characterPreviewFormats, + frontendBuild, + readBuildLabel, +} from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; import { runtimeState } from "./state"; import type { @@ -51,11 +55,6 @@ interface CharacterPreview { busy: () => unknown; } -/** Native methods used by the earlier preview panel. */ -const LEGACY_PREVIEW: CharacterPreviewFormat = { - lifecycle: "Ca", upload: "JR", marker: "Si", portrait: "ka", body: "ma", source: "psa", busy: "zy", -}; - /** Snapshot of character preview slot state read from component signals and DOM. */ interface PreviewSlotState { /** Resolved preview component instance when mounted. */ @@ -90,46 +89,47 @@ function callPanel(panel: object, name: string): unknown { return typeof method === "function" ? method.call(panel) : undefined; } -/** Finds the preview panel in a live Angular view and binds its methods. */ +/** Finds the preview panel in a live Angular view and binds its methods from newest to oldest format. */ function getCharacterPreviewInstance(): CharacterPreview | null { - const format = frontendBuild(readBuildLabel())?.characterPreview ?? LEGACY_PREVIEW; const roots = document.querySelectorAll( "flow-character-preview-panel, flow-character-image-preview", ); - const seen = new Set(); - for (const root of roots) { - const startLv = resolveLView(root); - if (!Array.isArray(startLv)) continue; - const queue: Array<[NgLView, number]> = [[startLv, 0]]; - while (queue.length > 0) { - const next = queue.shift(); - if (!next) break; - const [lv, depth] = next; - if (!Array.isArray(lv) || seen.has(lv)) continue; - seen.add(lv); - for (const slot of lv) { - if ( - slot && - typeof slot === "object" && - !(slot instanceof Node) && - !Array.isArray(slot) && - !(slot instanceof Map) && - !readOwn(readOwn(slot, format.lifecycle), "Va") && - typeof readOwn(slot, format.upload) === "function" && - typeof readOwn(slot, format.marker) === "function" - ) { - return { - upload: () => callPanel(slot, format.upload), - media: (which) => - legacyMedia(callPanel(slot, format[which]) as FlowMediaPayload | null | undefined), - source: () => callPanel(slot, format.source), - busy: () => callPanel(slot, format.busy), - }; + for (const format of characterPreviewFormats()) { + const seen = new Set(); + for (const root of roots) { + const startLv = resolveLView(root); + if (!Array.isArray(startLv)) continue; + const queue: Array<[NgLView, number]> = [[startLv, 0]]; + while (queue.length > 0) { + const next = queue.shift(); + if (!next) break; + const [lv, depth] = next; + if (!Array.isArray(lv) || seen.has(lv)) continue; + seen.add(lv); + for (const slot of lv) { + if ( + slot && + typeof slot === "object" && + !(slot instanceof Node) && + !Array.isArray(slot) && + !(slot instanceof Map) && + !readOwn(readOwn(slot, format.lifecycle), "Va") && + typeof readOwn(slot, format.upload) === "function" && + typeof readOwn(slot, format.marker) === "function" + ) { + return { + upload: () => callPanel(slot, format.upload), + media: (which) => + legacyMedia(callPanel(slot, format[which]) as FlowMediaPayload | null | undefined), + source: () => callPanel(slot, format.source), + busy: () => callPanel(slot, format.busy), + }; + } + } + if (depth < 4) { + if (Array.isArray(lv[3])) queue.push([lv[3], depth + 1]); + if (Array.isArray(lv[15])) queue.push([lv[15], depth + 1]); } - } - if (depth < 4) { - if (Array.isArray(lv[3])) queue.push([lv[3], depth + 1]); - if (Array.isArray(lv[15])) queue.push([lv[15], depth + 1]); } } } @@ -267,7 +267,10 @@ export async function characterMediaOp( const controls = [...document.querySelectorAll("flow-character-preview-panel [mattooltip], flow-character-preview-panel button")]; await withLViewMapCapture(() => hoverProbe(controls.slice(0, 6))); state = readPreviewSlotState(wantSlot); - if (!state.previewComp && frontendBuild(readBuildLabel())?.characterPreview) { + if ( + !state.previewComp && + (Boolean(frontendBuild(readBuildLabel())?.characterPreview) || !findPreviewUploadButton()) + ) { return { ok: false, error: "character_preview_not_bound" }; } } diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 0307d4a..db1efad 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -629,6 +629,36 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ }], ]); +/** Native methods used by the earlier character preview panel. */ +const LEGACY_CHARACTER_PREVIEW: CharacterPreviewFormat = { + lifecycle: "Ca", + upload: "JR", + marker: "Si", + portrait: "ka", + body: "ma", + source: "psa", + busy: "zy", +}; + +/** Returns verified builds ordered from newest to oldest. */ +function newestFirstBuilds(): FrontendBuild[] { + return Array.from(VERIFIED_BUILDS.values()).reverse(); +} + +/** Keeps the first item for each key while preserving order. */ +function uniqueFormats(items: readonly T[], keyOf: (item: T) => string): T[] { + const seen = new Set(); + const out: T[] = []; + for (const item of items) { + const key = keyOf(item); + if (!seen.has(key)) { + seen.add(key); + out.push(item); + } + } + return out; +} + /** Returns the exact label published by the active page. */ export function readBuildLabel(): string | null { const label = window.WIZ_global_data?.cfb2h; @@ -640,8 +670,55 @@ export function frontendBuild(label: string | null): FrontendBuild | undefined { return label === null ? undefined : VERIFIED_BUILDS.get(label); } -/** Returns the layouts to check when the runtime binds the active project store. */ +/** Returns the layouts to check from newest to oldest when the runtime binds the active project store. */ export function projectStoreFormats(): readonly ProjectStoreFormat[] { - const format = frontendBuild(readBuildLabel())?.projectStore; - return format ? [format] : [NOVEMBER_17_STORE, NOVEMBER_18_STORE]; + const build = frontendBuild(readBuildLabel()); + if (build) return [build.projectStore]; + return uniqueFormats( + newestFirstBuilds().map((entry) => entry.projectStore), + (format) => JSON.stringify(format), + ); +} + +/** Returns character preview layouts from newest to oldest for the active build. */ +export function characterPreviewFormats(): readonly CharacterPreviewFormat[] { + const build = frontendBuild(readBuildLabel()); + if (build) return [build.characterPreview ?? LEGACY_CHARACTER_PREVIEW]; + const candidates = newestFirstBuilds() + .flatMap((entry) => (entry.characterPreview ? [entry.characterPreview] : [])); + return uniqueFormats( + [...candidates, LEGACY_CHARACTER_PREVIEW], + (format) => JSON.stringify(format), + ); +} + +/** Returns voice confirmation layouts from newest to oldest for the active build. */ +export function voiceConfirmationFormats(): readonly VoiceConfirmationFormat[] { + const build = frontendBuild(readBuildLabel()); + if (build) return build.voiceConfirmation ? [build.voiceConfirmation] : []; + return uniqueFormats( + newestFirstBuilds().flatMap((entry) => + entry.voiceConfirmation ? [entry.voiceConfirmation] : [], + ), + (format) => JSON.stringify(format), + ); +} + +/** Returns scene tile field layouts from newest to oldest for the active build. */ +export function sceneTileFormats(): readonly SceneTileFormat[] { + const build = frontendBuild(readBuildLabel()); + if (build) return build.projectStore.scene ? [build.projectStore.scene] : []; + return uniqueFormats( + newestFirstBuilds().flatMap((entry) => + entry.projectStore.scene ? [entry.projectStore.scene] : [], + ), + (format) => `${format.clips}:${format.history}`, + ); +} + +/** Returns the mutation field layout for the active build, defaulting to the newest verified layout on unknown builds. */ +export function projectMutationFormat(): ProjectMutationFormat | undefined { + const build = frontendBuild(readBuildLabel()); + if (build) return build.projectStore.mutations; + return newestFirstBuilds().find((entry) => entry.projectStore.mutations)?.projectStore.mutations; } diff --git a/ts/frontend_compatibility.ts b/ts/frontend_compatibility.ts index c74127e..03206ef 100644 --- a/ts/frontend_compatibility.ts +++ b/ts/frontend_compatibility.ts @@ -3,7 +3,12 @@ // Check the build and runtime requirements of internal Flow operations. -import { frontendBuild, MEDIA_UPLOAD_EXPORTS, readBuildLabel } from "./frontend_builds"; +import { + frontendBuild, + MEDIA_UPLOAD_EXPORTS, + projectMutationFormat, + readBuildLabel, +} from "./frontend_builds"; import type { AgentAttachmentFormat, AgentChatFormat, @@ -38,7 +43,7 @@ type FrontendCompatibility = { ok: true; format: Format } | UnsupportedF /** Adds the native fields used by the general project store. */ export function withMutationAliases(payload: Record): Record { - const format = frontendBuild(readBuildLabel())?.projectStore.mutations; + const format = projectMutationFormat(); if (payload.type === "single_tile" && payload.Ve && typeof payload.Ve === "object") { if (!format) return { ...payload, We: payload.We ?? payload.Ve, df: payload.df ?? payload.Ve }; const change = payload.Ve as Record; diff --git a/ts/index.ts b/ts/index.ts index 41f0ea3..f5c4fc1 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -16,7 +16,7 @@ import { } from "./agent_chat"; import { bindAngularViews } from "./angular"; import { attachIngredients } from "./attach_ingredients"; -import { characterBioOp } from "./character_bio"; +import { characterBioEditorOp, characterBioOp } from "./character_bio"; import { characterExtraOp } from "./character_extra"; import { characterMediaOp } from "./character_media"; import { characterOp } from "./character_ops"; @@ -79,6 +79,7 @@ if (!window.__flowMcp) { videoOp, characterOp, characterBioOp, + characterBioEditorOp, characterVoiceOp, characterMediaOp, characterExtraOp, diff --git a/ts/page_view.ts b/ts/page_view.ts index 7137778..f97941b 100644 --- a/ts/page_view.ts +++ b/ts/page_view.ts @@ -62,25 +62,60 @@ function isRendered(el: Element): boolean { return el.getClientRects().length > 0; } -/** Returns the text input of the asset rename control. */ -function renameControl(): HTMLInputElement | null { - const host = Array.from(document.querySelectorAll('[aria-label="Rename tile"]')).find(isRendered); - const input = host?.querySelector("input"); - return input instanceof HTMLInputElement ? input : null; +/** Returns the viewport center of `el`. */ +function centerPoint(el: Element): { x: number; y: number } { + const r = el.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; } -/** Selects the text of the focused rename control. */ -export function selectText(): Record { - const el = renameControl(); +/** Returns the rendered text input for `control` (`tile`, `item`, or `title`). */ +function findTextControl(control: string, current: string): HTMLInputElement | null { + const kind = control || "tile"; + if (kind === "title") { + const inputs = Array.from( + document.querySelectorAll('input[aria-label="Editable text"]'), + ).filter(isRendered); + const active = inputs.find((el) => document.activeElement === el); + if (active) return active; + if (current) { + const exact = inputs.find((el) => el.value.trim() === current.trim()); + if (exact) return exact; + } + return inputs[0] ?? null; + } + const itemInput = Array.from( + document.querySelectorAll('input[aria-label="Rename item"]'), + ).find(isRendered); + const tileHost = Array.from(document.querySelectorAll('[aria-label="Rename tile"]')).find( + isRendered, + ); + const tileInput = tileHost?.querySelector("input"); + const resolvedTile = tileInput instanceof HTMLInputElement ? tileInput : null; + if (kind === "item") { + return itemInput ?? resolvedTile; + } + return resolvedTile ?? itemInput ?? null; +} + +/** Returns the click point of the requested text control. */ +export function textPoint(control = "tile", current = ""): Record { + const el = findTextControl(control, current); + if (!el) return { ok: false, error: "text_control_not_found" }; + return { ok: true, point: centerPoint(el) }; +} + +/** Selects the text of the focused rename or title control. */ +export function selectText(control = "tile", current = ""): Record { + const el = findTextControl(control, current); if (!el) return { ok: false, error: "text_control_not_found" }; const focused = document.activeElement === el; if (focused) el.select(); return { ok: true, focused, value: el.value }; } -/** Returns the text in the rename control. */ -export function readText(): Record { - const el = renameControl(); +/** Returns the text in the requested rename or title control. */ +export function readText(control = "tile", current = ""): Record { + const el = findTextControl(control, current); if (!el) return { ok: false, error: "text_control_not_found" }; return { ok: true, value: el.value }; } diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index 2b31842..fc6f906 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -8,6 +8,9 @@ import { delay } from "./dom"; import { runtimeState } from "./state"; import type { FlowTile, SceneOpRequest } from "./types"; +/** Maximum time to wait for a scene clip addition callback to settle. */ +const SCENE_ADD_CLIPS_TIMEOUT_MS = 10_000; + /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { const helper = runtimeState.store; @@ -48,25 +51,63 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } + const timeoutMs = + typeof req?.timeout_ms === "number" && req.timeout_ms > 0 + ? Math.min(req.timeout_ms, SCENE_ADD_CLIPS_TIMEOUT_MS) + : SCENE_ADD_CLIPS_TIMEOUT_MS; let resolveDe: (v: unknown) => void = () => {}; let rejectDe: (e: unknown) => void = () => {}; const dePromise = new Promise((res, rej) => { resolveDe = res; rejectDe = rej; }); - await helper.mutate({ - type: "add_workflows_to_scene", - Lc: sceneId, - Ic: sceneId, - rg: resolveWfIds(assetIds), - YWa: resolveWfIds(assetIds), - position: typeof req.position === "number" ? req.position : undefined, - Mh: undefined, - Eh: undefined, - De: { resolve: resolveDe, reject: rejectDe }, - ve: { resolve: resolveDe, reject: rejectDe }, - }); - await dePromise; + void dePromise.catch(() => undefined); + const workflows = resolveWfIds(assetIds); + try { + await helper.mutate({ + type: "add_workflows_to_scene", + Lc: sceneId, + Ic: sceneId, + rg: workflows, + YWa: workflows, + position: typeof req.position === "number" ? req.position : undefined, + Mh: undefined, + Eh: undefined, + De: { resolve: resolveDe, reject: rejectDe }, + ve: { resolve: resolveDe, reject: rejectDe }, + }); + } catch (error) { + return { + ok: false, + error: "scene_add_clips_failed", + scene_id: sceneId, + detail: error instanceof Error ? error.message : String(error), + }; + } + let timer: ReturnType | undefined; + try { + const outcome = await Promise.race([ + dePromise.then( + () => ({ ok: true as const }), + (error: unknown) => ({ + ok: false as const, + error: "scene_add_clips_failed" as const, + detail: error instanceof Error ? error.message : String(error), + }), + ), + new Promise<{ ok: false; error: "scene_add_clips_timeout" }>((resolve) => { + timer = setTimeout( + () => resolve({ ok: false, error: "scene_add_clips_timeout" }), + timeoutMs, + ); + }), + ]); + if (!outcome.ok) { + return { ...outcome, scene_id: sceneId }; + } + } finally { + if (timer !== undefined) clearTimeout(timer); + } await delay(400); return { ok: true, scene_id: sceneId, added: assetIds.length }; } diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..59e0aee 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -4,14 +4,30 @@ // Read clips and workflow history from the native scene tile. import { readOwn } from "./angular"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { sceneTileFormats } from "./frontend_builds"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +/** Returns true when `value` is a workflow history map or plain record. */ +function isHistoryRecord(value: unknown): boolean { + return value instanceof Map || (Boolean(value) && typeof value === "object" && !Array.isArray(value)); +} + /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { - const format = frontendBuild(readBuildLabel())?.projectStore.scene; - const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; - const history = (format && readOwn(tile, format.history)) ?? tile.Yf; + let clips: unknown; + let history: unknown; + for (const format of sceneTileFormats()) { + if (!Array.isArray(clips)) { + const candidate = readOwn(tile, format.clips); + if (Array.isArray(candidate)) clips = candidate; + } + if (!isHistoryRecord(history)) { + const candidate = readOwn(tile, format.history); + if (isHistoryRecord(candidate)) history = candidate; + } + } + if (!Array.isArray(clips)) clips = tile.Oc; + if (!isHistoryRecord(history)) history = tile.Yf; const entries: Iterable<[string, FlowMediaPayload[]]> = history instanceof Map ? history.entries() : history && typeof history === "object" ? Object.entries(history) : []; diff --git a/ts/tile_dom.ts b/ts/tile_dom.ts index 4a7c450..5743583 100644 --- a/ts/tile_dom.ts +++ b/ts/tile_dom.ts @@ -3,16 +3,55 @@ // Locate project tiles in the page, read their state from the bound store, and dispatch page view and text control actions. -import { collectionIdOf, delay, dismissOverlay, isTrashedTile, legacyTile } from "./dom"; -import { openView, readText, readView, selectText } from "./page_view"; +import { readOwn, resolveLView } from "./angular"; +import { + characterLooksOf, + collectionIdOf, + delay, + dismissOverlay, + fifeBase, + isTrashedTile, + legacyTile, +} from "./dom"; +import { openView, readText, readView, selectText, textPoint } from "./page_view"; +import { sceneContents } from "./scene_tiles"; import { runtimeState } from "./state"; import type { FlowTile, TileDomOpRequest, ViewportPoint } from "./types"; +/** Lowercase tile kind for a store tile. */ +function kindOf(raw: FlowTile | null | undefined): string { + return String(raw?.type || "").toLowerCase(); +} + +/** Normalizes a media URL to its `/asb/...` token or FIFE base URL for DOM matching. */ +function normalizedMediaKey(rawUrl: unknown): string { + const base = fifeBase(rawUrl); + if (!base) return ""; + const asb = /(\/asb\/[^/?#=]+)/.exec(base); + return asb ? asb[1] : base; +} + /** Returns the media IDs that the page can show for the store tile `raw`. */ function mediaIdsOf(raw: FlowTile | null | undefined): string[] { + if (!raw) return []; const t = legacyTile(raw); if (!t) return []; - const ids = [t.primaryMediaId, t.Fb?.id, t.Fb?.mediaId, t.mediaId]; + const ids: unknown[] = [t.primaryMediaId, t.Fb?.id, t.Fb?.mediaId, t.mediaId]; + const looks = characterLooksOf(raw); + if (looks instanceof Map) { + for (const entry of looks.values()) { + ids.push(entry?.primaryMediaId, entry?.media?.id, entry?.media?.mediaId); + if (Array.isArray(entry?.history)) { + for (const item of entry.history) { + ids.push(item?.primaryMediaId, item?.media?.id); + } + } + } + } + const { clips } = sceneContents(raw); + for (const clip of clips) { + ids.push(clip?.primaryMediaId, clip?.workflowId); + } return Array.from( new Set( ids @@ -22,30 +61,185 @@ function mediaIdsOf(raw: FlowTile | null | undefined): string[] { ); } -/** Returns true when a store tile other than `id` shows one of `mediaIds`. */ -function mediaIsShared( +/** Returns normalized media URL keys that a rendered tile element can carry in `src`. */ +function mediaUrlsOf(raw: FlowTile | null | undefined): string[] { + if (!raw) return []; + const t = legacyTile(raw); + if (!t) return []; + const urls: unknown[] = [ + t.ue, + t.Wb, + t.fifeUrl, + t.imageUrl, + t.videoUrl, + t.url, + t.Fb?.Wb, + t.Fb?.fifeUrl, + t.Fb?.Bd, + t.Fb?.uA, + t.Fb?.videoUrl, + t.Fb?.imageUrl, + t.Fb?.url, + ]; + const looks = characterLooksOf(raw); + if (looks instanceof Map) { + for (const entry of looks.values()) { + urls.push(entry?.Wb, entry?.fifeUrl, entry?.imageUrl, entry?.url, entry?.media?.Wb); + } + } + const { clips } = sceneContents(raw); + for (const clip of clips) { + urls.push(clip?.Wb, clip?.fifeUrl, clip?.Bd, clip?.uA, clip?.videoUrl); + } + return Array.from( + new Set( + urls + .map(normalizedMediaKey) + .filter((v) => v.length > 0), + ), + ); +} + +/** Returns true when another active tile in the same view shares any value from `values`. */ +function valuesSharedInView( tileMap: Map, id: string, - mediaIds: string[], + viewCollection: string | null, + isCollectionId: (v: string) => boolean, + extract: (tile: FlowTile) => string[], + values: string[], ): boolean { for (const [otherId, other] of tileMap.entries()) { - if (otherId === id) continue; - if (mediaIdsOf(other).some((m) => mediaIds.includes(m))) return true; + if (otherId === id || isTrashedTile(other)) continue; + if (collectionIdOf(other, isCollectionId) !== viewCollection) continue; + if (extract(other).some((item) => values.includes(item))) return true; } return false; } +/** Returns true when `el` is rendered with non-zero layout bounds. */ +function isRendered(el: Element): boolean { + const r = el.getBoundingClientRect(); + return r.width > 0 && r.height > 0; +} + +/** Checks whether an Angular context on `container` or its child tile host binds `id`. */ +function containerBindsTileId(container: HTMLElement, id: string, raw: FlowTile): boolean { + if ( + container.getAttribute("data-tile-id") === id || + container.getAttribute("data-item-id") === id + ) { + return true; + } + const hosts: Element[] = [ + container, + ...Array.from( + container.querySelectorAll( + "flow-image-tile, flow-video-tile, flow-character-tile, flow-scene-tile, flow-collection-tile", + ), + ), + ]; + for (const host of hosts) { + if ( + host.getAttribute("data-tile-id") === id || + host.getAttribute("data-item-id") === id + ) { + return true; + } + const lview = resolveLView(host); + if (!Array.isArray(lview)) continue; + for (let i = 0; i < Math.min(lview.length, 80); i++) { + const slot = lview[i]; + if (!slot || typeof slot !== "object") continue; + if (slot === raw) return true; + if (readOwn(slot, "id") === id && typeof readOwn(slot, "type") === "string") { + return true; + } + for (const key of Object.keys(slot)) { + const val = readOwn(slot, key); + if (val === raw) return true; + if (val && typeof val === "object" && readOwn(val, "id") === id) { + return true; + } + if ( + typeof val === "function" && + val.length === 0 && + Object.getOwnPropertySymbols(val).length > 0 + ) { + try { + const sigVal = val.call(slot); + if (sigVal === raw || (sigVal && typeof sigVal === "object" && readOwn(sigVal, "id") === id)) { + return true; + } + } catch { + // Ignore signal read failures. + } + } + } + } + } + return false; +} + +/** Returns true when `container` renders the child host expected for `kind`. */ +function containerMatchesKind(container: HTMLElement, kind: string): boolean { + const attr = (container.getAttribute("data-tile-kind") || "").toLowerCase(); + if (attr) return attr === kind; + if (kind === "collection") { + if (container.querySelector("flow-collection-tile")) return true; + return !container.querySelector( + "flow-image-tile, flow-video-tile, flow-character-tile, flow-scene-tile, [data-media-id]", + ); + } + if (kind === "character") return Boolean(container.querySelector("flow-character-tile")); + if (kind === "scene") return Boolean(container.querySelector("flow-scene-tile")); + if (kind === "image") return Boolean(container.querySelector("flow-image-tile")); + if (kind === "video") return Boolean(container.querySelector("flow-video-tile")); + return false; +} + +/** Returns true when `container` exposes the exact display title `title`. */ +function containerMatchesTitle(container: HTMLElement, title: string): boolean { + const want = title.trim(); + if (!want) return false; + if ((container.getAttribute("aria-label") || "").trim() === want) return true; + for (const el of Array.from(container.querySelectorAll("*"))) { + if ((el.getAttribute("aria-label") || "").trim() === want) return true; + if (el.children.length === 0 && (el.textContent || "").trim() === want) { + return true; + } + } + return false; +} + +/** Returns the rendered grid tiles that match `predicate`. */ +function findMatchingContainers(predicate: (el: HTMLElement) => boolean): HTMLElement[] { + return Array.from(document.querySelectorAll("flow-grid-tile-container")).filter( + (el) => isRendered(el) && predicate(el), + ); +} + /** Returns the rendered grid tiles that show one of `mediaIds`. */ -function findContainers(mediaIds: string[]): HTMLElement[] { +function findContainersByMediaIds(mediaIds: string[]): HTMLElement[] { const found = new Set(); for (const el of Array.from(document.querySelectorAll("[data-media-id]"))) { if (!mediaIds.includes(el.getAttribute("data-media-id") || "")) continue; const container = el.closest("flow-grid-tile-container"); - if (container) found.add(container); + if (container && isRendered(container)) found.add(container); } return Array.from(found); } +/** Returns the rendered grid tiles whose media `src` matches one of `urls`. */ +function findContainersByUrls(urls: string[]): HTMLElement[] { + return findMatchingContainers((container) => + Array.from(container.querySelectorAll("img[src], video[src]")).some((media) => { + const key = normalizedMediaKey(media.getAttribute("src")); + return Boolean(key && urls.includes(key)); + }), + ); +} + /** Returns the viewport center of `el`. */ function centerOf(el: Element): ViewportPoint { const r = el.getBoundingClientRect(); @@ -108,20 +302,143 @@ async function locateContainer(find: () => HTMLElement[]): Promise> { const tileMap = runtimeState.store?.getTileMap?.(); if (!(tileMap instanceof Map)) return { ok: false, error: "store_not_bound" }; - const mediaIds = mediaIdsOf(tileMap.get(id)); - if (mediaIds.length === 0) return { ok: false, error: "tile_media_id_unknown" }; - // The page has no tile ID. A media ID that two tiles show cannot identify one tile. - if (mediaIsShared(tileMap, id, mediaIds)) { + const raw = tileMap.get(id); + if (!raw || isTrashedTile(raw)) return { ok: false, error: "tile_not_found" }; + + const isCollectionId = (v: string): boolean => + String(tileMap.get(v)?.type || "").toUpperCase() === "COLLECTION"; + const viewCollection = collectionIdOf(raw, isCollectionId); + const kind = kindOf(raw); + const title = String(raw.displayName ?? "").trim(); + + const mediaIds = mediaIdsOf(raw); + const canUseMediaIds = + mediaIds.length > 0 && + !valuesSharedInView(tileMap, id, viewCollection, isCollectionId, mediaIdsOf, mediaIds); + + const mediaUrls = mediaUrlsOf(raw); + const canUseUrls = + mediaUrls.length > 0 && + !valuesSharedInView(tileMap, id, viewCollection, isCollectionId, mediaUrlsOf, mediaUrls); + + const titleOfKind = (tile: FlowTile): string[] => { + if (kindOf(tile) !== kind) return []; + const name = String(tile.displayName ?? "").trim(); + return name ? [name] : []; + }; + const canUseTitle = + title.length > 0 && + !valuesSharedInView(tileMap, id, viewCollection, isCollectionId, titleOfKind, [title]); + + const find = (): HTMLElement[] => { + const byBinding = findMatchingContainers((el) => containerBindsTileId(el, id, raw)); + if (byBinding.length > 0) return byBinding; + if (canUseMediaIds) { + const byMedia = findContainersByMediaIds(mediaIds); + if (byMedia.length > 0) return byMedia; + } + if (canUseUrls) { + const byUrl = findContainersByUrls(mediaUrls); + if (byUrl.length > 0) return byUrl; + } + if (canUseTitle) { + const byTitle = findMatchingContainers( + (el) => containerMatchesKind(el, kind) && containerMatchesTitle(el, title), + ); + if (byTitle.length > 0) return byTitle; + } + return []; + }; + + if (!canUseMediaIds && !canUseUrls && !canUseTitle) { + // Try exact Angular view binding before reporting ambiguity. + const exact = await locateContainer(() => + findMatchingContainers((el) => containerBindsTileId(el, id, raw)), + ); + if (exact.ok) return exact; return { ok: false, error: "tile_media_ambiguous" }; } - return locateContainer(() => findContainers(mediaIds)); + return locateContainer(find); +} + +/** Expands the library sidebar if it is collapsed. */ +async function ensureSidebarExpanded(): Promise { + const toggle = Array.from( + document.querySelectorAll( + 'button.library-expand-button, button[aria-label="Toggle library"]', + ), + ).find((el) => isRendered(el) && el.getAttribute("aria-expanded") !== "true"); + if (toggle && !document.querySelector("flow-nested-list")) { + toggle.click(); + await delay(350); + } +} + +/** Finds a rendered sidebar row or grid folder tile that accepts drops for collection `id`. */ +async function locateDropTarget(id: string): Promise> { + const findSidebarRow = (): HTMLElement | null => { + for (const el of Array.from(document.querySelectorAll("[data-item-id]"))) { + if (el.getAttribute("data-item-id") === id && isRendered(el)) return el; + } + return null; + }; + let row = findSidebarRow(); + if (!row) { + await ensureSidebarExpanded(); + row = findSidebarRow(); + } + if (row) { + row.scrollIntoView({ block: "center" }); + await delay(150); + const refreshed = findSidebarRow() ?? row; + return { ok: true, target: centerOf(refreshed) }; + } + const tileLoc = await locateTile(id); + if (tileLoc.ok && tileLoc.tile) { + return { ok: true, target: tileLoc.tile }; + } + return { ok: false, error: "drop_target_not_found" }; } -/** Returns `present`, `trashed`, or `gone` for the store tile `id`, with its name and its collection ID while it is present. */ +/** Finds the sidebar root drop zone that moves items out of a collection. */ +async function locateRootDropTarget(): Promise> { + const findRoot = (): HTMLElement | null => { + const direct = Array.from( + document.querySelectorAll( + "[flowNestedListRootDropZone], [flownestedlistrootdropzone], flow-nested-list [data-item-id='']", + ), + ).find(isRendered); + if (direct) return direct; + return ( + Array.from( + document.querySelectorAll( + "flow-nested-list button, flow-nested-list a, flow-nested-list [role='treeitem']", + ), + ).find( + (el) => + isRendered(el) && + !el.hasAttribute("data-item-id") && + /^(?:all\s+media|library|all\s+items|project)$/i.test((el.textContent || "").trim()), + ) ?? null + ); + }; + let root = findRoot(); + if (!root) { + await ensureSidebarExpanded(); + root = findRoot(); + } + if (!root) return { ok: false, error: "root_drop_target_not_found" }; + root.scrollIntoView({ block: "center" }); + await delay(150); + const refreshed = findRoot() ?? root; + return { ok: true, target: centerOf(refreshed) }; +} + +/** Returns `present`, `trashed`, or `gone` for the store tile `id`, with kind, name, collection, and members. */ function tileState(id: string): Record { const tileMap = runtimeState.store?.getTileMap?.(); if (!(tileMap instanceof Map)) return { ok: false, error: "store_not_bound" }; @@ -129,24 +446,75 @@ function tileState(id: string): Record { if (!t) return { ok: true, state: "gone" }; const isCollectionId = (v: string): boolean => String(tileMap.get(v)?.type || "").toUpperCase() === "COLLECTION"; + const kind = kindOf(t); + let count = 0; + const memberIds: string[] = []; + let hasChildCollections = false; + if (kind === "collection") { + for (const [otherId, other] of tileMap.entries()) { + if (otherId === id || isTrashedTile(other)) continue; + if (collectionIdOf(other, isCollectionId) !== id) continue; + if (kindOf(other) === "collection") { + hasChildCollections = true; + } else { + if (other.type === "SCENE" && other.isPending === true) continue; + count += 1; + memberIds.push(String(other.id ?? otherId)); + } + } + } return { ok: true, state: isTrashedTile(t) ? "trashed" : "present", + kind, name: String(t.displayName ?? ""), collection: collectionIdOf(t, isCollectionId), + count, + member_ids: memberIds, + has_child_collections: hasChildCollections, + }; +} + +/** Dispatches an HTML5 DragEvent sequence from `(sx, sy)` to `(tx, ty)` when native drag attributes are used. */ +async function html5Drag(coords?: [number, number, number, number]): Promise> { + if (!Array.isArray(coords) || coords.length !== 4) return { ok: false, error: "invalid_coords" }; + const [sx, sy, tx, ty] = coords; + const rawSrc = document.elementFromPoint(sx, sy); + const src = rawSrc?.closest("[draggable='true'], flow-grid-tile-container") ?? rawSrc; + const dst = document.elementFromPoint(tx, ty); + if (!src || !dst) return { ok: false, error: "drag_element_not_found" }; + const dt = new DataTransfer(); + const fire = (target: Element, type: string, x: number, y: number): void => { + target.dispatchEvent( + new DragEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, dataTransfer: dt }), + ); }; + fire(src, "dragstart", sx, sy); + await delay(60); + fire(dst, "dragenter", tx, ty); + fire(dst, "dragover", tx, ty); + await delay(60); + fire(dst, "drop", tx, ty); + fire(src, "dragend", tx, ty); + return { ok: true }; } -/** Finds an asset tile, changes the grid view, or uses the asset rename control. */ +/** Finds an asset tile, locates a drop target, changes the grid view, or uses a page text control. */ export async function tileDomOp(req: TileDomOpRequest): Promise { const action = String(req?.action || ""); const id = String(req?.id || ""); + const control = String(req?.control || "tile"); + const name = String(req?.name || ""); if (action === "locate") return locateTile(id); + if (action === "drop_target") return locateDropTarget(id); + if (action === "root_drop_target") return locateRootDropTarget(); + if (action === "html5_drag") return html5Drag(req?.coords); if (action === "state") return tileState(id); if (action === "view") return readView(); if (action === "open_view") return openView(id); - if (action === "text_select") return selectText(); - if (action === "text_value") return readText(); + if (action === "text_point") return textPoint(control, name); + if (action === "text_select") return selectText(control, name); + if (action === "text_value") return readText(control, name); if (action === "dismiss") { await dismissOverlay(); return { ok: true }; diff --git a/ts/types.ts b/ts/types.ts index 918312d..4038b3f 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -583,6 +583,8 @@ export interface SceneOpRequest { scene_id?: string | null; /** Optional insertion position index. */ position?: number | null; + /** Optional confirmation timeout in milliseconds for `add_clips`. */ + timeout_ms?: number | null; } /** Request payload for `videoOp`. */ @@ -687,10 +689,16 @@ export interface LocatePointRequest { /** Request for `tileDomOp`. */ export interface TileDomOpRequest { - /** `locate`, `state`, `view`, `open_view`, `text_select`, `text_value`, or `dismiss`. */ + /** `locate`, `drop_target`, `root_drop_target`, `html5_drag`, `state`, `view`, `open_view`, `text_point`, `text_select`, `text_value`, or `dismiss`. */ action: string; - /** Store tile ID for `locate` and `state`, or the collection ID for `open_view` (empty for the main grid). */ + /** Store tile ID for `locate` and `state`, or the collection ID for `open_view` and `drop_target` (empty for the main grid). */ id?: string; + /** Text control kind (`tile`, `item`, or `title`) for `text_point`, `text_select`, and `text_value`. */ + control?: string; + /** Expected current text or display name for text controls and drop targets. */ + name?: string; + /** Source and target viewport coordinates (`[sx, sy, tx, ty]`) for `html5_drag`. */ + coords?: [number, number, number, number]; } /** One check of the store probe. */ @@ -787,6 +795,8 @@ export interface FlowMcpRuntime { session: string, request: import("./character_bio").CharacterBioRequest, ) => Promise; + /** Saves and confirms character personality notes through the open character editor view. */ + characterBioEditorOp: (bio: string) => Promise; /** Lists available character voices and sets a voice on the character form. */ characterVoiceOp: (req: CharacterVoiceOpRequest) => Promise; /** Opens character uploads, attaches project references, and generates looks. */ From 04c523e83cba339c668c393992f456b63e597bb9 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:27:54 +0000 Subject: [PATCH 2/5] fix(flow): bound scene clip addition wait and confirm on timeout - Keep the verified build check before scene writes run - Stop before scene writes on unknown builds with unsupported_front_end - Limit the add_clips completion callback wait to 10 seconds - Read project tiles on callback timeout to confirm added scene clips - Report outcome_unknown when a read does not confirm the clip change --- src/scenes.rs | 45 ++++--- ts/project_store.ts | 13 ++ ts/scene_ops.ts | 306 ++++++++++++++++++++++++++++++++++++++++---- ts/types.ts | 2 + 4 files changed, 326 insertions(+), 40 deletions(-) diff --git a/src/scenes.rs b/src/scenes.rs index 4969fcc..6b7985b 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -15,7 +15,7 @@ use crate::assets::{ rename_assets, resolve_asset, trash_asset, }; use crate::db::FlowDb; -use crate::engine::ChromeEngine; +use crate::engine::{ChromeEngine, checked_runtime_result}; use crate::generation::{collect_created_assets, inspect_generation_network}; use crate::project::{ ensure_flow_store, ensure_project_workspace_root, project_id_from_url, project_workspace_url, @@ -170,6 +170,14 @@ pub(crate) struct VideoParams { pub(crate) scene_id: Option, } +/// Formats a failed browser `sceneOp` result while keeping structured diagnostic fields. +fn runtime_scene_error(res: Value) -> anyhow::Error { + match checked_runtime_result(res) { + Ok(_) => anyhow::anyhow!("unknown"), + Err(err) => err, + } +} + /// Dispatches `flow_scenes` actions (`list`, `create`, `add_clips`, `rename`, `trash`). pub(crate) async fn handle_scenes( engine: &ChromeEngine, @@ -198,13 +206,9 @@ pub(crate) async fn handle_scenes( "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) { - anyhow::bail!( - "Failed to create scene: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + if res.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(res); + anyhow::bail!("Failed to create scene: {err:#}"); } Ok(res) } @@ -214,21 +218,28 @@ pub(crate) async fn handle_scenes( .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 project_id = snap.get("projectId").and_then(Value::as_str); let payload = json!({ "action": "add_clips", "scene_id": scene_id, "asset_ids": asset_ids, "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) { - anyhow::bail!( - "Failed to add clips to scene: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + let res = match engine.call_flow_async("sceneOp", json!([payload])).await { + Ok(res) => res, + Err(error) => match project_id { + Some(pid) => anyhow::bail!( + "outcome_unknown (project {pid}, scene {scene_id} add_clips): {error:#}" + ), + None => { + anyhow::bail!("outcome_unknown (scene {scene_id} add_clips): {error:#}") + } + }, + }; + if res.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(res); + anyhow::bail!("Failed to add clips to scene: {err:#}"); } Ok(res) } diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..608fc3b 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -523,3 +523,16 @@ export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { + if (!isCurrent(store) || activeBoundStore() !== store) return null; + if (typeof projectQuery(store)?.fetch === "function") { + return await refreshAfterUnknown(store); + } + const tiles = readProjectStore(store); + if (tiles) projectsToRefresh.delete(store.projectId); + return tiles; +} diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index fc47fbb..ee7bcc9 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -4,16 +4,175 @@ // Create Google Flow scenes and append workflow clips via bound store state. import { createScene } from "./angular"; -import { delay } from "./dom"; -import { activeProjectStoreFormat } from "./frontend_builds"; +import { delay, isTrashedTile, legacyTile } from "./dom"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; +import { + clearProjectStore, + currentProjectStore, + projectMutationPending, + projectsToRefresh, + readConfirmedProjectStore, +} from "./project_store"; +import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { FlowTile, SceneOpRequest } from "./types"; +import type { FlowTile, SceneClipItem, SceneOpRequest } from "./types"; + +/** Maximum time in milliseconds to wait for a scene clip addition callback. */ +const SCENE_ADD_CLIPS_TIMEOUT_MS = 10_000; + +/** Store errors thrown before a mutation leaves the browser. */ +const PRE_SUBMIT_ERRORS = new Set([ + "unsupported_front_end", + "project_store_changed", + "store_mutate_missing", +]); + +/** Recorded identifiers of one clip in a scene. */ +interface ClipIdentity { + /** Workflow identifier on the clip. */ + workflowId: string | null; + /** Primary media identifier on the clip. */ + primaryMediaId: string | null; +} + +/** Expected identifiers of one clip requested in `add_clips`. */ +interface ExpectedClip { + /** Source asset ID passed by the caller. */ + assetId: string; + /** Resolved workflow ID sent to Flow. */ + workflowId: string; + /** Source primary media ID when known. */ + primaryMediaId: string | null; +} + +/** Outcome of waiting for a submitted `add_clips` mutation and its callback. */ +type AddClipsWaitOutcome = + | { kind: "settled" } + | { kind: "timeout" } + | { kind: "rejected"; error: string; preSubmit: boolean }; + +/** Extracts the workflow and primary media IDs from a scene clip item. */ +function readClipIdentity(clip: SceneClipItem | undefined): ClipIdentity { + const wf = clip?.workflowId; + const media = clip?.primaryMediaId; + return { + workflowId: wf == null || wf === "" ? null : String(wf), + primaryMediaId: media == null || media === "" ? null : String(media), + }; +} + +/** Reads the primary media ID of a source project tile when present. */ +function sourcePrimaryMediaId(rawTile: FlowTile | undefined): string | null { + const tile = legacyTile(rawTile); + const raw = + tile?.primaryMediaId ?? + tile?.Fb?.id ?? + tile?.Fb?.mediaId ?? + tile?.fb?.mediaId ?? + tile?.mediaId ?? + null; + return raw == null || raw === "" ? null : String(raw); +} + +/** Finds a live, non-trashed scene tile in `tiles` by ID. */ +function findLiveSceneTile( + tiles: Map | null | undefined, + sceneId: string, +): FlowTile | null { + if (!(tiles instanceof Map)) return null; + const candidate = tiles.get(sceneId); + if ( + candidate && + !isTrashedTile(candidate) && + !candidate.isPending && + String(candidate.type ?? "SCENE").toUpperCase() === "SCENE" + ) { + return candidate; + } + for (const [id, tile] of tiles.entries()) { + if ( + String(tile?.id ?? id) === sceneId && + !isTrashedTile(tile) && + !tile?.isPending && + String(tile?.type ?? "").toUpperCase() === "SCENE" + ) { + return tile; + } + } + return null; +} + +/** Returns true when `actual` matches a recorded pre-submission clip `prior`. */ +function clipMatchesPrior(actual: ClipIdentity, prior: ClipIdentity): boolean { + if (prior.workflowId !== null && actual.workflowId === prior.workflowId) { + return true; + } + return ( + prior.primaryMediaId !== null && + actual.primaryMediaId === prior.primaryMediaId + ); +} + +/** Returns true when `actual` matches a requested clip `expected`. */ +function clipMatchesExpected(actual: ClipIdentity, expected: ExpectedClip): boolean { + if ( + actual.workflowId !== null && + (actual.workflowId === expected.workflowId || + actual.workflowId === expected.assetId) + ) { + return true; + } + return ( + expected.primaryMediaId !== null && + actual.primaryMediaId === expected.primaryMediaId + ); +} + +/** Checks whether `afterScene` holds all `before` clips plus all `expected` clips. */ +function sceneClipsConfirmed( + before: ClipIdentity[], + afterScene: FlowTile, + expected: ExpectedClip[], + position: number | null | undefined, +): boolean { + const after = sceneContents(afterScene).clips.map(readClipIdentity); + if (after.length !== before.length + expected.length) return false; + + const insertAt = + typeof position === "number" && Number.isFinite(position) + ? Math.max(0, Math.min(Math.trunc(position), before.length)) + : before.length; + const matchesAtIndex = + before.slice(0, insertAt).every((b, i) => clipMatchesPrior(after[i], b)) && + expected.every((exp, i) => clipMatchesExpected(after[insertAt + i], exp)) && + before + .slice(insertAt) + .every((b, i) => clipMatchesPrior(after[insertAt + expected.length + i], b)); + if (matchesAtIndex) return true; + if (typeof position === "number" && Number.isFinite(position)) return false; + + const added: ClipIdentity[] = []; + let priorIndex = 0; + for (const item of after) { + if (priorIndex < before.length && clipMatchesPrior(item, before[priorIndex])) { + priorIndex += 1; + } else { + added.push(item); + } + } + return ( + priorIndex === before.length && + added.length === expected.length && + expected.every((exp, i) => clipMatchesExpected(added[i], exp)) + ); +} /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { + const build = readBuildLabel(); if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; } const helper = runtimeState.store; if (!helper || !helper.isCurrent()) { @@ -24,7 +183,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { return { ok: false, error: "store_loading" }; } const getMap = (): Map | null | undefined => helper.getTileMap(); - const tileMap = getMap(); + let tileMap = getMap(); if (!(tileMap instanceof Map) || !helper.mutate) { return { ok: false, error: "store_not_bound" }; } @@ -62,21 +221,69 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (action === "add_clips") { const sceneId = String(req?.scene_id || "").trim(); const assetIds = Array.isArray(req?.asset_ids) - ? req.asset_ids.map(String) + ? req.asset_ids.map((id) => String(id).trim()).filter(Boolean) : []; if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } - let callbackErr: unknown = null; + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + if (store && projectsToRefresh.has(store.projectId)) { + const refreshed = await readConfirmedProjectStore(store); + if (!refreshed) { + return { ok: false, error: "project_refresh_failed", project_id: store.projectId }; + } + tileMap = refreshed; + } + const existingTile = tileMap.get(sceneId); + if ( + existingTile && + (isTrashedTile(existingTile) || + existingTile.isPending === true || + (typeof existingTile.type === "string" && + existingTile.type.toUpperCase() !== "SCENE")) + ) { + return { ok: false, error: "scene_not_found", scene_id: sceneId }; + } + + const beforeScene = findLiveSceneTile(tileMap, sceneId); + const baseline = beforeScene + ? sceneContents(beforeScene).clips.map(readClipIdentity) + : null; + const expectedClips: ExpectedClip[] = assetIds.map((assetId) => { + const rawSource = tileMap?.get(assetId); + return { + assetId, + workflowId: String(rawSource?.workflowId || assetId), + primaryMediaId: sourcePrimaryMediaId(rawSource), + }; + }); + const workflowIds = expectedClips.map((clip) => clip.workflowId); + const timeoutMs = + typeof req?.timeout_ms === "number" && + Number.isFinite(req.timeout_ms) && + req.timeout_ms > 0 + ? Math.min(req.timeout_ms, SCENE_ADD_CLIPS_TIMEOUT_MS) + : SCENE_ADD_CLIPS_TIMEOUT_MS; + + let resolveCallback: () => void = () => {}; + let rejectCallback: (err: unknown) => void = () => {}; + const callbackPromise = new Promise((resolve, reject) => { + resolveCallback = resolve; + rejectCallback = reject; + }); + void callbackPromise.catch(() => undefined); const completion = { - resolve: () => {}, - reject: (err: unknown) => { - callbackErr ??= err; - }, + resolve: () => resolveCallback(), + reject: (err: unknown) => rejectCallback(err), }; - const workflowIds = resolveWfIds(assetIds); - try { - await helper.mutate({ + + if (store) projectsToRefresh.add(store.projectId); + const mutatePromise = Promise.resolve().then(() => + helper.mutate({ type: "add_workflows_to_scene", Lc: sceneId, Ic: sceneId, @@ -87,19 +294,72 @@ export async function sceneOp(req: SceneOpRequest): Promise { Eh: undefined, De: completion, ve: completion, - }); - } catch (err) { - return { - ok: false, - error: err instanceof Error ? err.message : String(err ?? "add_workflows_failed"), - }; + }), + ); + void mutatePromise.catch(() => undefined); + + let timer: ReturnType | undefined; + const outcome: AddClipsWaitOutcome = await Promise.race([ + Promise.all([mutatePromise, callbackPromise]).then( + (): AddClipsWaitOutcome => ({ kind: "settled" }), + (err: unknown): AddClipsWaitOutcome => { + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message === "mutation_timeout") { + return { kind: "timeout" }; + } + return { + kind: "rejected", + error: message, + preSubmit: PRE_SUBMIT_ERRORS.has(message), + }; + }, + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); + }), + ]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); + + if (outcome.kind === "rejected") { + if (outcome.preSubmit && store) { + projectsToRefresh.delete(store.projectId); + } + return { ok: false, error: outcome.error }; } - if (callbackErr) { + + if (outcome.kind === "timeout") { + const freshTiles = store + ? await readConfirmedProjectStore(store) + : helper.isCurrent() && helper.isReady() + ? helper.getTileMap() ?? null + : null; + const afterScene = findLiveSceneTile(freshTiles, sceneId); + if ( + baseline !== null && + afterScene !== null && + sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position) + ) { + if (store) projectsToRefresh.delete(store.projectId); + return { + ok: true, + scene_id: sceneId, + added: assetIds.length, + confirmed: true, + }; + } return { ok: false, - error: callbackErr instanceof Error ? callbackErr.message : String(callbackErr), + error: "outcome_unknown", + project_id: projectId, + stage: "add_clips", + scene_id: sceneId, + asset_ids: assetIds, }; } + + if (store) projectsToRefresh.delete(store.projectId); await delay(400); return { ok: true, scene_id: sceneId, added: assetIds.length }; } diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..c9fe7f6 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -653,6 +653,8 @@ export interface SceneOpRequest { scene_id?: string | null; /** Optional insertion position index. */ position?: number | null; + /** Optional callback wait limit in milliseconds for `add_clips`. */ + timeout_ms?: number | null; } /** Request payload for `videoOp`. */ From e20766ae51b18d06c69765ca56ac6fe95a9a4bfb Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:46:32 +0000 Subject: [PATCH 3/5] fix(flow): require server read on timeout and retain write guard - Require a fresh server fetch before confirming timed-out clip writes - Check exact clip order and count when confirming scene additions - Retain projectMutationPending until settlement or server confirmation --- ts/project_store.ts | 65 +++++++++++++++------- ts/scene_ops.ts | 129 +++++++++++++++++++++++++++++--------------- ts/types.ts | 2 - 3 files changed, 132 insertions(+), 64 deletions(-) diff --git a/ts/project_store.ts b/ts/project_store.ts index 608fc3b..17ba566 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -52,6 +52,8 @@ let boundStore: ProjectStore | null = null; let boundHandle: FlowStoreHandle | null = null; /** Promise chain that serializes general store mutations in this document. */ let mutationChain: Promise = Promise.resolve(); +/** Callback that unblocks `mutationChain` after server confirmation. */ +let releaseMutationChain: (() => void) | null = null; /** Returns the project ID in the current route. */ export function projectInRoute(): string | null { @@ -283,8 +285,23 @@ async function dispatchStoreMutation( /** Serializes general store mutations in the current page session. */ function mutateStore(store: ProjectStore, payload: Record): Promise { - const run = mutationChain.then(() => dispatchStoreMutation(store, payload)); - mutationChain = run.then(() => undefined, () => undefined); + let unblock: (() => void) | undefined; + const gate = new Promise((resolve) => { + unblock = resolve; + }); + const prev = mutationChain; + const run = prev.then(() => { + releaseMutationChain = unblock ?? null; + return dispatchStoreMutation(store, payload); + }); + mutationChain = Promise.race([ + run.then(() => undefined, () => undefined), + gate, + ]).finally(() => { + if (releaseMutationChain === unblock) { + releaseMutationChain = null; + } + }); return run; } @@ -459,18 +476,34 @@ export async function refreshProjectStore(store: ProjectStore): Promise(); +/** True until all active project submissions settle or are confirmed by the server. */ export let projectMutationPending = false; /** Projects that need a new query result after a mutation. */ export const projectsToRefresh = new Set(); +/** Marks one project submission as pending and returns an idempotent release function. */ +export function beginProjectMutation(): () => void { + const token = Symbol("project_mutation"); + activeProjectMutations.add(token); + projectMutationPending = true; + return () => { + if (!activeProjectMutations.delete(token)) return; + projectMutationPending = activeProjectMutations.size > 0; + if (!projectMutationPending) { + releaseMutationChain?.(); + } + }; +} + /** Sends one mutation and confirms it from a new server result. */ export async function mutateAndVerify( store: ProjectStore, payload: Record, verified: (tiles: Map) => boolean, ): Promise | null> { - projectMutationPending = true; + const finishMutation = beginProjectMutation(); projectsToRefresh.add(store.projectId); let timer: ReturnType | undefined; let timedOut = false; @@ -497,7 +530,7 @@ export async function mutateAndVerify( } catch { return null; } finally { - projectMutationPending = false; + finishMutation(); } })(); try { @@ -507,16 +540,16 @@ export async function mutateAndVerify( } } -/** Refreshes the project before the next operation after an unknown result. */ -export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { +/** Fetches a new tile result from the server within the mutation time limit. */ +export async function fetchProjectStore( + store: ProjectStore, +): Promise | null> { let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), MUTATION_TIMEOUT_MS); }); try { - const tiles = await Promise.race([refreshProjectStore(store), timeout]); - if (tiles) projectsToRefresh.delete(store.projectId); - return tiles; + return await Promise.race([refreshProjectStore(store), timeout]); } catch { return null; } finally { @@ -524,15 +557,9 @@ export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { - if (!isCurrent(store) || activeBoundStore() !== store) return null; - if (typeof projectQuery(store)?.fetch === "function") { - return await refreshAfterUnknown(store); - } - const tiles = readProjectStore(store); +/** Refreshes the project before the next operation after an unknown result. */ +export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { + const tiles = await fetchProjectStore(store); if (tiles) projectsToRefresh.delete(store.projectId); return tiles; } diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index ee7bcc9..ac0278b 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -7,11 +7,13 @@ import { createScene } from "./angular"; import { delay, isTrashedTile, legacyTile } from "./dom"; import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { + beginProjectMutation, clearProjectStore, currentProjectStore, + fetchProjectStore, projectMutationPending, projectsToRefresh, - readConfirmedProjectStore, + refreshAfterUnknown, } from "./project_store"; import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; @@ -104,6 +106,9 @@ function findLiveSceneTile( /** Returns true when `actual` matches a recorded pre-submission clip `prior`. */ function clipMatchesPrior(actual: ClipIdentity, prior: ClipIdentity): boolean { + if (prior.workflowId !== null && actual.workflowId !== null) { + return actual.workflowId === prior.workflowId; + } if (prior.workflowId !== null && actual.workflowId === prior.workflowId) { return true; } @@ -128,7 +133,7 @@ function clipMatchesExpected(actual: ClipIdentity, expected: ExpectedClip): bool ); } -/** Checks whether `afterScene` holds all `before` clips plus all `expected` clips. */ +/** Checks whether `afterScene` holds all `before` and `expected` clips in the intended order and count. */ function sceneClipsConfirmed( before: ClipIdentity[], afterScene: FlowTile, @@ -142,28 +147,12 @@ function sceneClipsConfirmed( typeof position === "number" && Number.isFinite(position) ? Math.max(0, Math.min(Math.trunc(position), before.length)) : before.length; - const matchesAtIndex = + return ( before.slice(0, insertAt).every((b, i) => clipMatchesPrior(after[i], b)) && expected.every((exp, i) => clipMatchesExpected(after[insertAt + i], exp)) && before .slice(insertAt) - .every((b, i) => clipMatchesPrior(after[insertAt + expected.length + i], b)); - if (matchesAtIndex) return true; - if (typeof position === "number" && Number.isFinite(position)) return false; - - const added: ClipIdentity[] = []; - let priorIndex = 0; - for (const item of after) { - if (priorIndex < before.length && clipMatchesPrior(item, before[priorIndex])) { - priorIndex += 1; - } else { - added.push(item); - } - } - return ( - priorIndex === before.length && - added.length === expected.length && - expected.every((exp, i) => clipMatchesExpected(added[i], exp)) + .every((b, i) => clipMatchesPrior(after[insertAt + expected.length + i], b)) ); } @@ -190,9 +179,21 @@ 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)); + ids.map((id) => String((tileMap ?? getMap())?.get(id)?.workflowId || id)); if (action === "create") { + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; + if (!refreshed) { + return { ok: false, error: "project_refresh_failed", project_id: projectId }; + } + tileMap = refreshed; + } const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map(String) : []; @@ -231,10 +232,12 @@ export async function sceneOp(req: SceneOpRequest): Promise { } const projectId = helper.projectId; const store = projectId ? currentProjectStore(projectId) : null; - if (store && projectsToRefresh.has(store.projectId)) { - const refreshed = await readConfirmedProjectStore(store); + const finishMutation = beginProjectMutation(); + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; if (!refreshed) { - return { ok: false, error: "project_refresh_failed", project_id: store.projectId }; + finishMutation(); + return { ok: false, error: "project_refresh_failed", project_id: projectId }; } tileMap = refreshed; } @@ -246,6 +249,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { (typeof existingTile.type === "string" && existingTile.type.toUpperCase() !== "SCENE")) ) { + finishMutation(); return { ok: false, error: "scene_not_found", scene_id: sceneId }; } @@ -262,12 +266,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { }; }); const workflowIds = expectedClips.map((clip) => clip.workflowId); - const timeoutMs = - typeof req?.timeout_ms === "number" && - Number.isFinite(req.timeout_ms) && - req.timeout_ms > 0 - ? Math.min(req.timeout_ms, SCENE_ADD_CLIPS_TIMEOUT_MS) - : SCENE_ADD_CLIPS_TIMEOUT_MS; let resolveCallback: () => void = () => {}; let rejectCallback: (err: unknown) => void = () => {}; @@ -275,13 +273,15 @@ export async function sceneOp(req: SceneOpRequest): Promise { resolveCallback = resolve; rejectCallback = reject; }); - void callbackPromise.catch(() => undefined); const completion = { resolve: () => resolveCallback(), reject: (err: unknown) => rejectCallback(err), }; - if (store) projectsToRefresh.add(store.projectId); + if (projectId) projectsToRefresh.add(projectId); + let timedOut = false; + let mutateSettled = false; + let lateError: string | null = null; const mutatePromise = Promise.resolve().then(() => helper.mutate({ type: "add_workflows_to_scene", @@ -296,7 +296,39 @@ export async function sceneOp(req: SceneOpRequest): Promise { ve: completion, }), ); - void mutatePromise.catch(() => undefined); + void callbackPromise.then( + () => { + void mutatePromise.then( + () => finishMutation(), + () => finishMutation(), + ); + }, + (err: unknown) => { + lateError ??= + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + void mutatePromise.then( + () => finishMutation(), + () => finishMutation(), + ); + }, + ); + void mutatePromise.then( + () => { + mutateSettled = true; + if (timedOut) { + finishMutation(); + } + }, + (err: unknown) => { + mutateSettled = true; + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message !== "mutation_timeout") { + lateError ??= message; + finishMutation(); + } + }, + ); let timer: ReturnType | undefined; const outcome: AddClipsWaitOutcome = await Promise.race([ @@ -306,6 +338,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { const message = err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); if (message === "mutation_timeout") { + timedOut = true; return { kind: "timeout" }; } return { @@ -316,32 +349,35 @@ export async function sceneOp(req: SceneOpRequest): Promise { }, ), new Promise((resolve) => { - timer = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs); + timer = setTimeout(() => { + timedOut = true; + resolve({ kind: "timeout" }); + }, SCENE_ADD_CLIPS_TIMEOUT_MS); }), ]).finally(() => { if (timer !== undefined) clearTimeout(timer); }); if (outcome.kind === "rejected") { - if (outcome.preSubmit && store) { - projectsToRefresh.delete(store.projectId); + if (mutateSettled) { + finishMutation(); + } + if (outcome.preSubmit && projectId) { + projectsToRefresh.delete(projectId); } return { ok: false, error: outcome.error }; } if (outcome.kind === "timeout") { - const freshTiles = store - ? await readConfirmedProjectStore(store) - : helper.isCurrent() && helper.isReady() - ? helper.getTileMap() ?? null - : null; + const freshTiles = store ? await fetchProjectStore(store) : null; const afterScene = findLiveSceneTile(freshTiles, sceneId); if ( baseline !== null && afterScene !== null && sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position) ) { - if (store) projectsToRefresh.delete(store.projectId); + finishMutation(); + if (projectId) projectsToRefresh.delete(projectId); return { ok: true, scene_id: sceneId, @@ -349,6 +385,12 @@ export async function sceneOp(req: SceneOpRequest): Promise { confirmed: true, }; } + if (lateError !== null) { + if (mutateSettled) { + finishMutation(); + } + return { ok: false, error: lateError }; + } return { ok: false, error: "outcome_unknown", @@ -359,7 +401,8 @@ export async function sceneOp(req: SceneOpRequest): Promise { }; } - if (store) projectsToRefresh.delete(store.projectId); + finishMutation(); + if (projectId) projectsToRefresh.delete(projectId); await delay(400); return { ok: true, scene_id: sceneId, added: assetIds.length }; } diff --git a/ts/types.ts b/ts/types.ts index c9fe7f6..2e1369d 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -653,8 +653,6 @@ export interface SceneOpRequest { scene_id?: string | null; /** Optional insertion position index. */ position?: number | null; - /** Optional callback wait limit in milliseconds for `add_clips`. */ - timeout_ms?: number | null; } /** Request payload for `videoOp`. */ From b26d8e5bf41e02818b4954b23c39c2b204f92bfd Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:07:23 +0000 Subject: [PATCH 4/5] fix(flow): settle clip additions on mutate and scope error prefixes - Resolve add_clips wait when mutate resolves without a callback. - Isolate mutationChain gates per payload with a WeakMap. - Run pre-write scene checks before submitting add_clips writes. - Prefix call_flow_async errors only when a write may have run. --- src/scenes.rs | 31 ++++- ts/project_store.ts | 61 ++++----- ts/scene_ops.ts | 299 ++++++++++++++++++++++++++++---------------- 3 files changed, 251 insertions(+), 140 deletions(-) diff --git a/src/scenes.rs b/src/scenes.rs index 6b7985b..a36d284 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -178,6 +178,23 @@ fn runtime_scene_error(res: Value) -> anyhow::Error { } } +/// Returns `true` when `call_flow_async` failed after the CDP evaluation request left for the page. +fn write_could_have_happened(error: &anyhow::Error) -> bool { + let message = error.to_string(); + if message.starts_with("Timed out waiting for CDP command Runtime.evaluate") + || message.starts_with("Chrome CDP closed during Runtime.evaluate") + || message == "Chrome CDP connection closed" + { + return true; + } + if let Some(cdp_err) = message.strip_prefix("Chrome CDP error:") { + let detail = cdp_err.trim(); + return !detail.starts_with("Cannot find default execution context") + && !detail.starts_with("Cannot find context with specified id"); + } + false +} + /// Dispatches `flow_scenes` actions (`list`, `create`, `add_clips`, `rename`, `trash`). pub(crate) async fn handle_scenes( engine: &ChromeEngine, @@ -220,6 +237,17 @@ pub(crate) async fn handle_scenes( .context("flow_scenes add_clips requires non-empty 'asset_ids'")?; let snap = read_snapshot(engine).await?; let project_id = snap.get("projectId").and_then(Value::as_str); + let prepare = json!({ + "action": "prepare_add_clips", + "scene_id": scene_id, + "asset_ids": asset_ids, + }); + let prepared = engine.call_flow_async("sceneOp", json!([prepare])).await?; + if prepared.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(prepared); + anyhow::bail!("Failed to add clips to scene: {err:#}"); + } + anyhow::ensure!(engine.has_page().await, "Chrome CDP connection closed"); let payload = json!({ "action": "add_clips", "scene_id": scene_id, @@ -228,7 +256,7 @@ pub(crate) async fn handle_scenes( }); let res = match engine.call_flow_async("sceneOp", json!([payload])).await { Ok(res) => res, - Err(error) => match project_id { + Err(error) if write_could_have_happened(&error) => match project_id { Some(pid) => anyhow::bail!( "outcome_unknown (project {pid}, scene {scene_id} add_clips): {error:#}" ), @@ -236,6 +264,7 @@ pub(crate) async fn handle_scenes( anyhow::bail!("outcome_unknown (scene {scene_id} add_clips): {error:#}") } }, + Err(error) => return Err(error), }; if res.get("ok").and_then(Value::as_bool) != Some(true) { let err = runtime_scene_error(res); diff --git a/ts/project_store.ts b/ts/project_store.ts index 17ba566..a0f1a4f 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -52,8 +52,8 @@ let boundStore: ProjectStore | null = null; let boundHandle: FlowStoreHandle | null = null; /** Promise chain that serializes general store mutations in this document. */ let mutationChain: Promise = Promise.resolve(); -/** Callback that unblocks `mutationChain` after server confirmation. */ -let releaseMutationChain: (() => void) | null = null; +/** Per-payload gates that unblock `mutationChain` when the server confirms a mutation early. */ +const mutationGates = new WeakMap, Promise>(); /** Returns the project ID in the current route. */ export function projectInRoute(): string | null { @@ -285,23 +285,12 @@ async function dispatchStoreMutation( /** Serializes general store mutations in the current page session. */ function mutateStore(store: ProjectStore, payload: Record): Promise { - let unblock: (() => void) | undefined; - const gate = new Promise((resolve) => { - unblock = resolve; - }); + const gate = mutationGates.get(payload); + mutationGates.delete(payload); const prev = mutationChain; - const run = prev.then(() => { - releaseMutationChain = unblock ?? null; - return dispatchStoreMutation(store, payload); - }); - mutationChain = Promise.race([ - run.then(() => undefined, () => undefined), - gate, - ]).finally(() => { - if (releaseMutationChain === unblock) { - releaseMutationChain = null; - } - }); + const run = prev.then(() => dispatchStoreMutation(store, payload)); + const settled = run.then(() => undefined, () => undefined); + mutationChain = gate ? prev.then(() => Promise.race([settled, gate])) : settled; return run; } @@ -483,17 +472,33 @@ export let projectMutationPending = false; /** Projects that need a new query result after a mutation. */ export const projectsToRefresh = new Set(); -/** Marks one project submission as pending and returns an idempotent release function. */ -export function beginProjectMutation(): () => void { +/** Guard for one active project submission and its optional `mutationChain` gate. */ +export interface ProjectMutationGuard { + /** Marks this submission settled or confirmed and releases its gate. */ + readonly finish: () => void; + /** Binds this submission's gate to a `mutateStore` payload. */ + readonly attach: >(payload: T) => T; +} + +/** Marks one project submission as pending and returns its idempotent guard. */ +export function beginProjectMutation(): ProjectMutationGuard { const token = Symbol("project_mutation"); activeProjectMutations.add(token); projectMutationPending = true; - return () => { - if (!activeProjectMutations.delete(token)) return; - projectMutationPending = activeProjectMutations.size > 0; - if (!projectMutationPending) { - releaseMutationChain?.(); - } + let releaseGate: (() => void) | undefined; + const gate = new Promise((resolve) => { + releaseGate = resolve; + }); + return { + finish: () => { + if (!activeProjectMutations.delete(token)) return; + projectMutationPending = activeProjectMutations.size > 0; + releaseGate?.(); + }, + attach: >(payload: T): T => { + mutationGates.set(payload, gate); + return payload; + }, }; } @@ -503,7 +508,7 @@ export async function mutateAndVerify( payload: Record, verified: (tiles: Map) => boolean, ): Promise | null> { - const finishMutation = beginProjectMutation(); + const mutation = beginProjectMutation(); projectsToRefresh.add(store.projectId); let timer: ReturnType | undefined; let timedOut = false; @@ -530,7 +535,7 @@ export async function mutateAndVerify( } catch { return null; } finally { - finishMutation(); + mutation.finish(); } })(); try { diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index ac0278b..f83113e 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -76,6 +76,16 @@ function sourcePrimaryMediaId(rawTile: FlowTile | undefined): string | null { return raw == null || raw === "" ? null : String(raw); } +/** Returns true when `tile` exists in the store and cannot act as a target scene. */ +function isInvalidSceneTile(tile: FlowTile | undefined): boolean { + return Boolean( + tile && + (isTrashedTile(tile) || + tile.isPending === true || + (typeof tile.type === "string" && tile.type.toUpperCase() !== "SCENE")), + ); +} + /** Finds a live, non-trashed scene tile in `tiles` by ID. */ function findLiveSceneTile( tiles: Map | null | undefined, @@ -219,7 +229,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { }; } - if (action === "add_clips") { + if (action === "prepare_add_clips") { const sceneId = String(req?.scene_id || "").trim(); const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map((id) => String(id).trim()).filter(Boolean) @@ -232,26 +242,53 @@ export async function sceneOp(req: SceneOpRequest): Promise { } const projectId = helper.projectId; const store = projectId ? currentProjectStore(projectId) : null; - const finishMutation = beginProjectMutation(); if (projectId && projectsToRefresh.has(projectId)) { const refreshed = store ? await refreshAfterUnknown(store) : null; if (!refreshed) { - finishMutation(); return { ok: false, error: "project_refresh_failed", project_id: projectId }; } tileMap = refreshed; } - const existingTile = tileMap.get(sceneId); - if ( - existingTile && - (isTrashedTile(existingTile) || - existingTile.isPending === true || - (typeof existingTile.type === "string" && - existingTile.type.toUpperCase() !== "SCENE")) - ) { - finishMutation(); + if (isInvalidSceneTile(tileMap.get(sceneId))) { return { ok: false, error: "scene_not_found", scene_id: sceneId }; } + return { ok: true, project_id: projectId }; + } + + if (action === "add_clips") { + const sceneId = String(req?.scene_id || "").trim(); + const assetIds = Array.isArray(req?.asset_ids) + ? req.asset_ids.map((id) => String(id).trim()).filter(Boolean) + : []; + if (!sceneId || !assetIds.length) { + return { ok: false, error: "scene_id_and_asset_ids_required" }; + } + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + const mutation = beginProjectMutation(); + try { + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; + if (!refreshed) { + mutation.finish(); + return { ok: false, error: "project_refresh_failed", project_id: projectId }; + } + tileMap = refreshed; + } + if (isInvalidSceneTile(tileMap.get(sceneId))) { + mutation.finish(); + return { ok: false, error: "scene_not_found", scene_id: sceneId }; + } + } catch (err) { + mutation.finish(); + return { + ok: false, + error: err instanceof Error ? err.message : String(err ?? "project_refresh_failed"), + }; + } const beforeScene = findLiveSceneTile(tileMap, sceneId); const baseline = beforeScene @@ -267,129 +304,174 @@ export async function sceneOp(req: SceneOpRequest): Promise { }); const workflowIds = expectedClips.map((clip) => clip.workflowId); - let resolveCallback: () => void = () => {}; - let rejectCallback: (err: unknown) => void = () => {}; - const callbackPromise = new Promise((resolve, reject) => { - resolveCallback = resolve; - rejectCallback = reject; + let callbackErr: unknown = null; + let resolveSettled: () => void = () => {}; + let rejectSettled: (err: unknown) => void = () => {}; + const settledPromise = new Promise((resolve, reject) => { + resolveSettled = resolve; + rejectSettled = reject; }); const completion = { - resolve: () => resolveCallback(), - reject: (err: unknown) => rejectCallback(err), + resolve: () => { + if (callbackErr === null) { + resolveSettled(); + } + }, + reject: (err: unknown) => { + callbackErr ??= err; + rejectSettled(callbackErr); + }, }; if (projectId) projectsToRefresh.add(projectId); - let timedOut = false; let mutateSettled = false; + let mutateSucceeded = false; + let releaseOnMutateSettle = false; let lateError: string | null = null; - const mutatePromise = Promise.resolve().then(() => - helper.mutate({ - type: "add_workflows_to_scene", - Lc: sceneId, - Ic: sceneId, - rg: workflowIds, - YWa: workflowIds, - position: typeof req.position === "number" ? req.position : undefined, - Mh: undefined, - Eh: undefined, - De: completion, - ve: completion, - }), - ); - void callbackPromise.then( - () => { - void mutatePromise.then( - () => finishMutation(), - () => finishMutation(), - ); - }, - (err: unknown) => { - lateError ??= - err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); - void mutatePromise.then( - () => finishMutation(), - () => finishMutation(), - ); - }, - ); + const payload = mutation.attach({ + type: "add_workflows_to_scene", + Lc: sceneId, + Ic: sceneId, + rg: workflowIds, + YWa: workflowIds, + position: typeof req.position === "number" ? req.position : undefined, + Mh: undefined, + Eh: undefined, + De: completion, + ve: completion, + }); + const mutatePromise = Promise.resolve().then(() => helper.mutate(payload)); void mutatePromise.then( () => { mutateSettled = true; - if (timedOut) { - finishMutation(); + if (callbackErr === null) { + mutateSucceeded = true; + } + completion.resolve(); + if (releaseOnMutateSettle) { + mutation.finish(); } }, (err: unknown) => { mutateSettled = true; + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message === "mutation_timeout") { + rejectSettled(new Error("mutation_timeout")); + } else { + lateError ??= message; + completion.reject(err); + } + if (releaseOnMutateSettle) { + mutation.finish(); + } + }, + ); + void settledPromise.then( + () => undefined, + (err: unknown) => { const message = err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); if (message !== "mutation_timeout") { lateError ??= message; - finishMutation(); } }, ); - let timer: ReturnType | undefined; - const outcome: AddClipsWaitOutcome = await Promise.race([ - Promise.all([mutatePromise, callbackPromise]).then( - (): AddClipsWaitOutcome => ({ kind: "settled" }), - (err: unknown): AddClipsWaitOutcome => { - const message = - err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); - if (message === "mutation_timeout") { - timedOut = true; - return { kind: "timeout" }; - } - return { - kind: "rejected", - error: message, - preSubmit: PRE_SUBMIT_ERRORS.has(message), - }; - }, - ), - new Promise((resolve) => { - timer = setTimeout(() => { - timedOut = true; - resolve({ kind: "timeout" }); - }, SCENE_ADD_CLIPS_TIMEOUT_MS); - }), - ]).finally(() => { - if (timer !== undefined) clearTimeout(timer); - }); + try { + let timer: ReturnType | undefined; + const outcome: AddClipsWaitOutcome = await Promise.race([ + settledPromise.then( + (): AddClipsWaitOutcome => ({ kind: "settled" }), + (err: unknown): AddClipsWaitOutcome => { + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message === "mutation_timeout") { + return { kind: "timeout" }; + } + return { + kind: "rejected", + error: message, + preSubmit: PRE_SUBMIT_ERRORS.has(message), + }; + }, + ), + new Promise((resolve) => { + timer = setTimeout(() => { + resolve({ kind: "timeout" }); + }, SCENE_ADD_CLIPS_TIMEOUT_MS); + }), + ]).finally(() => { + if (timer !== undefined) clearTimeout(timer); + }); - if (outcome.kind === "rejected") { - if (mutateSettled) { - finishMutation(); - } - if (outcome.preSubmit && projectId) { - projectsToRefresh.delete(projectId); + if (outcome.kind === "rejected") { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } + if (outcome.preSubmit && projectId) { + projectsToRefresh.delete(projectId); + } + return { ok: false, error: outcome.error }; } - return { ok: false, error: outcome.error }; - } - if (outcome.kind === "timeout") { - const freshTiles = store ? await fetchProjectStore(store) : null; - const afterScene = findLiveSceneTile(freshTiles, sceneId); - if ( - baseline !== null && - afterScene !== null && - sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position) - ) { - finishMutation(); - if (projectId) projectsToRefresh.delete(projectId); + if (outcome.kind === "timeout") { + const freshTiles = store ? await fetchProjectStore(store) : null; + const afterScene = findLiveSceneTile(freshTiles, sceneId); + if ( + baseline !== null && + afterScene !== null && + sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position) + ) { + mutation.finish(); + if (projectId) projectsToRefresh.delete(projectId); + return { + ok: true, + scene_id: sceneId, + added: assetIds.length, + confirmed: true, + }; + } + if (lateError !== null) { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } + return { ok: false, error: lateError }; + } + if (mutateSucceeded) { + mutation.finish(); + if (projectId) projectsToRefresh.delete(projectId); + await delay(400); + return { ok: true, scene_id: sceneId, added: assetIds.length }; + } + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } return { - ok: true, + ok: false, + error: "outcome_unknown", + project_id: projectId, + stage: "add_clips", scene_id: sceneId, - added: assetIds.length, - confirmed: true, + asset_ids: assetIds, }; } - if (lateError !== null) { - if (mutateSettled) { - finishMutation(); - } - return { ok: false, error: lateError }; + + mutation.finish(); + if (projectId) projectsToRefresh.delete(projectId); + await delay(400); + return { ok: true, scene_id: sceneId, added: assetIds.length }; + } catch { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; } return { ok: false, @@ -400,11 +482,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { asset_ids: assetIds, }; } - - finishMutation(); - if (projectId) projectsToRefresh.delete(projectId); - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; } return { ok: false, error: `unknown_scene_action:${action}` }; From 581721cf56ae79b35cbd67696304f36e8015dcee Mon Sep 17 00:00:00 2001 From: ByteLandTechnology Date: Tue, 1 Dec 2026 12:43:42 +0800 Subject: [PATCH 5/5] fix(flow): confirm scene clip additions after a timeout - Release the project write guard when the baseline read fails - Read the source media ID through the build media container - Poll the store for up to eight reads before an unknown outcome - Remove the unreachable success branch and report the error detail - Treat JavaScript errors as possible writes in the scene tool --- src/scenes.rs | 3 +- ts/scene_ops.ts | 73 +++++++++++++++++++++++-------------------------- 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/src/scenes.rs b/src/scenes.rs index a36d284..e5f512d 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -181,7 +181,8 @@ fn runtime_scene_error(res: Value) -> anyhow::Error { /// Returns `true` when `call_flow_async` failed after the CDP evaluation request left for the page. fn write_could_have_happened(error: &anyhow::Error) -> bool { let message = error.to_string(); - if message.starts_with("Timed out waiting for CDP command Runtime.evaluate") + if message.starts_with("JavaScript error") + || message.starts_with("Timed out waiting for CDP command Runtime.evaluate") || message.starts_with("Chrome CDP closed during Runtime.evaluate") || message == "Chrome CDP connection closed" { diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index f83113e..58c1cb7 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -4,7 +4,7 @@ // Create Google Flow scenes and append workflow clips via bound store state. import { createScene } from "./angular"; -import { delay, isTrashedTile, legacyTile } from "./dom"; +import { delay, findMediaContainer, isTrashedTile, legacyTile } from "./dom"; import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { beginProjectMutation, @@ -19,6 +19,10 @@ import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, SceneClipItem, SceneOpRequest } from "./types"; +/** Number of reads that confirm a scene change after the callback times out. */ +const SCENE_CONFIRM_ATTEMPTS = 8; +/** Time between two confirmation reads. */ +const SCENE_CONFIRM_INTERVAL_MS = 1_000; /** Maximum time in milliseconds to wait for a scene clip addition callback. */ const SCENE_ADD_CLIPS_TIMEOUT_MS = 10_000; @@ -66,13 +70,7 @@ function readClipIdentity(clip: SceneClipItem | undefined): ClipIdentity { /** Reads the primary media ID of a source project tile when present. */ function sourcePrimaryMediaId(rawTile: FlowTile | undefined): string | null { const tile = legacyTile(rawTile); - const raw = - tile?.primaryMediaId ?? - tile?.Fb?.id ?? - tile?.Fb?.mediaId ?? - tile?.fb?.mediaId ?? - tile?.mediaId ?? - null; + const raw = tile?.primaryMediaId ?? (rawTile ? findMediaContainer(rawTile)?.[1].id : undefined) ?? null; return raw == null || raw === "" ? null : String(raw); } @@ -269,6 +267,8 @@ export async function sceneOp(req: SceneOpRequest): Promise { const projectId = helper.projectId; const store = projectId ? currentProjectStore(projectId) : null; const mutation = beginProjectMutation(); + let baseline: ReturnType[] | null; + let expectedClips: ExpectedClip[]; try { if (projectId && projectsToRefresh.has(projectId)) { const refreshed = store ? await refreshAfterUnknown(store) : null; @@ -282,6 +282,18 @@ export async function sceneOp(req: SceneOpRequest): Promise { mutation.finish(); return { ok: false, error: "scene_not_found", scene_id: sceneId }; } + const beforeScene = findLiveSceneTile(tileMap, sceneId); + baseline = beforeScene + ? sceneContents(beforeScene).clips.map(readClipIdentity) + : null; + expectedClips = assetIds.map((assetId) => { + const rawSource = tileMap?.get(assetId); + return { + assetId, + workflowId: String(rawSource?.workflowId || assetId), + primaryMediaId: sourcePrimaryMediaId(rawSource), + }; + }); } catch (err) { mutation.finish(); return { @@ -289,19 +301,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { error: err instanceof Error ? err.message : String(err ?? "project_refresh_failed"), }; } - - const beforeScene = findLiveSceneTile(tileMap, sceneId); - const baseline = beforeScene - ? sceneContents(beforeScene).clips.map(readClipIdentity) - : null; - const expectedClips: ExpectedClip[] = assetIds.map((assetId) => { - const rawSource = tileMap?.get(assetId); - return { - assetId, - workflowId: String(rawSource?.workflowId || assetId), - primaryMediaId: sourcePrimaryMediaId(rawSource), - }; - }); const workflowIds = expectedClips.map((clip) => clip.workflowId); let callbackErr: unknown = null; @@ -325,7 +324,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (projectId) projectsToRefresh.add(projectId); let mutateSettled = false; - let mutateSucceeded = false; let releaseOnMutateSettle = false; let lateError: string | null = null; const payload = mutation.attach({ @@ -344,9 +342,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { void mutatePromise.then( () => { mutateSettled = true; - if (callbackErr === null) { - mutateSucceeded = true; - } completion.resolve(); if (releaseOnMutateSettle) { mutation.finish(); @@ -418,13 +413,18 @@ export async function sceneOp(req: SceneOpRequest): Promise { } if (outcome.kind === "timeout") { - const freshTiles = store ? await fetchProjectStore(store) : null; - const afterScene = findLiveSceneTile(freshTiles, sceneId); - if ( - baseline !== null && - afterScene !== null && - sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position) - ) { + let confirmed = false; + for (let attempt = 0; attempt < SCENE_CONFIRM_ATTEMPTS && !confirmed; attempt += 1) { + if (attempt > 0) await delay(SCENE_CONFIRM_INTERVAL_MS); + const freshTiles = store ? await fetchProjectStore(store) : null; + const afterScene = findLiveSceneTile(freshTiles, sceneId); + confirmed = + baseline !== null && + afterScene !== null && + sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position); + if (lateError !== null) break; + } + if (confirmed) { mutation.finish(); if (projectId) projectsToRefresh.delete(projectId); return { @@ -442,12 +442,6 @@ export async function sceneOp(req: SceneOpRequest): Promise { } return { ok: false, error: lateError }; } - if (mutateSucceeded) { - mutation.finish(); - if (projectId) projectsToRefresh.delete(projectId); - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; - } if (mutateSettled) { mutation.finish(); } else { @@ -467,7 +461,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (projectId) projectsToRefresh.delete(projectId); await delay(400); return { ok: true, scene_id: sceneId, added: assetIds.length }; - } catch { + } catch (err) { if (mutateSettled) { mutation.finish(); } else { @@ -476,6 +470,7 @@ export async function sceneOp(req: SceneOpRequest): Promise { return { ok: false, error: "outcome_unknown", + detail: err instanceof Error ? err.message : String(err), project_id: projectId, stage: "add_clips", scene_id: sceneId,