From b071df9533999f631b8992d9aec4e46b647af56a 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:51:31 +0000 Subject: [PATCH 1/2] fix(flow): cascade read-only stores and add UI fallbacks - Cascade verified store layouts from newest to oldest on reads - Use 20261120.00_p0 fallbacks for LViews, titles, clips, and voices - Match tile IDs in Angular LView slots before media ID selectors - Fall back to UI menus and character forms when store writes reject - Reject unverified store and Agent writes with active build labels --- src/assets.rs | 87 +++++++------- src/character_bio.rs | 187 ++++++++++++++++++++++++++++--- src/characters.rs | 84 ++++---------- src/collections.rs | 18 +-- src/project.rs | 78 ++++++------- src/tile_menu.rs | 13 ++- src/upload.rs | 114 ++++++++++++++++--- ts/angular.ts | 15 ++- ts/asset_ops.ts | 5 +- ts/character_extra.ts | 12 +- ts/character_media.ts | 226 +++---------------------------------- ts/character_ops.ts | 44 ++++++-- ts/character_preview.ts | 230 ++++++++++++++++++++++++++++++++++++++ ts/character_voices.ts | 7 +- ts/discover_store.ts | 7 +- ts/frontend_builds.ts | 104 +++++++++++++---- ts/open_edit_asset.ts | 4 +- ts/project_store.ts | 82 ++++++++------ ts/projects_ops.ts | 31 ++++- ts/read_store_snapshot.ts | 6 +- ts/scene_ops.ts | 5 +- ts/scene_tiles.ts | 8 +- ts/tile_dom.ts | 178 +++++++++++++++++++++++++++-- ts/types.ts | 4 +- ts/video_ops.ts | 32 +++--- 25 files changed, 1052 insertions(+), 529 deletions(-) create mode 100644 ts/character_preview.ts diff --git a/src/assets.rs b/src/assets.rs index c3c8975..0d93ed2 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -10,7 +10,7 @@ use futures_util::{StreamExt, stream}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use tokio::time::{Duration, Instant}; use crate::collections::{FlowCollection, find_collection}; @@ -431,35 +431,21 @@ async fn confirm_renamed_asset(engine: &ChromeEngine, id: &str, name: &str) -> b false } -/// Renames collections through the collection store and other tiles through the page or store. +/// Renames collections through the menu or collection store and other tiles through the page or store. pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec) -> Result { - let collections = ProjectStoreSession::open(engine).await?; + ensure_flow_store(engine).await?; + let mut snap = read_snapshot(engine).await?; + let collection_list: Vec = serde_json::from_value( + snap.get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?; + let collection_ids: HashSet = collection_list.into_iter().map(|c| c.id).collect(); 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)), - } - 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() && matches!( @@ -473,6 +459,22 @@ pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec } continue 'items; } + if collection_ids.contains(&entry.id) { + match ProjectStoreSession::open(engine).await { + Ok(collections) => 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)), + }, + Err(err) => failed.push(rename_error(&entry, &err)), + } + if idx + 1 < total { + tokio::time::sleep(Duration::from_millis(250)).await; + } + continue 'items; + } + ensure_flow_store(engine).await?; let mut ok = false; for attempt in 0..2 { let res = engine @@ -521,12 +523,8 @@ 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. -async fn invoke_trash_tile( - engine: &ChromeEngine, - session: &ProjectStoreSession<'_>, - id: &str, -) -> Result { +/// Moves an asset to trash through the tile menu first, or through the pinned project store. +async fn invoke_trash_tile(engine: &ChromeEngine, id: &str) -> Result { let menu_error = if ensure_flow_store(engine).await.is_ok() && tile_state(engine, id).await.is_present() { match trash_through_menu(engine, id).await { @@ -541,6 +539,7 @@ async fn invoke_trash_tile( } else { None }; + let session = ProjectStoreSession::open(engine).await?; let mut result = session .call("trashAssetOp", json!(id), Some("trash asset")) .await?; @@ -552,32 +551,40 @@ 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 through the menu or store. pub(crate) async fn trash_asset( engine: &ChromeEngine, db: &FlowDb, match_str: &str, ) -> Result { - let collections = ProjectStoreSession::open(engine).await?; let query = match_str.trim(); - if collections.is_collection(query).await? { + ensure_flow_store(engine).await?; + let mut snap = read_snapshot(engine).await?; + let summaries: Vec = serde_json::from_value( + snap.get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?; + if summaries.iter().any(|c| c.id == query) { + let collections = ProjectStoreSession::open(engine).await?; return collections.delete(query).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 raw_assets: Vec = serde_json::from_value( + snap.get_mut("assets") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?; + let Some(asset) = match_asset(&raw_assets, query, true).cloned() else { let collection = find_collection(&summaries, query, true)? .with_context(|| format!("No asset or collection matches '{query}' for flow_trash"))?; + let collections = ProjectStoreSession::open(engine).await?; return collections.delete(&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, 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..8b0f9ad 100644 --- a/src/character_bio.rs +++ b/src/character_bio.rs @@ -1,16 +1,54 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Direct project store operations for character personality notes. +//! Direct project store and character form fallback operations for character personality notes. + +use std::time::Duration; use anyhow::{Context, Result}; -use serde_json::json; +use serde_json::{Value, 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::project::{ensure_flow_store, ensure_project_workspace_root, project_id_from_url}; +use crate::project_route::character_id_from_url; use crate::project_store::ProjectStoreSession; +/// Returns true when `err` indicates that direct character bio store mutations are unverified. +fn is_unsupported_bio_store(err: &anyhow::Error) -> bool { + let msg = format!("{err:#}"); + !msg.contains("outcome_unknown") + && (msg.contains("unsupported_front_end") + || msg.contains("collection_store_not_bound") + || msg.contains("ambiguous_collection_store")) +} + +/// Opens a verified project store session for character bio writes, or returns `Ok(None)` on unverified builds. +pub(crate) async fn open_verified_bio_store<'a>( + engine: &'a ChromeEngine, + expected_project_id: Option<&str>, +) -> Result>> { + let store = match ProjectStoreSession::open(engine).await { + Ok(store) => store, + Err(err) if is_unsupported_bio_store(&err) => return Ok(None), + Err(err) => return Err(err), + }; + anyhow::ensure!( + expected_project_id == Some(store.project_id()), + "The active project changed before the character update" + ); + match store + .call("characterBioOp", json!({ "action": "check" }), None) + .await + { + Ok(_) => Ok(Some(store)), + Err(err) if is_unsupported_bio_store(&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 +65,150 @@ 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( +/// Opens `/character/` if needed and applies character name and personality form edits. +pub(crate) async fn update_character_form_fields( + engine: &ChromeEngine, + project_id: Option<&str>, + character_id: &str, + new_name: Option<&str>, + bio: Option<&str>, +) -> Result<()> { + let payload = json!({ + "action": "update", + "character_id": character_id, + "name": new_name, + "bio": bio, + }); + let mut res = engine + .call_flow_async("characterOp", json!([payload.clone()])) + .await?; + if let Some(nav_url) = res.get("need_navigate").and_then(Value::as_str) { + if let (Some(pid), Some(cid)) = + (project_id_from_url(nav_url), character_id_from_url(nav_url)) + { + open_character_editor(engine, nav_url, &pid, &cid).await?; + } else { + engine.navigate(nav_url).await?; + tokio::time::sleep(Duration::from_millis(1800)).await; + let _ = ensure_flow_store(engine).await; + } + res = engine + .call_flow_async("characterOp", json!([payload.clone()])) + .await?; + } + for _ in 0..25 { + if res.get("error").and_then(Value::as_str) != Some("store_loading") { + break; + } + tokio::time::sleep(Duration::from_millis(200)).await; + let _ = ensure_flow_store(engine).await; + res = engine + .call_flow_async("characterOp", json!([payload.clone()])) + .await?; + } + if res.get("ok").and_then(Value::as_bool) != Some(true) { + if engine + .current_url() + .await + .unwrap_or_default() + .contains("/character/") + { + exit_character_editor(engine, project_id).await; + } + anyhow::bail!( + "Failed to edit character '{}': {}", + character_id, + res.get("error") + .and_then(Value::as_str) + .unwrap_or("unknown") + ); + } + Ok(()) +} + +/// Edits character personality notes through `flow-character-form` when direct store updates are unavailable. +async fn edit_character_bio_in_form( 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) + ensure_project_workspace_root(engine).await?; + ensure_flow_store(engine).await?; + let snap = list_assets_with_project(engine).await?; + let char_assets: Vec = snap + .assets + .into_iter() + .filter(|a| a.kind == "character") + .collect(); + let target = match_asset(&char_assets, 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 pid = snap + .project_id + .clone() + .or_else(|| project_id_from_url(&cur_url)) + .context("Missing project ID for character route")?; + open_character_editor(engine, &cur_url, &pid, &target.id).await?; + let update_res = + update_character_form_fields(engine, Some(&pid), &target.id, None, Some(bio)).await; + exit_character_editor(engine, Some(&pid)).await; + update_res?; db.upsert_character( target.id.clone(), - Some(store.project_id().to_owned()), + Some(pid), target.name.clone(), 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 verified store or `flow-character-form`. +pub(crate) async fn edit_character_bio( + engine: &ChromeEngine, + db: &FlowDb, + selector: &str, + bio: &str, +) -> Result { + let direct_target = match ProjectStoreSession::open(engine).await { + Ok(store) => { + match store + .call("characterBioOp", json!({ "action": "list" }), None) + .await + { + Ok(mut result) => { + 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?; + Some((target, store.project_id().to_owned())) + } + Err(err) if is_unsupported_bio_store(&err) => None, + Err(err) => return Err(err), + } + } + Err(err) if is_unsupported_bio_store(&err) => None, + Err(err) => return Err(err), + }; + if let Some((target, project_id)) = direct_target { + db.upsert_character( + target.id.clone(), + Some(project_id), + target.name.clone(), + Some(bio.to_owned()), + None, + None, + ) + .await?; + return Ok(target.id); + } + edit_character_bio_in_form(engine, db, selector, bio).await } diff --git a/src/characters.rs b/src/characters.rs index 12c6de2..95fd45f 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, open_verified_bio_store, set_character_bio, update_character_form_fields, +}; use crate::db::FlowDb; use crate::download::download_resolved_asset; use crate::engine::{ChromeEngine, checked_runtime_result, validate_local_files}; @@ -20,8 +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_route::character_id_from_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, @@ -422,15 +422,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) + open_verified_bio_store(engine, project_id.as_deref()).await? } else { None }; @@ -542,60 +534,22 @@ 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?; - } - editor_opened = true; - - let payload = json!({ - "action": "update", - "character_id": target.id, - "name": scene.new_name, - }); - let mut res = engine - .call_flow_async("characterOp", json!([payload.clone()])) - .await?; - if let Some(nav_url) = res.get("need_navigate").and_then(|v| v.as_str()) { - if let (Some(pid), Some(cid)) = - (project_id_from_url(nav_url), character_id_from_url(nav_url)) - { - open_character_editor(engine, nav_url, &pid, &cid).await?; + let form_bio = + if let (Some(store), Some(bio)) = (bio_store.take(), effective_bio.as_deref()) { + set_character_bio(&store, &target.id, bio).await?; + None } else { - engine.navigate(nav_url).await?; - tokio::time::sleep(Duration::from_millis(1800)).await; - let _ = ensure_flow_store(engine).await; - } - res = engine - .call_flow_async("characterOp", json!([payload.clone()])) - .await?; - } - for _ in 0..25 { - if res.get("error").and_then(Value::as_str) != Some("store_loading") { - break; - } - tokio::time::sleep(Duration::from_millis(200)).await; - let _ = ensure_flow_store(engine).await; - res = engine - .call_flow_async("characterOp", json!([payload.clone()])) - .await?; - } - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - if engine - .current_url() - .await - .unwrap_or_default() - .contains("/character/") - { - exit_character_editor(engine, project_id.as_deref()).await; - } - anyhow::bail!( - "Failed to edit character '{}': {}", - target.id, - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } + effective_bio.as_deref() + }; + editor_opened = true; + update_character_form_fields( + engine, + project_id.as_deref(), + &target.id, + scene.new_name.as_deref(), + form_bio, + ) + .await?; let default_voice_name = scene .new_name .clone() diff --git a/src/collections.rs b/src/collections.rs index a2a2f16..8d98866 100644 --- a/src/collections.rs +++ b/src/collections.rs @@ -57,14 +57,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 })) @@ -189,9 +181,17 @@ pub(crate) async fn handle_collections( engine: &ChromeEngine, req: CollectionsParams, ) -> Result { + if req.action == "list" { + let mut snap = crate::project::read_snapshot(engine).await?; + let collections: Vec = serde_json::from_value( + snap.get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?; + return Ok(json!({ "collections": collections })); + } let session = ProjectStoreSession::open(engine).await?; match req.action.as_str() { - "list" => Ok(json!({ "collections": session.list().await? })), "create" => { let name = req .name diff --git a/src/project.rs b/src/project.rs index e11643e..04e8908 100644 --- a/src/project.rs +++ b/src/project.rs @@ -377,12 +377,6 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { ); let status = store_loading_result(bind_current_store(engine, &project_id).await)?; let status_err = status.get("error").and_then(Value::as_str); - if status_err == Some("unsupported_front_end") { - anyhow::bail!( - "Google Flow front end build is not supported (unsupported_front_end).{}", - build_suffix(engine).await - ); - } if status["ok"].as_bool() == Some(true) { return Ok(()); } @@ -395,12 +389,6 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { let discovery = store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?; let discovery_err = discovery.get("error").and_then(Value::as_str); - if discovery_err == Some("unsupported_front_end") { - anyhow::bail!( - "Google Flow front end build is not supported (unsupported_front_end).{}", - build_suffix(engine).await - ); - } input_pending |= discovery_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); if discovery["bound"].as_bool() == Some(true) { tokio::time::sleep(Duration::from_millis(250)).await; @@ -462,16 +450,9 @@ async fn build_suffix(engine: &ChromeEngine) -> String { pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { if engine.has_page().await && let Ok(snap) = engine.call_flow_js("readStoreSnapshot", json!([])).await + && snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { - if snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { - return Ok(snap); - } - if snap.get("error").and_then(Value::as_str) == Some("unsupported_front_end") { - anyhow::bail!( - "Google Flow front end build is not supported (unsupported_front_end).{}", - build_suffix(engine).await - ); - } + return Ok(snap); } let mut last_err = "store_not_bound".to_string(); for _ in 0..25 { @@ -485,12 +466,6 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { .and_then(|v| v.as_str()) .unwrap_or("unknown") .to_string(); - if last_err == "unsupported_front_end" { - anyhow::bail!( - "Google Flow front end build is not supported (unsupported_front_end).{}", - build_suffix(engine).await - ); - } let delay_ms = if matches!( last_err.as_str(), "store_loading" | ANGULAR_REQUIRED_INPUT_ERROR @@ -682,28 +657,48 @@ async fn open_project( })) } -/// Polls project snapshots until `projectTitle` holds `desired` after a short settle delay. +/// Returns true when the header editable title control holds `desired` outside editing mode. +async fn dom_project_title_matches(engine: &ChromeEngine, desired: &str) -> bool { + let Ok(res) = run_projects_op(engine, json!({ "action": "get_title" })).await else { + return false; + }; + res.get("ok").and_then(Value::as_bool) == Some(true) + && res.get("editing").and_then(Value::as_bool) == Some(false) + && res.get("title").and_then(Value::as_str).map(str::trim) == Some(desired) +} + +/// Polls project snapshots or the settled header title input until the title holds `desired`. async fn confirm_project_title(engine: &ChromeEngine, desired: &str) -> Result { let deadline = Instant::now() + Duration::from_secs(6); tokio::time::sleep(Duration::from_millis(250)).await; while Instant::now() < deadline { - if let Ok(snap) = read_snapshot(engine).await - && snap - .get("projectTitle") - .and_then(Value::as_str) - .map(str::trim) - == Some(desired) - { - tokio::time::sleep(Duration::from_millis(200)).await; - if let Ok(settled) = read_snapshot(engine).await - && settled + match read_snapshot(engine).await { + Ok(snap) => { + if snap .get("projectTitle") .and_then(Value::as_str) .map(str::trim) == Some(desired) - { - return Ok(desired.to_string()); + { + tokio::time::sleep(Duration::from_millis(200)).await; + if let Ok(settled) = read_snapshot(engine).await + && settled + .get("projectTitle") + .and_then(Value::as_str) + .map(str::trim) + == Some(desired) + { + return Ok(desired.to_string()); + } + } + } + Err(_) if dom_project_title_matches(engine, desired).await => { + tokio::time::sleep(Duration::from_millis(200)).await; + if dom_project_title_matches(engine, desired).await { + return Ok(desired.to_string()); + } } + Err(_) => {} } tokio::time::sleep(Duration::from_millis(250)).await; } @@ -783,7 +778,8 @@ async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> let _ = open_project(engine, Some(pid), None).await?; } } else { - ensure_flow_store(engine).await?; + ensure_project_workspace_root(engine).await?; + let _ = ensure_flow_store(engine).await; } let res = run_projects_op(engine, json!({ "action": "set_title", "title": trimmed })).await?; if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { diff --git a/src/tile_menu.rs b/src/tile_menu.rs index 3791a9a..8cc64d7 100644 --- a/src/tile_menu.rs +++ b/src/tile_menu.rs @@ -211,7 +211,18 @@ async fn trash_in_view(engine: &ChromeEngine, id: &str) -> Result { if !click_tile_menu_item(engine, id, TRASH_MENU_ITEM).await? { return Ok(false); } - if wait_trashed(engine, id, 40).await { + if wait_trashed(engine, id, 6).await { + return Ok(true); + } + let confirm = page_op(engine, json!({ "action": "confirm_dialog" })).await?; + if is_ok(&confirm) + && let Some(point) = confirm.get("point") + && engine.click_point(point).await? + && wait_trashed(engine, id, 36).await + { + return Ok(true); + } + if wait_trashed(engine, id, 34).await { return Ok(true); } // The page can show a dialog after the click. Close it before the caller sends the store mutation. diff --git a/src/upload.rs b/src/upload.rs index 896bde0..5548320 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -44,29 +44,54 @@ 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. -pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { - crate::project::ensure_project_workspace_root(engine).await?; - let project = ProjectStoreSession::open(engine).await?; - let has_video = files.iter().any(|file| { +/// Returns true when `files` contains at least one video path. +fn has_video_file(files: &[String]) -> bool { + files.iter().any(|file| { mime_guess::from_path(file) .first() .is_some_and(|mime| mime.type_() == mime_guess::mime::VIDEO) - }); - if has_video && eval_value(engine, "document.hidden").await? == Value::Bool(true) { + }) +} + +/// Returns true when a direct upload error occurred before any upload RPC was sent. +fn should_fallback_to_menu_upload(err: &anyhow::Error) -> bool { + let msg = format!("{err:#}"); + !msg.contains("outcome_unknown") + && (msg.contains("unsupported_front_end") + || msg.contains("collection_store_not_bound") + || msg.contains("ambiguous_collection_store") + || msg.contains("project_upload_page_not_ready")) +} + +/// Uploads files to the pinned project and falls back to the workspace upload menu on unverified builds. +pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { + crate::project::ensure_project_workspace_root(engine).await?; + if has_video_file(files) && eval_value(engine, "document.hidden").await? == Value::Bool(true) { // 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 + match ProjectStoreSession::open(engine).await { + Ok(project) => { + engine + .upload_files_to("window.__flowMcp.stageMediaFiles()", files) + .await?; + match project + .call( + "projectUpload", + json!(files.len()), + Some("upload local media"), + ) + .await + { + Ok(res) => return Ok(res), + Err(err) if !should_fallback_to_menu_upload(&err) => return Err(err), + Err(_) => {} + } + } + Err(err) if !should_fallback_to_menu_upload(&err) => return Err(err), + Err(_) => {} + } + upload_project_files_through_menu(engine, files).await } /// Script that keeps the next file input that the page clicks in `window.__fmUploadInput`. @@ -273,6 +298,61 @@ async fn project_tile_ids(engine: &ChromeEngine) -> Result> { Ok(snap.assets.into_iter().map(|a| a.id).collect()) } +/// Uploads `files` (images and videos) through the workspace library menu and returns the new assets. +async fn upload_project_files_through_menu( + engine: &ChromeEngine, + files: &[String], +) -> Result { + let initial = crate::assets::list_assets_with_project(engine).await?; + let initial_project_id = initial.project_id; + let before: HashSet = initial.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 _ in 0..90 { + tokio::time::sleep(Duration::from_millis(1000)).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 let Some(detail) = asset.media_error.as_deref() { + anyhow::bail!("Flow rejected uploaded media '{}': {detail}", asset.name); + } + if matches!( + asset.media_status.as_deref(), + Some("failed" | "canceled" | "UPLOAD_FAILED") + ) { + anyhow::bail!("Flow failed to process uploaded media '{}'", asset.name); + } + if asset.url.is_some() { + ready.push(json!({ + "id": asset.id, + "primary_media_id": asset.primary_media_id, + "name": asset.name, + "kind": asset.kind, + })); + } + } + ready_count = ready.len(); + if ready_count >= files.len() { + return Ok(json!({ + "project_id": snap.project_id.or(initial_project_id), + "count": ready.len(), + "assets": ready, + })); + } + } + anyhow::bail!( + "Uploaded {} of {} files into the Flow library within 90 seconds", + ready_count, + files.len() + ) +} + /// Uploads `files` into the project library, accepts the upload consent dialog, and returns the new image asset IDs. pub(crate) async fn upload_to_library( engine: &ChromeEngine, diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..6ce0ad7 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -11,7 +11,7 @@ import { normalizeFlowMediaUrl, readMediaUrl, } from "./dom"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { frontendBuild, lContextViewFields, readBuildLabel } from "./frontend_builds"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -86,9 +86,11 @@ export function resolveLView(elOrCtx: unknown): NgLView | null { if (raw && typeof raw === "object") { const lView = readOwn(raw, "lView"); if (Array.isArray(lView)) return lView; - const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView; - const verifiedView = contextField ? readOwn(raw, contextField) : undefined; - return Array.isArray(verifiedView) ? verifiedView : null; + for (const contextField of lContextViewFields()) { + const candidateView = readOwn(raw, contextField); + if (Array.isArray(candidateView)) return candidateView; + } + return null; } return null; } @@ -438,7 +440,8 @@ 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 build = frontendBuild(readBuildLabel()); + const resultField = (build ? build.projectStore.mutations?.sceneCreated : undefined) ?? "t6a"; let confirmedId: string | undefined; let failure: string | undefined; const completion = { @@ -457,7 +460,7 @@ export async function createScene( De: completion, ve: completion, })).then((response) => { - completion.resolve(readOwn(response, resultField)); + completion.resolve(readOwn(response, resultField) ?? readOwn(response, "VWa")); }, completion.reject); while (performance.now() < deadline) { diff --git a/ts/asset_ops.ts b/ts/asset_ops.ts index 546e15a..a6f307a 100644 --- a/ts/asset_ops.ts +++ b/ts/asset_ops.ts @@ -3,7 +3,7 @@ // Rename assets through the bound store. -import { activeProjectStoreFormat } from "./frontend_builds"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { AssetRenameExtra } from "./types"; @@ -15,8 +15,7 @@ export async function assetOps( ): Promise { if (action !== "rename") return { ok: false, err: "unknown_asset_action" }; if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, err: "unsupported_front_end" }; + return { ok: false, err: "unsupported_front_end", build: readBuildLabel() }; } const helper = runtimeState.store; if (!helper || !helper.isCurrent()) { diff --git a/ts/character_extra.ts b/ts/character_extra.ts index aed6828..f771c0b 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, + voiceConfirmationFormat, + type VoiceConfirmationFormat, +} from "./frontend_builds"; import type { CharacterExtraOpRequest } from "./types"; import { bindCustomVoiceReceipt, bindVoiceConfirmation } from "./voice_confirmation"; @@ -317,11 +322,12 @@ 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; + const format = voiceConfirmationFormat(); + const strictConfirm = Boolean(frontendBuild(readBuildLabel())?.voiceConfirmation); let pane = format ? await withLViewMapCapture(openDialog) : await openDialog(); if (!pane) return { ok: false, error: "voice_dialog_not_available" }; const confirm = format && bindVoiceConfirmation(format); - if (format && !confirm) { + if (strictConfirm && !confirm) { await dismissOverlay(); return { ok: false, error: "voice_confirmation_unavailable" }; } diff --git a/ts/character_media.ts b/ts/character_media.ts index 53d34d0..0a7c200 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -8,9 +8,22 @@ import { pickerElementMatches, readOwn, resolveLView, - withLViewMapCapture, type PickerMatchTarget, } from "./angular"; +import { + captureLViewAndClick, + dismissAllSnackbars, + findPreviewSlotButton, + getCharacterPreviewInstance, + isPreviewSlotOccupiedDom, + isPreviewSlotSelected, + normSlot, + probePreviewControls, + readPreviewSlotState, + selectPreviewSlot, + type CharacterPreview, + type CharacterSlot, +} from "./character_preview"; import { clickButtonByRegex, delay, @@ -18,9 +31,7 @@ import { elText, findSnackbarMatch, fifeBase, - hoverProbe, isVisibleEnabled, - legacyMedia, pickTileUrl, setNativeValue, } from "./dom"; @@ -31,218 +42,11 @@ import { } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; import { runtimeState } from "./state"; -import type { - CharacterMediaOpRequest, - FlowMediaPayload, - NgLView, -} from "./types"; - -/** Image slot in the character editor. */ -type CharacterSlot = "portrait" | "body"; +import type { CharacterMediaOpRequest } from "./types"; /** Maximum wait for the editor to select and load an upload slot. */ const UPLOAD_SLOT_TIMEOUT_MS = 30_000; -/** Character preview panel used to open the native picker and read slot state. */ -interface CharacterPreview { - /** Opens the picker for the active slot. */ - upload: () => unknown; - /** Reads one slot's media record. */ - media: (slot: CharacterSlot) => FlowMediaPayload | null | undefined; - /** Reads the source URL of the active slot. */ - source: () => unknown; - /** Reads the loading state of the active slot. */ - busy: () => unknown; -} - -/** Snapshot of character preview slot state read from component signals and DOM. */ -interface PreviewSlotState { - /** Resolved preview component instance when mounted. */ - previewComp: CharacterPreview | null; - /** Media record for the selected slot (`portrait` or `body`). */ - slotMedia: FlowMediaPayload | null | undefined; - /** Trimmed slot media identifier string. */ - slotMediaId: string; - /** Preview source URL reported by component signal. */ - compSrc: string; - /** Preview `` source attribute rendered in DOM. */ - imgSrc: string; - /** True while image preview container is busy. */ - isAreaBusy: boolean; -} - -/** Runs `fn` inside LView map capture when the registry map has not yet been discovered. */ -async function captureLViewAndClick(fn: () => void): Promise { - if (runtimeState.ngLViewMap instanceof Map) { - fn(); - return; - } - await withLViewMapCapture(async () => { - fn(); - await delay(250); - }); -} - -/** Reads a signal or calls a method on the native preview panel. */ -function callPanel(panel: object, name: string): unknown { - const method = readOwn(panel, name); - return typeof method === "function" ? method.call(panel) : undefined; -} - -/** Finds the preview panel in a live Angular view and binds its methods. */ -function getCharacterPreviewInstance(): CharacterPreview | null { - const format = characterPreviewFormat(); - 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) { - const lc = readOwn(slot, format.lifecycle); - if ( - slot && - typeof slot === "object" && - !(slot instanceof Node) && - !Array.isArray(slot) && - !(slot instanceof Map) && - !(lc && typeof lc === "object" && readOwn(lc, "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]); - } - } - } - return null; -} - -/** Normalizes character slot selector into `"portrait"` or `"body"`. */ -function normSlot(raw: unknown): CharacterSlot { - return String(raw || "portrait").toLowerCase() === "body" - ? "body" - : "portrait"; -} - -/** Reads current slot media, preview URLs, and busy indicators for `slot`. */ -function readPreviewSlotState(slot: CharacterSlot): PreviewSlotState { - const previewComp = getCharacterPreviewInstance(); - const slotMedia = previewComp?.media(slot); - const slotMediaId = String(slotMedia?.id || "").trim(); - const compSrc = String(previewComp?.source() || "").trim(); - const imgSrc = ( - document - .querySelector("flow-character-image-preview img.preview-image[src]") - ?.getAttribute("src") || "" - ).trim(); - const isAreaBusy = - Boolean( - document.querySelector( - 'flow-character-image-preview .image-area[aria-busy="true"]', - ), - ) || Boolean(previewComp?.busy()); - return { previewComp, slotMedia, slotMediaId, compSrc, imgSrc, isAreaBusy }; -} - -/** Dismisses active Flow snackbars so stale notifications do not mask results. */ -function dismissAllSnackbars(): boolean { - let dismissed = false; - for (const snack of document.querySelectorAll( - "flow-snackbar, simple-snack-bar, mat-snack-bar-container", - )) { - if (clickButtonByRegex(/^dismiss$/i, snack)) dismissed = true; - } - return dismissed; -} - -/** Finds a visible slot button, including the Create portrait and Create body states. */ -function findPreviewSlotButton(slot: CharacterSlot): HTMLButtonElement | undefined { - const label = slot === "portrait" ? /\bportrait\b/i : /\bbody\b/i; - return [...document.querySelectorAll( - "flow-character-preview-panel flow-slot-chip-button button", - )].find((button) => button.getClientRects().length > 0 && label.test(elText(button))); -} - -/** Reports whether the requested slot controls the visible preview. */ -function isPreviewSlotSelected(slot: CharacterSlot): boolean { - const button = findPreviewSlotButton(slot); - if (button) return button.classList.contains("chip-button-active"); - return slot === "portrait" && !findPreviewSlotButton("body") && - Boolean(document.querySelector("flow-character-image-preview")); -} - -/** Probes preview controls inside LView capture so Angular reveals its view registry. */ -async function probePreviewControls(): Promise { - const controls = [ - ...document.querySelectorAll( - "flow-character-preview-panel [mattooltip], flow-character-preview-panel button", - ), - ]; - await withLViewMapCapture(() => hoverProbe(controls.slice(0, 6))); -} - -/** Infers whether `slot` holds media from preview slot chips and rendered image state. */ -function isPreviewSlotOccupiedDom(slot: CharacterSlot): boolean { - const button = findPreviewSlotButton(slot); - if (button) { - const chip = button.closest("flow-slot-chip-button"); - if (chip?.querySelector("img[src]")) return true; - const label = `${elText(button)} ${button.getAttribute("aria-label") || ""}`; - if (/\bcreate\b/i.test(label)) return false; - if (!button.classList.contains("chip-button-active")) return true; - const previewImg = document - .querySelector("flow-character-image-preview img.preview-image[src]") - ?.getAttribute("src") - ?.trim(); - if (previewImg) return true; - const previewEl = document.querySelector("flow-character-image-preview"); - return !previewEl || !/\badd from project\b/i.test(elText(previewEl)); - } - return ( - slot === "portrait" && - Boolean( - document - .querySelector("flow-character-image-preview img.preview-image[src]") - ?.getAttribute("src") - ?.trim(), - ) - ); -} - -/** Selects the requested slot and waits for the preview controls. */ -async function selectPreviewSlot(slot: CharacterSlot, deadline: number): Promise { - let clicked: HTMLButtonElement | undefined; - while (performance.now() < deadline) { - if (isPreviewSlotSelected(slot)) return true; - const button = findPreviewSlotButton(slot); - if (isVisibleEnabled(button) && button !== clicked) { - clicked = button; - await captureLViewAndClick(() => button.click()); - } - await delay(100); - } - return false; -} - /** Handles character uploads, project reference attachments, and look generation prompts. */ export async function characterMediaOp( req: CharacterMediaOpRequest, diff --git a/ts/character_ops.ts b/ts/character_ops.ts index 788055c..5184cde 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -5,7 +5,11 @@ import { buildProjectUrl, findRouter, navigateSpa, readOwn } from "./angular"; import { clickButtonByRegex, delay, isVisibleEnabled, setNativeValue } from "./dom"; -import { activeProjectStoreFormat, characterCreateFormat } from "./frontend_builds"; +import { + activeProjectStoreFormat, + characterCreateFormat, + readBuildLabel, +} from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { CharacterOpRequest } from "./types"; @@ -88,10 +92,6 @@ export async function characterOp(req: CharacterOpRequest): Promise { return { ok: true, closed, in_workspace: inWorkspace }; } - if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; - } if (helper && !helper.isCurrent()) clearStore(); const activeHelper = runtimeState.store; const projectMatch = /\/project\/([^/?#]+)/.exec(location.pathname || ""); @@ -99,6 +99,9 @@ export async function characterOp(req: CharacterOpRequest): Promise { let charId = req?.character_id ? String(req.character_id).trim() : null; if (action === "create") { + if (!activeProjectStoreFormat()) { + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; + } if (!activeHelper) { return { ok: false, error: "store_not_bound" }; } @@ -252,7 +255,7 @@ export async function characterOp(req: CharacterOpRequest): Promise { for (let i = 0; i < 50; i++) { if ( document.querySelector( - 'flow-character-form, flow-character-image-preview, input[aria-label="Character name"]', + 'flow-character-form, flow-character-image-preview, input[aria-label="Character name"], textarea[aria-label="Character personality"]', ) ) { break; @@ -264,15 +267,16 @@ export async function characterOp(req: CharacterOpRequest): Promise { if (req?.name) { const nameStr = String(req.name).trim(); const nameInput = document.querySelector( - 'input[aria-label="Character name"]', + 'input[aria-label="Character name"], flow-character-form input[type="text"], flow-character-form input:not([type])', ); if (nameInput instanceof HTMLInputElement) { nameInput.focus(); setNativeValue(nameInput, nameStr, true); + nameInput.dispatchEvent(new Event("blur", { bubbles: true })); applied.push("ui_name"); await delay(150); } - if (charId && activeHelper?.rename) { + if (activeProjectStoreFormat() && charId && activeHelper?.rename) { try { await activeHelper.rename(charId, nameStr); applied.push("store_name"); @@ -282,6 +286,30 @@ export async function characterOp(req: CharacterOpRequest): Promise { error: err instanceof Error ? err.message : String(err ?? "rename_failed"), }; } + } else if (!applied.includes("ui_name")) { + return { ok: false, error: "character_name_input_not_found" }; + } + } + + if (req?.bio !== undefined && req?.bio !== null) { + const bioStr = String(req.bio); + const bioInput = document.querySelector( + 'textarea[aria-label="Character personality"], flow-character-form textarea, input[aria-label="Character personality"]', + ); + if ( + bioInput instanceof HTMLTextAreaElement || + bioInput instanceof HTMLInputElement + ) { + bioInput.focus(); + setNativeValue(bioInput, bioStr, true); + bioInput.dispatchEvent(new Event("blur", { bubbles: true })); + await delay(200); + if ((bioInput.value ?? "") !== bioStr) { + return { ok: false, error: "character_bio_input_mismatch" }; + } + applied.push("ui_bio"); + } else { + return { ok: false, error: "character_bio_input_not_found" }; } } diff --git a/ts/character_preview.ts b/ts/character_preview.ts new file mode 100644 index 0000000..ca8c785 --- /dev/null +++ b/ts/character_preview.ts @@ -0,0 +1,230 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Bind the character preview panel and manage portrait and body preview slots. + +import { readOwn, resolveLView, withLViewMapCapture } from "./angular"; +import { + clickButtonByRegex, + delay, + elText, + hoverProbe, + isVisibleEnabled, + legacyMedia, +} from "./dom"; +import { characterPreviewFormat } from "./frontend_builds"; +import { runtimeState } from "./state"; +import type { FlowMediaPayload, NgLView } from "./types"; + +/** Image slot in the character editor. */ +export type CharacterSlot = "portrait" | "body"; + +/** Character preview panel used to open the native picker and read slot state. */ +export interface CharacterPreview { + /** Opens the picker for the active slot. */ + upload: () => unknown; + /** Reads one slot's media record. */ + media: (slot: CharacterSlot) => FlowMediaPayload | null | undefined; + /** Reads the source URL of the active slot. */ + source: () => unknown; + /** Reads the loading state of the active slot. */ + busy: () => unknown; +} + +/** Snapshot of character preview slot state read from component signals and DOM. */ +export interface PreviewSlotState { + /** Resolved preview component instance when mounted. */ + previewComp: CharacterPreview | null; + /** Media record for the selected slot (`portrait` or `body`). */ + slotMedia: FlowMediaPayload | null | undefined; + /** Trimmed slot media identifier string. */ + slotMediaId: string; + /** Preview source URL reported by component signal. */ + compSrc: string; + /** Preview `` source attribute rendered in DOM. */ + imgSrc: string; + /** True while image preview container is busy. */ + isAreaBusy: boolean; +} + +/** Runs `fn` inside LView map capture when the registry map has not yet been discovered. */ +export async function captureLViewAndClick(fn: () => void): Promise { + if (runtimeState.ngLViewMap instanceof Map) { + fn(); + return; + } + await withLViewMapCapture(async () => { + fn(); + await delay(250); + }); +} + +/** Reads a signal or calls a method on the native preview panel. */ +function callPanel(panel: object, name: string): unknown { + const method = readOwn(panel, name); + return typeof method === "function" ? method.call(panel) : undefined; +} + +/** Finds the preview panel in a live Angular view and binds its methods. */ +export function getCharacterPreviewInstance(): CharacterPreview | null { + const format = characterPreviewFormat(); + 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) { + const lc = readOwn(slot, format.lifecycle); + if ( + slot && + typeof slot === "object" && + !(slot instanceof Node) && + !Array.isArray(slot) && + !(slot instanceof Map) && + !(lc && typeof lc === "object" && readOwn(lc, "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]); + } + } + } + return null; +} + +/** Normalizes character slot selector into `"portrait"` or `"body"`. */ +export function normSlot(raw: unknown): CharacterSlot { + return String(raw || "portrait").toLowerCase() === "body" + ? "body" + : "portrait"; +} + +/** Reads current slot media, preview URLs, and busy indicators for `slot`. */ +export function readPreviewSlotState(slot: CharacterSlot): PreviewSlotState { + const previewComp = getCharacterPreviewInstance(); + const slotMedia = previewComp?.media(slot); + const slotMediaId = String(slotMedia?.id || "").trim(); + const compSrc = String(previewComp?.source() || "").trim(); + const imgSrc = ( + document + .querySelector("flow-character-image-preview img.preview-image[src]") + ?.getAttribute("src") || "" + ).trim(); + const isAreaBusy = + Boolean( + document.querySelector( + 'flow-character-image-preview .image-area[aria-busy="true"]', + ), + ) || Boolean(previewComp?.busy()); + return { previewComp, slotMedia, slotMediaId, compSrc, imgSrc, isAreaBusy }; +} + +/** Dismisses active Flow snackbars so stale notifications do not mask results. */ +export function dismissAllSnackbars(): boolean { + let dismissed = false; + for (const snack of document.querySelectorAll( + "flow-snackbar, simple-snack-bar, mat-snack-bar-container", + )) { + if (clickButtonByRegex(/^dismiss$/i, snack)) dismissed = true; + } + return dismissed; +} + +/** Finds a visible slot button, including the Create portrait and Create body states. */ +export function findPreviewSlotButton(slot: CharacterSlot): HTMLButtonElement | undefined { + const label = slot === "portrait" ? /\bportrait\b/i : /\bbody\b/i; + return [ + ...document.querySelectorAll( + "flow-character-preview-panel flow-slot-chip-button button", + ), + ].find((button) => button.getClientRects().length > 0 && label.test(elText(button))); +} + +/** Reports whether the requested slot controls the visible preview. */ +export function isPreviewSlotSelected(slot: CharacterSlot): boolean { + const button = findPreviewSlotButton(slot); + if (button) return button.classList.contains("chip-button-active"); + return ( + slot === "portrait" && + !findPreviewSlotButton("body") && + Boolean(document.querySelector("flow-character-image-preview")) + ); +} + +/** Probes preview controls inside LView capture so Angular reveals its view registry. */ +export async function probePreviewControls(): Promise { + const controls = [ + ...document.querySelectorAll( + "flow-character-preview-panel [mattooltip], flow-character-preview-panel button", + ), + ]; + await withLViewMapCapture(() => hoverProbe(controls.slice(0, 6))); +} + +/** Infers whether `slot` holds media from preview slot chips and rendered image state. */ +export function isPreviewSlotOccupiedDom(slot: CharacterSlot): boolean { + const button = findPreviewSlotButton(slot); + if (button) { + const chip = button.closest("flow-slot-chip-button"); + if (chip?.querySelector("img[src]")) return true; + const label = `${elText(button)} ${button.getAttribute("aria-label") || ""}`; + if (/\bcreate\b/i.test(label)) return false; + if (!button.classList.contains("chip-button-active")) return true; + const previewImg = document + .querySelector("flow-character-image-preview img.preview-image[src]") + ?.getAttribute("src") + ?.trim(); + if (previewImg) return true; + const previewEl = document.querySelector("flow-character-image-preview"); + return !previewEl || !/\badd from project\b/i.test(elText(previewEl)); + } + return ( + slot === "portrait" && + Boolean( + document + .querySelector("flow-character-image-preview img.preview-image[src]") + ?.getAttribute("src") + ?.trim(), + ) + ); +} + +/** Selects the requested slot and waits for the preview controls. */ +export async function selectPreviewSlot( + slot: CharacterSlot, + deadline: number, +): Promise { + let clicked: HTMLButtonElement | undefined; + while (performance.now() < deadline) { + if (isPreviewSlotSelected(slot)) return true; + const button = findPreviewSlotButton(slot); + if (isVisibleEnabled(button) && button !== clicked) { + clicked = button; + await captureLViewAndClick(() => button.click()); + } + await delay(100); + } + return false; +} diff --git a/ts/character_voices.ts b/ts/character_voices.ts index a434d37..cdeeb86 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -3,7 +3,7 @@ // List and assign Google Flow character voices inside the character editor. -import { readOwn, startMapCapture, type NgContextCarrier } from "./angular"; +import { readOwn, resolveLView, startMapCapture, type NgContextCarrier } from "./angular"; import { VOICE_ICON_WORDS, voicePane } from "./character_extra"; import { clickButtonByRegex, @@ -118,13 +118,14 @@ export async function characterVoiceOp( }; return walk(rootLv, 0); }; - const formNg = (form as NgContextCarrier).__ngContext__; + const formLv = resolveLView(form); const direct = - scanLView(formNg, isExactComp) || scanLView(formNg, isFormComp); + scanLView(formLv, isExactComp) || scanLView(formLv, isFormComp); if (direct) { formComponents.set(form, direct); return direct; } + const formNg = (form as NgContextCarrier).__ngContext__; if (typeof formNg !== "number" || probedForms.has(form)) { return null; } diff --git a/ts/discover_store.ts b/ts/discover_store.ts index a6b793e..f61c161 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -5,7 +5,6 @@ import { isNgLViewMap, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe } from "./dom"; -import { activeProjectStoreFormat } from "./frontend_builds"; import { clearProjectStore, currentProjectStore, @@ -119,12 +118,8 @@ async function captureStoreDuring( return selectProjectStoreCandidate(candidates) ?? null; } -/** Binds the verified project store from DOM contexts or transient Angular view activity. */ +/** Binds the project store from DOM contexts or transient Angular view activity. */ export async function discoverStore(): Promise { - if (!activeProjectStoreFormat()) { - clearProjectStore(); - return { bound: false, newlyDiscovered: false, error: "unsupported_front_end" }; - } const projectId = projectInRoute(); if (!projectId) { clearProjectStore(); diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index c10c146..086bb00 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -831,12 +831,42 @@ const LEGACY_CHARACTER_CREATE: CharacterCreateFormat = { /** Editable project title format of earlier builds. */ const LEGACY_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "tJa", stateSignal: "state" }; +/** Character preview format of build `20261120.00_p0` used as the default fallback. */ +const NOVEMBER_20_CHARACTER_PREVIEW: CharacterPreviewFormat = { + lifecycle: "Ba", upload: "NV", marker: "hh", portrait: "ka", body: "ma", + source: "Gza", busy: "mB", footerBusy: "Zh", pickerAssets: "xZ", pickerSelect: "Qda", +}; + +/** Character voice form format of build `20261120.00_p0` used as the default fallback. */ +const NOVEMBER_20_CHARACTER_VOICE: CharacterVoiceFormat = { + lifecycle: "Ba", destroyed: "Va", voiceMap: "o_", selectedVoice: "A3", + selectedRecord: "Pua", changeEmitter: "Pea", busy: "yb", emptyMap: true, +}; + +/** Character creation format of build `20261120.00_p0` used as the default fallback. */ +const NOVEMBER_20_CHARACTER_CREATE: CharacterCreateFormat = { + lifecycle: "Ba", destroyed: "Va", entityKinds: ["pM"], + collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], +}; + +/** Editable project title format of build `20261120.00_p0` used as the default fallback. */ +const NOVEMBER_20_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "HSa", stateSignal: "state" }; + +/** Voice confirmation format of build `20261120.00_p0` used as the default fallback. */ +const NOVEMBER_20_VOICE_CONFIRMATION: VoiceConfirmationFormat = { + editor: "qu", entityQuery: "ma", savedVoice: "Xjb", selectedVoice: "A3", + previewSaved: "MK", pickerSelection: "Qn", +}; + /** Request formats by exact build label. Include only verified operations. */ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261117.10_p0", { legacy: true, projectStore: NOVEMBER_17_STORE, + characterPreview: LEGACY_CHARACTER_PREVIEW, + characterVoice: LEGACY_CHARACTER_VOICE, characterCreate: { ...LEGACY_CHARACTER_CREATE, lifecycle: "Ca", destroyed: "Wa" }, + projectTitle: LEGACY_PROJECT_TITLE, operations: { collection_write: { tileId: "Uc", tileChange: "df", moveTarget: "Sj", moveTiles: "Bb" }, asset_trash_store: { @@ -852,8 +882,10 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ }], ["boq_labs-ai-sandbox-frontend_20261118.14_p0", { projectStore: NOVEMBER_18_STORE, + characterPreview: LEGACY_CHARACTER_PREVIEW, characterCreate: { ...LEGACY_CHARACTER_CREATE, lifecycle: "Ba", destroyed: "Va" }, characterVoice: { ...LEGACY_CHARACTER_VOICE, lifecycle: "Ba", destroyed: "Va" }, + projectTitle: LEGACY_PROJECT_TITLE, operations: { collection_write: { tileId: "Vc", tileChange: "jf", moveTarget: "Wj", moveTiles: "Ab" }, asset_trash_store: { @@ -870,23 +902,11 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261120.00_p0", { projectStore: NOVEMBER_20_STORE, snapshot: NOVEMBER_20_SNAPSHOT, - voiceConfirmation: { - editor: "qu", entityQuery: "ma", savedVoice: "Xjb", selectedVoice: "A3", - previewSaved: "MK", pickerSelection: "Qn", - }, - characterPreview: { - lifecycle: "Ba", upload: "NV", marker: "hh", portrait: "ka", body: "ma", - source: "Gza", busy: "mB", footerBusy: "Zh", pickerAssets: "xZ", pickerSelect: "Qda", - }, - characterVoice: { - lifecycle: "Ba", destroyed: "Va", voiceMap: "o_", selectedVoice: "A3", - selectedRecord: "Pua", changeEmitter: "Pea", busy: "yb", emptyMap: true, - }, - characterCreate: { - lifecycle: "Ba", destroyed: "Va", entityKinds: ["pM"], - collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], - }, - projectTitle: { saveEmitter: "HSa", stateSignal: "state" }, + voiceConfirmation: NOVEMBER_20_VOICE_CONFIRMATION, + characterPreview: NOVEMBER_20_CHARACTER_PREVIEW, + characterVoice: NOVEMBER_20_CHARACTER_VOICE, + characterCreate: NOVEMBER_20_CHARACTER_CREATE, + projectTitle: NOVEMBER_20_PROJECT_TITLE, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -904,6 +924,11 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ }], ]); +/** Verified project store formats ordered from newest to oldest for read-only discovery. */ +const CASCADED_PROJECT_STORES: readonly ProjectStoreFormat[] = Array.from( + new Set(Array.from(VERIFIED_BUILDS.values(), (b) => b.projectStore).reverse()), +); + /** Returns the exact label published by the active page. */ export function readBuildLabel(): string | null { const label = window.WIZ_global_data?.cfb2h; @@ -920,10 +945,30 @@ export function activeProjectStoreFormat(): ProjectStoreFormat | undefined { return frontendBuild(readBuildLabel())?.projectStore; } +/** Returns candidate store layouts from newest to oldest when the active build is unverified. */ +export function projectStoreFormats(): readonly ProjectStoreFormat[] { + const verified = activeProjectStoreFormat(); + return verified ? [verified] : CASCADED_PROJECT_STORES; +} + +/** Returns candidate Angular `LContext` view property names, defaulting to `20261120.00_p0` first. */ +export function lContextViewFields(): readonly string[] { + const verified = activeProjectStoreFormat(); + if (verified) return [verified.lContextView]; + return Array.from( + new Set([NOVEMBER_20_STORE.lContextView, ...CASCADED_PROJECT_STORES.map((s) => s.lContextView)]), + ); +} + +/** Returns the scene clip and history field names, defaulting to `20261120.00_p0`. */ +export function sceneTileFormat(): NonNullable { + return activeProjectStoreFormat()?.scene ?? { clips: "Uc", history: "Cg" }; +} + /** Adds the native fields used by the verified project store mutator. */ export function withMutationAliases(payload: Record): Record { const build = frontendBuild(readBuildLabel()); - const format = build?.projectStore.mutations; + const format = build ? build.projectStore.mutations : NOVEMBER_20_STORE.mutations; if (payload.type === "single_tile" && payload.Ve && typeof payload.Ve === "object") { const change = payload.Ve as Record; if (format) { @@ -956,25 +1001,36 @@ export function withMutationAliases(payload: Record): Record, ): Promise { if (!activeProjectStoreFormat()) { - clearProjectStore(); throw new Error("unsupported_front_end"); } if (activeBoundStore() !== store || !isCurrent(store)) { @@ -312,13 +316,17 @@ export function installProjectStore(store: ProjectStore, views?: Map { const frontEnd = readOwn(window, "default_AiSandboxAngularFrontend"); - const storeClass = readOwn(frontEnd, format.storeClass); - return typeof storeClass === "function" ? { format, storeClass } : null; + const layouts: Array<{ format: ProjectStoreFormat; storeClass: Function }> = []; + for (const format of projectStoreFormats()) { + const storeClass = readOwn(frontEnd, format.storeClass); + if (typeof storeClass === "function") { + layouts.push({ format, storeClass }); + } + } + return layouts; } /** Collects live `ProjectStore` candidates from one Angular `LView` array. */ @@ -328,23 +336,27 @@ export function findProjectStoreInView( seen = new Set(), ): ProjectStore[] { if (!Array.isArray(view)) return []; - const layout = verifiedStoreLayout(); - if (!layout) return []; - const { format, storeClass } = layout; + const layouts = verifiedStoreLayouts(); + if (layouts.length === 0) return []; const matches: ProjectStore[] = []; const consider = (value: unknown): void => { if (!value || typeof value !== "object" || seen.has(value)) return; seen.add(value); - if (!(value instanceof storeClass)) return; - const candidate: ProjectStore = { projectId, service: value, format }; - if (isCurrent(candidate)) matches.push(candidate); + for (const { format, storeClass } of layouts) { + if (!(value instanceof storeClass)) continue; + const candidate: ProjectStore = { projectId, service: value, format }; + if (isCurrent(candidate)) matches.push(candidate); + break; + } }; for (const slot of view) { consider(slot); if (!slot || typeof slot !== "object" || slot instanceof Node) continue; - for (const key of format.componentSlots) { - consider(Object.getOwnPropertyDescriptor(slot, key)?.value); + for (const { format } of layouts) { + for (const key of format.componentSlots) { + consider(Object.getOwnPropertyDescriptor(slot, key)?.value); + } } } return matches; @@ -353,41 +365,38 @@ export function findProjectStoreInView( /** Reports whether the current runtime has a bound and ready store for `projectId`. */ export function projectStoreStatus(projectId: string): ProjectStoreStatus { const build = readBuildLabel(); - if (!activeProjectStoreFormat()) { - clearProjectStore(); - return { ok: false, error: "unsupported_front_end", build }; - } if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; const store = currentProjectStore(projectId); - if (!store) return { ok: false, error: "collection_store_not_bound" }; + if (!store) return { ok: false, error: "collection_store_not_bound", build }; if (isProjectStorePending(store)) { - return { ok: false, bound: true, error: "store_loading" }; + return { ok: false, bound: true, error: "store_loading", build }; } if (!readProjectStore(store)) { - return { ok: false, error: "collection_store_not_bound" }; + return { ok: false, error: "collection_store_not_bound", build }; } session ??= crypto.randomUUID(); - return { ok: true, bound: true, session }; + return { ok: true, bound: true, session, build }; } -/** Selects a single verified store. If several stores match, selects the only ready store. */ +/** Selects a store from the newest matching format, preferring the single ready store. */ export function selectProjectStoreCandidate(candidates: ProjectStore[]): ProjectStore | undefined { - if (candidates.length === 1) return candidates[0]; - const ready = candidates.filter((store) => Boolean(readProjectStore(store))); - return ready.length === 1 ? ready[0] : undefined; + for (const format of projectStoreFormats()) { + const matching = candidates.filter((store) => store.format === format); + if (matching.length === 0) continue; + if (matching.length === 1) return matching[0]; + const ready = matching.filter((store) => Boolean(readProjectStore(store))); + return ready.length === 1 ? ready[0] : undefined; + } + return undefined; } -/** Binds one live verified store found in the Angular view registry. */ +/** Binds one live store found in the Angular view registry using the newest matching verified layout. */ export function bindProjectStore(maps: unknown[], projectId: string): ProjectStoreStatus { const build = readBuildLabel(); - if (!activeProjectStoreFormat()) { - clearProjectStore(); - return { ok: false, error: "unsupported_front_end", build }; - } if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; - if (!verifiedStoreLayout()) { + if (verifiedStoreLayouts().length === 0) { clearProjectStore(); - return { ok: false, error: "collection_store_not_bound" }; + return { ok: false, error: "collection_store_not_bound", build }; } const seen = new Set(); @@ -437,6 +446,9 @@ async function submitProjectMutation( store: ProjectStore, payload: Record, ): Promise { + if (!activeProjectStoreFormat()) { + throw new Error("unsupported_front_end"); + } const dispatch = storeDispatcher(store); if (!isCurrent(store) || activeBoundStore() !== store || typeof dispatch !== "function") { throw new Error("project_store_changed"); diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..e4f8d52 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -7,11 +7,13 @@ import { buildProjectUrl, readOwn, resolveLView, + withLViewMapCapture, withMapCapture, type NgContextCarrier, } from "./angular"; -import { delay, elText, setNativeValue } from "./dom"; +import { delay, elText, hoverProbe, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; +import { runtimeState } from "./state"; import type { ProjectsOpRequest } from "./types"; /** Internal card descriptor captured on the Flow projects grid. */ @@ -137,9 +139,10 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } if (!pid) { + const cardLv = resolveLView(card); const ng = (card as NgContextCarrier).__ngContext__; - if (Array.isArray(ng)) { - pid = extractIdFromObject(ng, 0, new Set()); + if (Array.isArray(cardLv)) { + pid = extractIdFromObject(cardLv, 0, new Set()); } else if (typeof ng === "number") { for (const sm of seenMaps) { try { @@ -347,6 +350,12 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { (titleInput.value || "").trim() !== desired) ) { try { + if ( + !(runtimeState.ngLViewMap instanceof Map) && + typeof (host as NgContextCarrier).__ngContext__ === "number" + ) { + await withLViewMapCapture(() => hoverProbe([host])); + } const lv = resolveLView(host); if (Array.isArray(lv)) { const titleFormat = projectTitleFormat(); @@ -391,6 +400,22 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { return { ok: false, error: "project_title_not_confirmed" }; } + if (action === "get_title") { + const titleInput = document.querySelector( + 'flow-editable-text input, input[aria-label*="project" i], header input[type="text"]', + ); + if (!(titleInput instanceof HTMLInputElement)) { + return { ok: false, error: "project_title_input_not_found" }; + } + const host = titleInput.closest("flow-editable-text"); + const editing = Boolean(host?.querySelector(".editable-text-container.editing")); + return { + ok: true, + editing, + title: (titleInput.value || "").trim(), + }; + } + if (action === "delete") { const targetId = req?.project_id ? String(req.project_id).trim() : ""; const targetTitle = req?.title ? String(req.title).trim() : ""; diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..95fea7b 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -5,7 +5,7 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; -import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; +import { snapshotFormat } from "./frontend_builds"; import { currentProjectStore, projectInRoute } from "./project_store"; import { sceneContents } from "./scene_tiles"; import { @@ -182,10 +182,6 @@ function normalizeVoiceVal(v: unknown): string | null { /** Reads project tiles, scenes, characters, and collections from bound runtime state. */ export function readStoreSnapshot(): StoreSnapshotResult { - if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; - } const match = /\/project\/([^/?#]+)/.exec(location.pathname || ""); const projectId = match ? match[1] : null; const helper = runtimeState.store; diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index fc47fbb..a21e3ff 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -5,15 +5,14 @@ import { createScene } from "./angular"; import { delay } from "./dom"; -import { activeProjectStoreFormat } from "./frontend_builds"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, SceneOpRequest } from "./types"; /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; } const helper = runtimeState.store; if (!helper || !helper.isCurrent()) { diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..96cc986 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -4,14 +4,14 @@ // Read clips and workflow history from the native scene tile. import { readOwn } from "./angular"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { sceneTileFormat } from "./frontend_builds"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { - const format = frontendBuild(readBuildLabel())?.projectStore.scene; - const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; - const history = (format && readOwn(tile, format.history)) ?? tile.Yf; + const format = sceneTileFormat(); + const clips = readOwn(tile, format.clips) ?? readOwn(tile, "Tc") ?? tile.Oc; + const history = readOwn(tile, format.history) ?? readOwn(tile, "tg") ?? 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..26b239b 100644 --- a/ts/tile_dom.ts +++ b/ts/tile_dom.ts @@ -3,10 +3,25 @@ // 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 { + readOwn, + resolveLView, + withLViewMapCapture, + type NgContextCarrier, +} from "./angular"; +import { + collectionIdOf, + delay, + dismissOverlay, + elText, + hoverProbe, + isTrashedTile, + isVisibleEnabled, + legacyTile, +} from "./dom"; import { openView, readText, readView, selectText } from "./page_view"; import { runtimeState } from "./state"; -import type { FlowTile, TileDomOpRequest, ViewportPoint } from "./types"; +import type { FlowTile, NgLView, TileDomOpRequest, ViewportPoint } from "./types"; /** Returns the media IDs that the page can show for the store tile `raw`. */ function mediaIdsOf(raw: FlowTile | null | undefined): string[] { @@ -35,6 +50,123 @@ function mediaIsShared( return false; } +/** Captures the Angular `LView` map from rendered grid containers when numeric contexts are active. */ +async function ensureGridLViewMap(): Promise { + if (runtimeState.ngLViewMap instanceof Map) return; + const containers = Array.from( + document.querySelectorAll("flow-grid-tile-container"), + ); + const needsMap = containers.some( + (el) => typeof (el as NgContextCarrier).__ngContext__ === "number", + ); + if (!needsMap) return; + const probes: Element[] = []; + for (const el of containers.slice(0, 4)) { + probes.push(el); + const btn = el.querySelector("button, [mattooltip]"); + if (btn) probes.push(btn); + } + await withLViewMapCapture(() => hoverProbe(probes, 20)); +} + +/** Returns true when `cand` is a single tile record whose identifier matches `id` or `target`. */ +function objectMatchesTile(cand: unknown, id: string, target: FlowTile): boolean { + if (cand === target) return true; + if ( + !cand || + typeof cand !== "object" || + cand instanceof Node || + cand instanceof Map || + cand instanceof Set || + cand instanceof Error || + Array.isArray(cand) + ) { + return false; + } + const candId = readOwn(cand, "id"); + return candId !== undefined && candId !== null && String(candId) === id; +} + +/** Returns true when one `LView` slot or component input signal binds `id`. */ +function slotMatchesTile(slot: unknown, id: string, target: FlowTile): boolean { + if (objectMatchesTile(slot, id, target)) return true; + if ( + !slot || + typeof slot !== "object" || + slot instanceof Node || + slot instanceof Map || + slot instanceof Set || + slot instanceof Error || + Array.isArray(slot) + ) { + return false; + } + for (const key of Object.getOwnPropertyNames(slot)) { + const desc = Object.getOwnPropertyDescriptor(slot, key); + if (!desc || !("value" in desc)) continue; + const val: unknown = desc.value; + if (objectMatchesTile(val, id, target)) return true; + if (typeof val === "function" && val.length === 0) { + try { + if (objectMatchesTile(val.call(slot), id, target)) return true; + } catch { + // Ignore unset Angular required input signals or stateful methods. + } + } + } + return false; +} + +/** Returns true when `view` belongs exclusively to `container` rather than the whole grid. */ +function isSingleTileView(view: NgLView, container: HTMLElement): boolean { + const hasOtherContainer = view.some( + (s) => s instanceof Element && s.tagName === "FLOW-GRID-TILE-CONTAINER" && s !== container, + ); + if (hasOtherContainer) return false; + const root = view[0]; + if (root instanceof Element) { + if (container.contains(root)) return true; + return ( + root.contains(container) && + root.querySelectorAll("flow-grid-tile-container").length <= 1 + ); + } + return view.some((s) => s === container || (s instanceof Node && container.contains(s))); +} + +/** Returns true when `container`'s scoped Angular `LView` slots bind tile `id`. */ +function containerMatchesTile(container: HTMLElement, id: string, target: FlowTile): boolean { + const views = new Set(); + const addHostView = (el: Element, checkParent: boolean): void => { + const lv = resolveLView(el); + if (!Array.isArray(lv)) return; + views.add(lv); + if (!checkParent) return; + for (const parent of [lv[3], lv[15]]) { + if (Array.isArray(parent) && isSingleTileView(parent, container)) { + views.add(parent); + } + } + }; + addHostView(container, true); + for (const child of Array.from(container.querySelectorAll("*")).slice(0, 24)) { + if (child.tagName.includes("-") || "__ngContext__" in child) { + addHostView(child, false); + } + } + for (const lv of views) { + if (lv.some((slot) => slotMatchesTile(slot, id, target))) return true; + } + return false; +} + +/** Returns rendered `flow-grid-tile-container` elements whose `LView` slots match `id`. */ +function findContainersByLView(id: string, target: FlowTile): HTMLElement[] { + return Array.from( + document.querySelectorAll("flow-grid-tile-container"), + ).filter((el) => containerMatchesTile(el, id, target)); +} + /** Returns the rendered grid tiles that show one of `mediaIds`. */ function findContainers(mediaIds: string[]): HTMLElement[] { const found = new Set(); @@ -108,17 +240,46 @@ 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 target = tileMap.get(id); + if (!target) return { ok: false, error: "tile_not_found" }; + await ensureGridLViewMap(); + const mediaIds = mediaIdsOf(target); + const sharedMedia = mediaIds.length > 0 && mediaIsShared(tileMap, id, mediaIds); + const find = (): HTMLElement[] => { + const byLView = findContainersByLView(id, target); + if (byLView.length > 0) return byLView; + if (mediaIds.length > 0 && !sharedMedia) return findContainers(mediaIds); + return []; + }; + const located = await locateContainer(find); + if (located.ok !== true && located.error === "tile_not_rendered" && sharedMedia) { return { ok: false, error: "tile_media_ambiguous" }; } - return locateContainer(() => findContainers(mediaIds)); + return located; +} + +/** Finds the confirm button of an open trash dialog and returns its viewport point. */ +function confirmTrashDialog(): Record { + const dialogs = Array.from( + document.querySelectorAll( + '[role="dialog"], [role="alertdialog"], mat-dialog-container', + ), + ).filter((el) => el.getClientRects().length > 0); + const pattern = + /^(?:(?:delete|delete_forever|warning)\s+)?(?:move(?: all contents)? to trash|delete)$/i; + for (const dialog of dialogs) { + for (const btn of Array.from(dialog.querySelectorAll("button"))) { + if (!isVisibleEnabled(btn)) continue; + if (pattern.test(elText(btn))) { + return { ok: true, point: centerOf(btn) }; + } + } + } + return { ok: false, error: "dialog_confirm_not_found" }; } /** Returns `present`, `trashed`, or `gone` for the store tile `id`, with its name and its collection ID while it is present. */ @@ -147,6 +308,7 @@ export async function tileDomOp(req: TileDomOpRequest): Promise { if (action === "open_view") return openView(id); if (action === "text_select") return selectText(); if (action === "text_value") return readText(); + if (action === "confirm_dialog") return confirmTrashDialog(); if (action === "dismiss") { await dismissOverlay(); return { ok: true }; diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..cc2dc60 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -681,6 +681,8 @@ export interface CharacterOpRequest { character_id?: string | null; /** Character display name. */ name?: string | null; + /** Optional character personality notes updated in the character form. */ + bio?: string | null; /** Optional voice name triggering editor navigation after create. */ voice?: string | null; /** Optional project reference asset IDs triggering editor navigation after create. */ @@ -757,7 +759,7 @@ export interface LocatePointRequest { /** Request for `tileDomOp`. */ export interface TileDomOpRequest { - /** `locate`, `state`, `view`, `open_view`, `text_select`, `text_value`, or `dismiss`. */ + /** `locate`, `state`, `view`, `open_view`, `text_select`, `text_value`, `confirm_dialog`, or `dismiss`. */ action: string; /** Store tile ID for `locate` and `state`, or the collection ID for `open_view` (empty for the main grid). */ id?: string; diff --git a/ts/video_ops.ts b/ts/video_ops.ts index 0cc0e8c..265bf06 100644 --- a/ts/video_ops.ts +++ b/ts/video_ops.ts @@ -6,7 +6,7 @@ import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, withLViewMapCapture } from "./angular"; import { findComposerWarning } from "./composer"; import { delay, elText, hoverProbe, isDisabledProp, isVisibleEnabled, legacyTile, videoTrimBounds } from "./dom"; -import { activeProjectStoreFormat } from "./frontend_builds"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; import { clearStore, runtimeState } from "./state"; import type { FlowTile, VideoOpRequest } from "./types"; @@ -51,8 +51,7 @@ export async function videoOp(req: VideoOpRequest): Promise { if (action === "trim") { if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; } if (!helper || !helper.isCurrent()) { if (helper) clearStore(); @@ -141,22 +140,21 @@ export async function videoOp(req: VideoOpRequest): Promise { const id = String(req?.asset_id || "").trim(); const activeScene = /\/scene\/([^/?#]+)/.exec(location.pathname)?.[1]; if (!activeScene || (req.scene_id && activeScene !== req.scene_id)) { - if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; - } - if (!helper || !helper.isCurrent()) { - if (helper) clearStore(); - return { ok: false, error: "store_not_bound" }; - } - if (!helper.isReady()) { - return { ok: false, error: "store_loading" }; - } - if (!(tileMap instanceof Map) || !helper.mutate) { - return { ok: false, error: "store_not_bound" }; - } let sceneId = req?.scene_id ? String(req.scene_id).trim() : null; if (!sceneId) { + if (!activeProjectStoreFormat()) { + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; + } + if (!helper || !helper.isCurrent()) { + if (helper) clearStore(); + return { ok: false, error: "store_not_bound" }; + } + if (!helper.isReady()) { + return { ok: false, error: "store_loading" }; + } + if (!(tileMap instanceof Map) || !helper.mutate) { + return { ok: false, error: "store_not_bound" }; + } const wfId = String(tileMap.get(id)?.workflowId || id); const created = await createScene(helper, getMap, [wfId]); if (!created?.ok || !created.id) { From 5801b01f6a381190b9c0caefde67fa0f3e930c1c 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 04:18:40 +0000 Subject: [PATCH 2/2] fix(flow): tighten store cascade safety and verified build gates - Restrict slotMatchesTile to allow-listed Angular signal keys - Pair snapshot and scene formats with the bound cascaded store - Validate cascaded tile readability and fail closed on drift - Restore immediate unsupported_front_end stops with build labels - Tighten character form selectors and poll debounced store reads - Route collection IDs directly to store writes in rename_assets - Bind trash dialog checks to target tiles and cap wait at 40 polls - Consolidate store write error and snapshot collection helpers - Gate internal mutations and component hooks on VERIFIED_BUILDS --- src/assets.rs | 69 +++++++++---------- src/character_bio.rs | 48 ++++++++----- src/characters.rs | 10 ++- src/collections.rs | 15 ++-- src/project.rs | 42 ++++++++++-- src/project_store.rs | 22 +++++- src/tile_menu.rs | 6 +- src/upload.rs | 16 +---- ts/angular.ts | 21 ++++-- ts/character_extra.ts | 6 +- ts/character_media.ts | 10 +-- ts/character_ops.ts | 128 +++++++++++++++++++++++++++++++---- ts/character_preview.ts | 1 + ts/character_voices.ts | 29 +++++--- ts/discover_store.ts | 34 +++++++++- ts/frontend_builds.ts | 123 +++++++++++++++------------------ ts/frontend_compatibility.ts | 84 ++++++++++++++++++++++- ts/project_store.ts | 45 +++++++++--- ts/projects_ops.ts | 6 +- ts/read_store_snapshot.ts | 9 ++- ts/scene_tiles.ts | 6 +- ts/state.ts | 5 ++ ts/tile_dom.ts | 106 ++++++++++++++++++++++++++--- ts/types.ts | 4 +- 24 files changed, 622 insertions(+), 223 deletions(-) diff --git a/src/assets.rs b/src/assets.rs index 0d93ed2..01f7e0f 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; use std::collections::{HashMap, HashSet}; use tokio::time::{Duration, Instant}; -use crate::collections::{FlowCollection, find_collection}; +use crate::collections::{find_collection, snapshot_collections}; use crate::db::FlowDb; use crate::download::eval_resolve_media_url; use crate::engine::ChromeEngine; @@ -241,9 +241,18 @@ pub(crate) async fn list_assets_with_project( Ok(snapshot) } +/// Extracts the asset list from a project store snapshot. +fn snapshot_assets(snap: &mut Value) -> Result> { + Ok(serde_json::from_value( + snap.get_mut("assets") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?) +} + /// Reads project metadata and assets without requesting media URLs. async fn read_project_assets(engine: &ChromeEngine) -> Result { - let snap = read_snapshot(engine).await?; + let mut snap = read_snapshot(engine).await?; let project_id = snap .get("projectId") .and_then(|v| v.as_str()) @@ -256,11 +265,7 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result b false } -/// Renames collections through the menu or collection store and other tiles through the page or store. +/// Renames collections through the collection store and other tiles through the page or store. pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec) -> Result { ensure_flow_store(engine).await?; let mut snap = read_snapshot(engine).await?; - let collection_list: Vec = serde_json::from_value( - snap.get_mut("collections") - .map(Value::take) - .unwrap_or_else(|| json!([])), - )?; - let collection_ids: HashSet = collection_list.into_iter().map(|c| c.id).collect(); + let collection_ids: HashSet = snapshot_collections(&mut snap)? + .into_iter() + .map(|c| c.id) + .collect(); let total = items.len(); let mut renamed = Vec::new(); let mut failed = Vec::new(); 'items: for (idx, entry) in items.into_iter().enumerate() { - // Use the rename control of the page first. The page then builds its own mutation. - if tile_state(engine, &entry.id).await.is_present() - && matches!( - rename_through_menu(engine, &entry.id, &entry.name).await, - Ok(true) - ) - { - renamed.push(json!({ "id": entry.id, "name": entry.name, "method": "menu:rename" })); - if idx + 1 < total { - tokio::time::sleep(Duration::from_millis(250)).await; - } - continue 'items; - } if collection_ids.contains(&entry.id) { match ProjectStoreSession::open(engine).await { Ok(collections) => match collections.rename(&entry.id, &entry.name).await { @@ -474,6 +464,19 @@ pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec } continue 'items; } + // Use the rename control of the page first. The page then builds its own mutation. + if tile_state(engine, &entry.id).await.is_present() + && matches!( + rename_through_menu(engine, &entry.id, &entry.name).await, + Ok(true) + ) + { + renamed.push(json!({ "id": entry.id, "name": entry.name, "method": "menu:rename" })); + if idx + 1 < total { + tokio::time::sleep(Duration::from_millis(250)).await; + } + continue 'items; + } ensure_flow_store(engine).await?; let mut ok = false; for attempt in 0..2 { @@ -560,21 +563,13 @@ pub(crate) async fn trash_asset( let query = match_str.trim(); ensure_flow_store(engine).await?; let mut snap = read_snapshot(engine).await?; - let summaries: Vec = serde_json::from_value( - snap.get_mut("collections") - .map(Value::take) - .unwrap_or_else(|| json!([])), - )?; + let summaries = snapshot_collections(&mut snap)?; if summaries.iter().any(|c| c.id == query) { let collections = ProjectStoreSession::open(engine).await?; return collections.delete(query).await; } - let raw_assets: Vec = serde_json::from_value( - snap.get_mut("assets") - .map(Value::take) - .unwrap_or_else(|| json!([])), - )?; + let raw_assets = snapshot_assets(&mut snap)?; let Some(asset) = match_asset(&raw_assets, query, true).cloned() else { let collection = find_collection(&summaries, query, true)? .with_context(|| format!("No asset or collection matches '{query}' for flow_trash"))?; diff --git a/src/character_bio.rs b/src/character_bio.rs index 8b0f9ad..b3965c4 100644 --- a/src/character_bio.rs +++ b/src/character_bio.rs @@ -14,16 +14,7 @@ use crate::db::FlowDb; use crate::engine::ChromeEngine; use crate::project::{ensure_flow_store, ensure_project_workspace_root, project_id_from_url}; use crate::project_route::character_id_from_url; -use crate::project_store::ProjectStoreSession; - -/// Returns true when `err` indicates that direct character bio store mutations are unverified. -fn is_unsupported_bio_store(err: &anyhow::Error) -> bool { - let msg = format!("{err:#}"); - !msg.contains("outcome_unknown") - && (msg.contains("unsupported_front_end") - || msg.contains("collection_store_not_bound") - || msg.contains("ambiguous_collection_store")) -} +use crate::project_store::{ProjectStoreSession, is_store_write_unavailable}; /// Opens a verified project store session for character bio writes, or returns `Ok(None)` on unverified builds. pub(crate) async fn open_verified_bio_store<'a>( @@ -32,7 +23,7 @@ pub(crate) async fn open_verified_bio_store<'a>( ) -> Result>> { let store = match ProjectStoreSession::open(engine).await { Ok(store) => store, - Err(err) if is_unsupported_bio_store(&err) => return Ok(None), + Err(err) if is_store_write_unavailable(&err) => return Ok(None), Err(err) => return Err(err), }; anyhow::ensure!( @@ -44,7 +35,7 @@ pub(crate) async fn open_verified_bio_store<'a>( .await { Ok(_) => Ok(Some(store)), - Err(err) if is_unsupported_bio_store(&err) => Ok(None), + Err(err) if is_store_write_unavailable(&err) => Ok(None), Err(err) => Err(err), } } @@ -97,11 +88,14 @@ pub(crate) async fn update_character_form_fields( .await?; } for _ in 0..25 { - if res.get("error").and_then(Value::as_str) != Some("store_loading") { + let err = res.get("error").and_then(Value::as_str); + if !matches!(err, Some("store_loading" | "store_not_bound")) { break; } - tokio::time::sleep(Duration::from_millis(200)).await; - let _ = ensure_flow_store(engine).await; + if err == Some("store_loading") { + tokio::time::sleep(Duration::from_millis(200)).await; + } + ensure_flow_store(engine).await?; res = engine .call_flow_async("characterOp", json!([payload.clone()])) .await?; @@ -126,6 +120,23 @@ pub(crate) async fn update_character_form_fields( Ok(()) } +/// Checks the project snapshot to confirm that `bio` saved on character `char_id`. +pub(crate) async fn confirm_character_bio_saved( + engine: &ChromeEngine, + char_id: &str, + bio: &str, +) -> Result<()> { + let refreshed = list_assets_with_project(engine).await?; + let confirmed = refreshed.assets.iter().any(|asset| { + asset.id == char_id && asset.personality_notes.as_deref().map(str::trim) == Some(bio.trim()) + }); + anyhow::ensure!( + confirmed, + "Flow did not persist personality notes for character '{char_id}'" + ); + Ok(()) +} + /// Edits character personality notes through `flow-character-form` when direct store updates are unavailable. async fn edit_character_bio_in_form( engine: &ChromeEngine, @@ -155,11 +166,12 @@ async fn edit_character_bio_in_form( update_character_form_fields(engine, Some(&pid), &target.id, None, Some(bio)).await; exit_character_editor(engine, Some(&pid)).await; update_res?; + confirm_character_bio_saved(engine, &target.id, bio).await?; db.upsert_character( target.id.clone(), Some(pid), target.name.clone(), - Some(bio.to_owned()), + Some(bio.trim().to_owned()), None, None, ) @@ -191,11 +203,11 @@ pub(crate) async fn edit_character_bio( set_character_bio(&store, &target.id, bio).await?; Some((target, store.project_id().to_owned())) } - Err(err) if is_unsupported_bio_store(&err) => None, + Err(err) if is_store_write_unavailable(&err) => None, Err(err) => return Err(err), } } - Err(err) if is_unsupported_bio_store(&err) => None, + Err(err) if is_store_write_unavailable(&err) => None, Err(err) => return Err(err), }; if let Some((target, project_id)) = direct_target { diff --git a/src/characters.rs b/src/characters.rs index 95fd45f..3c45713 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -12,7 +12,8 @@ use tokio::time::{Duration, Instant}; use crate::assets::{FlowAsset, list_assets_with_project, match_asset, trash_asset}; use crate::character_bio::{ - edit_character_bio, open_verified_bio_store, set_character_bio, update_character_form_fields, + confirm_character_bio_saved, edit_character_bio, open_verified_bio_store, set_character_bio, + update_character_form_fields, }; use crate::db::FlowDb; use crate::download::download_resolved_asset; @@ -427,6 +428,7 @@ pub(crate) async fn create_or_update_character_job( None }; let editor_opened; + let mut form_bio_to_confirm: Option = None; let mut net_rx = if look_prompt.is_some() || has_refs { Some(engine.subscribe_network().await?) } else { @@ -541,6 +543,9 @@ pub(crate) async fn create_or_update_character_job( } else { effective_bio.as_deref() }; + if let Some(bio) = form_bio { + form_bio_to_confirm = Some(bio.to_owned()); + } editor_opened = true; update_character_form_fields( engine, @@ -759,6 +764,9 @@ pub(crate) async fn create_or_update_character_job( if editor_opened { exit_character_editor(engine, project_id.as_deref()).await; } + if let Some(ref bio) = form_bio_to_confirm { + confirm_character_bio_saved(engine, &char_id, bio).await?; + } if let Some(err) = upload_err.or(look_err) { if !is_edit { diff --git a/src/collections.rs b/src/collections.rs index 8d98866..e9626bc 100644 --- a/src/collections.rs +++ b/src/collections.rs @@ -176,6 +176,15 @@ fn move_ids(ids: Option>, action: &str) -> Result> { }) } +/// Extracts the collection summaries from a project store snapshot. +pub(crate) fn snapshot_collections(snap: &mut Value) -> Result> { + Ok(serde_json::from_value( + snap.get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| json!([])), + )?) +} + /// Dispatches the six actions of `flow_collections`. pub(crate) async fn handle_collections( engine: &ChromeEngine, @@ -183,11 +192,7 @@ pub(crate) async fn handle_collections( ) -> Result { if req.action == "list" { let mut snap = crate::project::read_snapshot(engine).await?; - let collections: Vec = serde_json::from_value( - snap.get_mut("collections") - .map(Value::take) - .unwrap_or_else(|| json!([])), - )?; + let collections = snapshot_collections(&mut snap)?; return Ok(json!({ "collections": collections })); } let session = ProjectStoreSession::open(engine).await?; diff --git a/src/project.rs b/src/project.rs index 04e8908..8f43e42 100644 --- a/src/project.rs +++ b/src/project.rs @@ -380,6 +380,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { if status["ok"].as_bool() == Some(true) { return Ok(()); } + if status_err == Some("unsupported_front_end") { + anyhow::bail!( + "Google Flow front end build is not supported (unsupported_front_end).{}", + build_suffix(engine).await + ); + } if status_err == Some("store_loading") { tokio::time::sleep(Duration::from_millis(250)).await; continue; @@ -389,6 +395,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { let discovery = store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?; let discovery_err = discovery.get("error").and_then(Value::as_str); + if discovery_err == Some("unsupported_front_end") { + anyhow::bail!( + "Google Flow front end build is not supported (unsupported_front_end).{}", + build_suffix(engine).await + ); + } input_pending |= discovery_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); if discovery["bound"].as_bool() == Some(true) { tokio::time::sleep(Duration::from_millis(250)).await; @@ -450,13 +462,20 @@ async fn build_suffix(engine: &ChromeEngine) -> String { pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { if engine.has_page().await && let Ok(snap) = engine.call_flow_js("readStoreSnapshot", json!([])).await - && snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { - return Ok(snap); + if snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { + return Ok(snap); + } + if snap.get("error").and_then(Value::as_str) == Some("unsupported_front_end") { + anyhow::bail!( + "Google Flow front end build is not supported (unsupported_front_end).{}", + build_suffix(engine).await + ); + } } + ensure_flow_store(engine).await?; let mut last_err = "store_not_bound".to_string(); - for _ in 0..25 { - ensure_flow_store(engine).await?; + for attempt in 0..25 { let snap = store_loading_result(engine.call_flow_js("readStoreSnapshot", json!([])).await)?; if snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { return Ok(snap); @@ -466,6 +485,21 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { .and_then(|v| v.as_str()) .unwrap_or("unknown") .to_string(); + if last_err == "unsupported_front_end" { + anyhow::bail!( + "Google Flow front end build is not supported (unsupported_front_end).{}", + build_suffix(engine).await + ); + } + if attempt < 2 + && matches!( + last_err.as_str(), + "store_not_bound" | "route_changed" | "project_mismatch" + ) + { + ensure_flow_store(engine).await?; + continue; + } let delay_ms = if matches!( last_err.as_str(), "store_loading" | ANGULAR_REQUIRED_INPUT_ERROR diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..17f4cde 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -41,7 +41,17 @@ impl<'a> ProjectStoreSession<'a> { let err = status.get("error").and_then(Value::as_str); if err == Some("collection_store_not_bound") && !dom_probed { dom_probed = true; - let _ = engine.call_flow_async("discoverStore", json!([])).await; + if let Ok(discovery) = engine.call_flow_async("discoverStore", json!([])).await + && discovery.get("error").and_then(Value::as_str) + == Some("unsupported_front_end") + { + status = json!({ + "ok": false, + "error": "unsupported_front_end", + "build": discovery.get("build").cloned().unwrap_or(Value::Null), + }); + break; + } status = engine .call_flow_js("projectStoreStatus", json!([project_id])) .await?; @@ -96,6 +106,16 @@ impl<'a> ProjectStoreSession<'a> { } } +/// Returns true when `err` shows that direct store writes cannot run before sending a request. +pub(crate) fn is_store_write_unavailable(err: &anyhow::Error) -> bool { + let msg = format!("{err:#}"); + !msg.contains("outcome_unknown") + && (msg.contains("unsupported_front_end") + || msg.contains("collection_store_not_bound") + || msg.contains("ambiguous_collection_store") + || msg.contains("project_upload_page_not_ready")) +} + /// Prepares the direct store for a status check without changing the page. pub(crate) async fn prepare_project_store_status(engine: &ChromeEngine, project_id: &str) { if let Some(_guard) = engine.try_lock_project_store() { diff --git a/src/tile_menu.rs b/src/tile_menu.rs index 8cc64d7..d2debf9 100644 --- a/src/tile_menu.rs +++ b/src/tile_menu.rs @@ -214,13 +214,11 @@ async fn trash_in_view(engine: &ChromeEngine, id: &str) -> Result { if wait_trashed(engine, id, 6).await { return Ok(true); } - let confirm = page_op(engine, json!({ "action": "confirm_dialog" })).await?; + let confirm = tile_dom_op(engine, "confirm_dialog", id).await?; if is_ok(&confirm) && let Some(point) = confirm.get("point") - && engine.click_point(point).await? - && wait_trashed(engine, id, 36).await { - return Ok(true); + let _ = engine.click_point(point).await?; } if wait_trashed(engine, id, 34).await { return Ok(true); diff --git a/src/upload.rs b/src/upload.rs index 5548320..c9feae8 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -13,7 +13,7 @@ use anyhow::{Context, Result}; use serde_json::{Value, json}; use crate::engine::{ChromeEngine, validate_local_files}; -use crate::project_store::ProjectStoreSession; +use crate::project_store::{ProjectStoreSession, is_store_write_unavailable}; /// Menu button that adds ingredients to the prompt box. pub(crate) const PROMPT_INGREDIENTS_MENU: &str = "Add ingredients to the prompt box"; @@ -53,16 +53,6 @@ fn has_video_file(files: &[String]) -> bool { }) } -/// Returns true when a direct upload error occurred before any upload RPC was sent. -fn should_fallback_to_menu_upload(err: &anyhow::Error) -> bool { - let msg = format!("{err:#}"); - !msg.contains("outcome_unknown") - && (msg.contains("unsupported_front_end") - || msg.contains("collection_store_not_bound") - || msg.contains("ambiguous_collection_store") - || msg.contains("project_upload_page_not_ready")) -} - /// Uploads files to the pinned project and falls back to the workspace upload menu on unverified builds. pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { crate::project::ensure_project_workspace_root(engine).await?; @@ -84,11 +74,11 @@ pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String] .await { Ok(res) => return Ok(res), - Err(err) if !should_fallback_to_menu_upload(&err) => return Err(err), + Err(err) if !is_store_write_unavailable(&err) => return Err(err), Err(_) => {} } } - Err(err) if !should_fallback_to_menu_upload(&err) => return Err(err), + Err(err) if !is_store_write_unavailable(&err) => return Err(err), Err(_) => {} } upload_project_files_through_menu(engine, files).await diff --git a/ts/angular.ts b/ts/angular.ts index 6ce0ad7..8ae27e0 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -33,6 +33,11 @@ export function readOwn(obj: unknown, key: string): unknown { } } +/** Returns true when `fn` carries an Angular signal symbol. */ +export function isAngularSignal(fn: Function): boolean { + return Object.getOwnPropertySymbols(fn).length > 0; +} + /** Returns `lv` if `lv` is a live Angular LView whose host node remains connected. */ export function isLiveLView(lv: unknown): lv is NgLView { return Array.isArray(lv) && (!(lv[0] instanceof Node) || lv[0].isConnected); @@ -83,12 +88,17 @@ export function resolveLView(elOrCtx: unknown): NgLView | null { ? runtimeState.ngLViewMap.get(raw) || null : null; } - if (raw && typeof raw === "object") { + if (raw && typeof raw === "object" && !(raw instanceof Node)) { const lView = readOwn(raw, "lView"); - if (Array.isArray(lView)) return lView; + if (isLiveLView(lView)) return lView; for (const contextField of lContextViewFields()) { const candidateView = readOwn(raw, contextField); - if (Array.isArray(candidateView)) return candidateView; + if (isLiveLView(candidateView)) return candidateView; + } + const lViewId = readOwn(raw, "lViewId"); + if (typeof lViewId === "number" && runtimeState.ngLViewMap instanceof Map) { + const mapped = runtimeState.ngLViewMap.get(lViewId); + return isLiveLView(mapped) ? mapped : null; } return null; } @@ -440,8 +450,7 @@ export async function createScene( workflowIds: string[], ): Promise<{ ok: boolean; id?: string; error?: string }> { const before = new Set(sceneIds(getMap())); - const build = frontendBuild(readBuildLabel()); - const resultField = (build ? build.projectStore.mutations?.sceneCreated : undefined) ?? "t6a"; + const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa"; let confirmedId: string | undefined; let failure: string | undefined; const completion = { @@ -460,7 +469,7 @@ export async function createScene( De: completion, ve: completion, })).then((response) => { - completion.resolve(readOwn(response, resultField) ?? readOwn(response, "VWa")); + completion.resolve(readOwn(response, resultField)); }, completion.reject); while (performance.now() < deadline) { diff --git a/ts/character_extra.ts b/ts/character_extra.ts index f771c0b..8c3b1f1 100644 --- a/ts/character_extra.ts +++ b/ts/character_extra.ts @@ -16,7 +16,6 @@ import { import { frontendBuild, readBuildLabel, - voiceConfirmationFormat, type VoiceConfirmationFormat, } from "./frontend_builds"; import type { CharacterExtraOpRequest } from "./types"; @@ -322,12 +321,11 @@ async function applyVoice( const custom = Boolean(sample || performance); if (custom && sample.length > 120) return { ok: false, error: "voice_sample_over_120_characters" }; - const format = voiceConfirmationFormat(); - const strictConfirm = Boolean(frontendBuild(readBuildLabel())?.voiceConfirmation); + const format = frontendBuild(readBuildLabel())?.voiceConfirmation; let pane = format ? await withLViewMapCapture(openDialog) : await openDialog(); if (!pane) return { ok: false, error: "voice_dialog_not_available" }; const confirm = format && bindVoiceConfirmation(format); - if (strictConfirm && !confirm) { + if (format && !confirm) { await dismissOverlay(); return { ok: false, error: "voice_confirmation_unavailable" }; } diff --git a/ts/character_media.ts b/ts/character_media.ts index 0a7c200..55c283d 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -223,8 +223,9 @@ export async function characterMediaOp( let footerBusy = false; const footerEl = document.querySelector("flow-edit-character-footer"); const footerLv = footerEl ? resolveLView(footerEl) : null; - if (Array.isArray(footerLv)) { - const { footerBusy: footerBusyKey } = characterPreviewFormat(); + const previewFmt = characterPreviewFormat(); + if (previewFmt && Array.isArray(footerLv)) { + const { footerBusy: footerBusyKey } = previewFmt; for (const cand of footerLv) { try { const busyFn = readOwn(cand, footerBusyKey); @@ -468,8 +469,9 @@ export async function characterMediaOp( overlayRoot.querySelector("flow-add-menu-popover-content") || document.querySelector("flow-add-menu-popover-content"); const popLv = popEl ? resolveLView(popEl) : null; - if (Array.isArray(popLv)) { - const { pickerAssets, pickerSelect } = characterPreviewFormat(); + const previewFmt = characterPreviewFormat(); + if (previewFmt && Array.isArray(popLv)) { + const { pickerAssets, pickerSelect } = previewFmt; for (const cand of popLv) { const listFn = readOwn(cand, pickerAssets); const pickFn = readOwn(cand, pickerSelect); diff --git a/ts/character_ops.ts b/ts/character_ops.ts index 5184cde..c63ea51 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -4,14 +4,80 @@ // Open, finish, create, and update profile fields for Google Flow characters. import { buildProjectUrl, findRouter, navigateSpa, readOwn } from "./angular"; +import { characterPersonalityNotes } from "./character_bio"; import { clickButtonByRegex, delay, isVisibleEnabled, setNativeValue } from "./dom"; import { activeProjectStoreFormat, characterCreateFormat, readBuildLabel, } from "./frontend_builds"; +import { currentProjectStore, refreshProjectStore } from "./project_store"; import { clearStore, runtimeState } from "./state"; -import type { CharacterOpRequest } from "./types"; +import type { CharacterOpRequest, FlowTile } from "./types"; + +/** Selector for the character name input inside `flow-character-form`. */ +const CHARACTER_NAME_INPUT_SELECTOR = + 'flow-character-form input[aria-label="Character name"], input[aria-label="Character name"], flow-character-form input.name-input'; + +/** Selector for the character personality textarea inside `flow-character-form`. */ +const CHARACTER_BIO_INPUT_SELECTOR = + 'flow-character-form textarea[aria-label="Character personality"], textarea[aria-label="Character personality"], flow-character-form textarea.personality-textarea'; + +/** Returns true when `el` is an enabled, non-inert text control. */ +function isEditableField( + el: Element | null, +): el is HTMLInputElement | HTMLTextAreaElement { + return ( + (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && + !el.disabled && + !el.readOnly && + !el.closest("[inert]") + ); +} + +/** Reads normalized personality notes from `tile`, or null when unreadable. */ +function readCharacterTileBio(tile: FlowTile | undefined): string | null { + if (!tile) return null; + const fromEntity = characterPersonalityNotes(tile); + if (fromEntity !== null) return fromEntity; + return typeof tile.personalityNotes === "string" ? tile.personalityNotes : null; +} + +/** Polls the bound project store after form debounce until `matches` holds across two checks. */ +async function confirmCharacterStoreReadback( + projectId: string | null, + charId: string, + matches: (tile: FlowTile | undefined) => boolean, +): Promise { + await delay(550); + for (let i = 0; i < 30; i += 1) { + const busy = Boolean( + document.querySelector( + 'flow-character-form [aria-busy="true"], flow-character-edit-page [aria-busy="true"]', + ), + ); + if (!busy && i > 0 && i % 3 === 0 && projectId) { + const liveStore = currentProjectStore(projectId); + if (liveStore) { + await refreshProjectStore(liveStore).catch(() => null); + } + } + const tile = runtimeState.store?.getTileMap?.()?.get(charId); + if (!busy && matches(tile)) { + await delay(300); + if (projectId) { + const liveStore = currentProjectStore(projectId); + if (liveStore) { + await refreshProjectStore(liveStore).catch(() => null); + } + } + const settled = runtimeState.store?.getTileMap?.()?.get(charId); + if (matches(settled)) return true; + } + await delay(250); + } + return false; +} /** Creates, opens, updates, or finishes character entity editing in Google Flow. */ export async function characterOp(req: CharacterOpRequest): Promise { @@ -141,6 +207,9 @@ export async function characterOp(req: CharacterOpRequest): Promise { ); const format = characterCreateFormat(); + if (!format) { + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; + } const completion = { resolve: resolveDe, reject: rejectDe }; const payload: Record = { type: "create_entity", @@ -248,14 +317,30 @@ export async function characterOp(req: CharacterOpRequest): Promise { } return { ok: false, error: "not_in_project_route" }; } + const needsStoreConfirm = Boolean( + (req?.bio !== undefined && req?.bio !== null) || + (req?.name && !activeProjectStoreFormat()), + ); + if (needsStoreConfirm && !activeHelper) { + return { ok: false, error: "store_not_bound" }; + } if (activeHelper && !activeHelper.isReady()) { return { ok: false, error: "store_loading" }; } for (let i = 0; i < 50; i++) { + const nameReady = + !req?.name || + isEditableField(document.querySelector(CHARACTER_NAME_INPUT_SELECTOR)); + const bioReady = + req?.bio === undefined || + req?.bio === null || + isEditableField(document.querySelector(CHARACTER_BIO_INPUT_SELECTOR)); if ( + nameReady && + bioReady && document.querySelector( - 'flow-character-form, flow-character-image-preview, input[aria-label="Character name"], textarea[aria-label="Character personality"]', + `flow-character-form, flow-character-image-preview, ${CHARACTER_NAME_INPUT_SELECTOR}, ${CHARACTER_BIO_INPUT_SELECTOR}`, ) ) { break; @@ -266,10 +351,8 @@ export async function characterOp(req: CharacterOpRequest): Promise { const applied: string[] = []; if (req?.name) { const nameStr = String(req.name).trim(); - const nameInput = document.querySelector( - 'input[aria-label="Character name"], flow-character-form input[type="text"], flow-character-form input:not([type])', - ); - if (nameInput instanceof HTMLInputElement) { + const nameInput = document.querySelector(CHARACTER_NAME_INPUT_SELECTOR); + if (nameInput instanceof HTMLInputElement && isEditableField(nameInput)) { nameInput.focus(); setNativeValue(nameInput, nameStr, true); nameInput.dispatchEvent(new Event("blur", { bubbles: true })); @@ -288,25 +371,42 @@ export async function characterOp(req: CharacterOpRequest): Promise { } } else if (!applied.includes("ui_name")) { return { ok: false, error: "character_name_input_not_found" }; + } else { + const confirmed = await confirmCharacterStoreReadback( + currentPid, + charId, + (tile) => String(tile?.displayName ?? "").trim() === nameStr, + ); + if (!confirmed) { + return { ok: false, error: "character_name_not_confirmed" }; + } } } if (req?.bio !== undefined && req?.bio !== null) { const bioStr = String(req.bio); - const bioInput = document.querySelector( - 'textarea[aria-label="Character personality"], flow-character-form textarea, input[aria-label="Character personality"]', - ); - if ( - bioInput instanceof HTMLTextAreaElement || - bioInput instanceof HTMLInputElement - ) { + const expectedBio = bioStr.trim(); + const bioInput = document.querySelector(CHARACTER_BIO_INPUT_SELECTOR); + if (isEditableField(bioInput)) { bioInput.focus(); setNativeValue(bioInput, bioStr, true); bioInput.dispatchEvent(new Event("blur", { bubbles: true })); await delay(200); - if ((bioInput.value ?? "") !== bioStr) { + const inputVal = bioInput.value ?? ""; + if (inputVal !== bioStr && inputVal.trim() !== expectedBio) { return { ok: false, error: "character_bio_input_mismatch" }; } + const confirmed = await confirmCharacterStoreReadback( + currentPid, + charId, + (tile) => { + const notes = readCharacterTileBio(tile); + return notes !== null && notes.trim() === expectedBio; + }, + ); + if (!confirmed) { + return { ok: false, error: "character_bio_not_confirmed" }; + } applied.push("ui_bio"); } else { return { ok: false, error: "character_bio_input_not_found" }; diff --git a/ts/character_preview.ts b/ts/character_preview.ts index ca8c785..0425677 100644 --- a/ts/character_preview.ts +++ b/ts/character_preview.ts @@ -68,6 +68,7 @@ function callPanel(panel: object, name: string): unknown { /** Finds the preview panel in a live Angular view and binds its methods. */ export function getCharacterPreviewInstance(): CharacterPreview | null { const format = characterPreviewFormat(); + if (!format) return null; const roots = document.querySelectorAll( "flow-character-preview-panel, flow-character-image-preview", ); diff --git a/ts/character_voices.ts b/ts/character_voices.ts index cdeeb86..af2771a 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -55,11 +55,13 @@ export async function characterVoiceOp( const format = characterVoiceFormat(); function isFormBusy(comp: CharacterFormComponent | null): boolean { + if (!format) return false; const busyFn = readOwn(comp, format.busy); return typeof busyFn === "function" && Boolean(busyFn.call(comp)); } function getCharacterFormInstance(): CharacterFormComponent | null { + if (!format) return null; const form = document.querySelector("flow-character-form"); if (!form) return null; const isDisposed = (cand: AngularLifecycleHandle): boolean => { @@ -216,7 +218,7 @@ export async function characterVoiceOp( function readVoiceMap( comp: CharacterFormComponent | null, ): Map | null { - if (!comp) return null; + if (!comp || !format) return null; try { const mapFn = readOwn(comp, format.voiceMap); const voiceMap = typeof mapFn === "function" ? mapFn.call(comp) : null; @@ -272,6 +274,7 @@ export async function characterVoiceOp( comp: CharacterFormComponent | null; voices: NormalizedVoiceItem[]; }> { + if (!format) return { comp: null, voices: [] }; await waitForVoiceHost(40); let lastComp: CharacterFormComponent | null = null; for (let i = 0; i < maxTicks; i++) { @@ -485,15 +488,21 @@ export async function characterVoiceOp( }); const matchedComp = findVoice(compVoices, true) || findVoice(compVoices, false); - const recordSetter = readOwn(comp, format.selectedRecord) as - | { set?: (raw: RawVoiceEntry) => void } - | undefined; - const idSetter = readOwn(comp, format.selectedVoice) as - | { set?: (id: string) => void } - | undefined; - const changeEmitter = readOwn(comp, format.changeEmitter) as - | { emit?: (id: string) => void } - | undefined; + const recordSetter = format + ? (readOwn(comp, format.selectedRecord) as + | { set?: (raw: RawVoiceEntry) => void } + | undefined) + : undefined; + const idSetter = format + ? (readOwn(comp, format.selectedVoice) as + | { set?: (id: string) => void } + | undefined) + : undefined; + const changeEmitter = format + ? (readOwn(comp, format.changeEmitter) as + | { emit?: (id: string) => void } + | undefined) + : undefined; if ( comp && matchedComp?._raw && diff --git a/ts/discover_store.ts b/ts/discover_store.ts index f61c161..3708625 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -3,12 +3,14 @@ // Capture Angular Ivy views from the DOM as a fallback for verified store binding. -import { isNgLViewMap, resolveLView, withLViewMapCapture } from "./angular"; +import { isNgLViewMap, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe } from "./dom"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { clearProjectStore, currentProjectStore, findProjectStoreInView, + hasNoCascadedStoreClasses, installProjectStore, isCurrent, projectInRoute, @@ -125,6 +127,15 @@ export async function discoverStore(): Promise { clearProjectStore(); return { bound: false, newlyDiscovered: false, error: "not_in_project" }; } + if (hasNoCascadedStoreClasses()) { + clearProjectStore(); + return { + bound: false, + newlyDiscovered: false, + error: "unsupported_front_end", + build: readBuildLabel(), + }; + } const existing = currentProjectStore(projectId); if (existing) { @@ -182,5 +193,26 @@ export async function discoverStore(): Promise { return { bound: true, newlyDiscovered: true }; } } + if ( + !activeProjectStoreFormat() && + Boolean(readOwn(window, "default_AiSandboxAngularFrontend")) && + !document.querySelector("flow-loading-page") && + (allMaps.size > 0 || + Boolean( + document.querySelector( + "flow-project-shell, flow-project-page, flow-character-edit-page, flow-scene-builder, flow-editor-page", + ), + ) || + Array.from(document.querySelectorAll("*")) + .slice(0, 120) + .some((el) => "__ngContext__" in el)) + ) { + return { + bound: false, + newlyDiscovered: false, + error: "unsupported_front_end", + build: readBuildLabel(), + }; + } return { bound: false, newlyDiscovered: false }; } diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 086bb00..94b646c 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -8,6 +8,7 @@ import type { AgentExport } from "./agent_protocol"; import type { AgentWireFormat } from "./agent_wire"; import type { AgentSettingsExport } from "./agent_settings_protocol"; import type { MediaUploadExport } from "./project_upload"; +import { runtimeState } from "./state"; /** Field names for the collection write requests of one build. */ export interface CollectionWriteFormat { @@ -831,33 +832,6 @@ const LEGACY_CHARACTER_CREATE: CharacterCreateFormat = { /** Editable project title format of earlier builds. */ const LEGACY_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "tJa", stateSignal: "state" }; -/** Character preview format of build `20261120.00_p0` used as the default fallback. */ -const NOVEMBER_20_CHARACTER_PREVIEW: CharacterPreviewFormat = { - lifecycle: "Ba", upload: "NV", marker: "hh", portrait: "ka", body: "ma", - source: "Gza", busy: "mB", footerBusy: "Zh", pickerAssets: "xZ", pickerSelect: "Qda", -}; - -/** Character voice form format of build `20261120.00_p0` used as the default fallback. */ -const NOVEMBER_20_CHARACTER_VOICE: CharacterVoiceFormat = { - lifecycle: "Ba", destroyed: "Va", voiceMap: "o_", selectedVoice: "A3", - selectedRecord: "Pua", changeEmitter: "Pea", busy: "yb", emptyMap: true, -}; - -/** Character creation format of build `20261120.00_p0` used as the default fallback. */ -const NOVEMBER_20_CHARACTER_CREATE: CharacterCreateFormat = { - lifecycle: "Ba", destroyed: "Va", entityKinds: ["pM"], - collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], -}; - -/** Editable project title format of build `20261120.00_p0` used as the default fallback. */ -const NOVEMBER_20_PROJECT_TITLE: ProjectTitleFormat = { saveEmitter: "HSa", stateSignal: "state" }; - -/** Voice confirmation format of build `20261120.00_p0` used as the default fallback. */ -const NOVEMBER_20_VOICE_CONFIRMATION: VoiceConfirmationFormat = { - editor: "qu", entityQuery: "ma", savedVoice: "Xjb", selectedVoice: "A3", - previewSaved: "MK", pickerSelection: "Qn", -}; - /** Request formats by exact build label. Include only verified operations. */ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261117.10_p0", { @@ -902,11 +876,23 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261120.00_p0", { projectStore: NOVEMBER_20_STORE, snapshot: NOVEMBER_20_SNAPSHOT, - voiceConfirmation: NOVEMBER_20_VOICE_CONFIRMATION, - characterPreview: NOVEMBER_20_CHARACTER_PREVIEW, - characterVoice: NOVEMBER_20_CHARACTER_VOICE, - characterCreate: NOVEMBER_20_CHARACTER_CREATE, - projectTitle: NOVEMBER_20_PROJECT_TITLE, + voiceConfirmation: { + editor: "qu", entityQuery: "ma", savedVoice: "Xjb", selectedVoice: "A3", + previewSaved: "MK", pickerSelection: "Qn", + }, + characterPreview: { + lifecycle: "Ba", upload: "NV", marker: "hh", portrait: "ka", body: "ma", + source: "Gza", busy: "mB", footerBusy: "Zh", pickerAssets: "xZ", pickerSelect: "Qda", + }, + characterVoice: { + lifecycle: "Ba", destroyed: "Va", voiceMap: "o_", selectedVoice: "A3", + selectedRecord: "Pua", changeEmitter: "Pea", busy: "yb", emptyMap: true, + }, + characterCreate: { + lifecycle: "Ba", destroyed: "Va", entityKinds: ["pM"], + collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], + }, + projectTitle: { saveEmitter: "HSa", stateSignal: "state" }, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -924,9 +910,12 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ }], ]); +/** Verified builds ordered from newest to oldest for read-only store discovery. */ +const CASCADED_BUILDS: readonly FrontendBuild[] = Array.from(VERIFIED_BUILDS.values()).reverse(); + /** Verified project store formats ordered from newest to oldest for read-only discovery. */ const CASCADED_PROJECT_STORES: readonly ProjectStoreFormat[] = Array.from( - new Set(Array.from(VERIFIED_BUILDS.values(), (b) => b.projectStore).reverse()), + new Set(CASCADED_BUILDS.map((b) => b.projectStore)), ); /** Returns the exact label published by the active page. */ @@ -940,6 +929,17 @@ export function frontendBuild(label: string | null): FrontendBuild | undefined { return label === null ? undefined : VERIFIED_BUILDS.get(label); } +/** Returns the verified build that owns `format`, or undefined. */ +function frontendBuildForStore(format: ProjectStoreFormat | null | undefined): FrontendBuild | undefined { + if (!format) return undefined; + return CASCADED_BUILDS.find((build) => build.projectStore === format); +} + +/** Returns the active verified build, or the build paired with the bound read-only store. */ +function boundOrActiveBuild(): FrontendBuild | undefined { + return frontendBuild(readBuildLabel()) ?? frontendBuildForStore(runtimeState.storeFormat); +} + /** Returns the verified project store layout of the active build, or undefined. */ export function activeProjectStoreFormat(): ProjectStoreFormat | undefined { return frontendBuild(readBuildLabel())?.projectStore; @@ -951,24 +951,22 @@ export function projectStoreFormats(): readonly ProjectStoreFormat[] { return verified ? [verified] : CASCADED_PROJECT_STORES; } -/** Returns candidate Angular `LContext` view property names, defaulting to `20261120.00_p0` first. */ +/** Returns candidate Angular `LContext` view property names for the active or cascaded store. */ export function lContextViewFields(): readonly string[] { - const verified = activeProjectStoreFormat(); - if (verified) return [verified.lContextView]; - return Array.from( - new Set([NOVEMBER_20_STORE.lContextView, ...CASCADED_PROJECT_STORES.map((s) => s.lContextView)]), - ); + const paired = boundOrActiveBuild()?.projectStore; + if (paired) return [paired.lContextView]; + return Array.from(new Set(CASCADED_PROJECT_STORES.map((s) => s.lContextView))); } -/** Returns the scene clip and history field names, defaulting to `20261120.00_p0`. */ -export function sceneTileFormat(): NonNullable { - return activeProjectStoreFormat()?.scene ?? { clips: "Uc", history: "Cg" }; +/** Returns the scene clip and history field names paired with the active or bound store. */ +export function sceneTileFormat(): SceneTileFormat | undefined { + return boundOrActiveBuild()?.projectStore.scene; } /** Adds the native fields used by the verified project store mutator. */ export function withMutationAliases(payload: Record): Record { const build = frontendBuild(readBuildLabel()); - const format = build ? build.projectStore.mutations : NOVEMBER_20_STORE.mutations; + const format = build?.projectStore.mutations; if (payload.type === "single_tile" && payload.Ve && typeof payload.Ve === "object") { const change = payload.Ve as Record; if (format) { @@ -999,38 +997,27 @@ export function withMutationAliases(payload: Record): Record): StoreProbeCheck { }; } +/** Known uppercase tile types when `snapshotFormat()?.tileTypes` is absent. */ +const KNOWN_TILE_TYPES = new Set([ + "COLLECTION", + "IMAGE", + "VIDEO", + "SCENE", + "CHARACTER", + "TEXT_TILE", + "CUSTOM", + "FAILED_ASSET", + "AUDIO", + "MUSIC", + "VOICE", +]); + +/** Returns true when every inspected tile in an unverified store has readable fields. */ +export function hasReadableCascadedTiles(tiles: Map): boolean { + if (!tileLayout(tiles.values()).ok) return false; + const snapFmt = snapshotFormat(); + const sceneFmt = sceneTileFormat(); + let seen = 0; + for (const raw of tiles.values()) { + if (++seen > 200) break; + const kind = String(raw?.type ?? "").toUpperCase(); + if (!kind) return false; + if (snapFmt) { + const { tileTypes } = snapFmt; + const recognized = + kind === tileTypes.collection || + tileTypes.assets.includes(kind) || + tileTypes.ignored.includes(kind) || + KNOWN_TILE_TYPES.has(kind); + if (!recognized) return false; + } else if (!KNOWN_TILE_TYPES.has(kind)) { + return false; + } + if (isTrashedTile(raw) || raw.isPending === true) continue; + if (kind === "IMAGE" || kind === "VIDEO") { + const mediaKeys = snapFmt ? [snapFmt.media.container, "Fb"] : ["Fb", "Eb"]; + const hasContainer = mediaKeys.some((key) => { + const value = readOwn(raw, key); + return Boolean(value && typeof value === "object"); + }); + if (!hasContainer) return false; + } + if (kind === "CHARACTER") { + if (typeof raw.displayName !== "string") return false; + if ( + characterPersonalityNotes(raw) === null && + typeof raw.personalityNotes !== "string" + ) { + return false; + } + } + if (kind === "COLLECTION" && typeof raw.displayName !== "string") { + return false; + } + if (kind === "SCENE") { + if (typeof raw.displayName !== "string") return false; + const hasClips = sceneFmt + ? Array.isArray(readOwn(raw, sceneFmt.clips)) || Array.isArray(raw.Oc) + : Array.isArray(raw.Oc); + if (!hasClips) return false; + } + } + return true; +} + /** Checks the bound store and tile layout used by asset trash. */ function assetTrashChecks(tiles: Map | null | undefined): StoreProbeCheck[] { const rawStore = runtimeState.store; diff --git a/ts/project_store.ts b/ts/project_store.ts index 1441b06..beba964 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -3,7 +3,7 @@ // Bind, validate, read, and mutate the active project store from verified build formats. -import { isNgLViewMap, readOwn } from "./angular"; +import { isAngularSignal, isNgLViewMap, readOwn } from "./angular"; import { delay } from "./dom"; import { activeProjectStoreFormat, @@ -12,6 +12,7 @@ import { withMutationAliases, } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; +import { hasReadableCascadedTiles } from "./frontend_compatibility"; import { clearStore, runtimeState } from "./state"; import type { FlowStoreHandle, FlowTile, NgLView, StoreProbeCheck } from "./types"; @@ -170,11 +171,6 @@ export function projectStore(projectId: string, expectedSession: string): Projec return active && session === expectedSession ? active : null; } -/** Returns true when `fn` carries an Angular signal symbol. */ -function isAngularSignal(fn: Function): boolean { - return Object.getOwnPropertySymbols(fn).length > 0; -} - /** Resolves an async promise runner from the verified `mutator` field on the store. */ function resolveAsyncMutator( owner: object, @@ -313,9 +309,19 @@ export function installProjectStore(store: ProjectStore, views?: Map { const frontEnd = readOwn(window, "default_AiSandboxAngularFrontend"); @@ -365,15 +371,28 @@ export function findProjectStoreInView( /** Reports whether the current runtime has a bound and ready store for `projectId`. */ export function projectStoreStatus(projectId: string): ProjectStoreStatus { const build = readBuildLabel(); - if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; + if (projectInRoute() !== projectId) return { ok: false, error: "project_changed", build }; + if (hasNoCascadedStoreClasses()) { + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; + } const store = currentProjectStore(projectId); if (!store) return { ok: false, error: "collection_store_not_bound", build }; if (isProjectStorePending(store)) { return { ok: false, bound: true, error: "store_loading", build }; } - if (!readProjectStore(store)) { + const tiles = readProjectStore(store); + if (!tiles) { + if (!activeProjectStoreFormat()) { + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; + } return { ok: false, error: "collection_store_not_bound", build }; } + if (!activeProjectStoreFormat() && !hasReadableCascadedTiles(tiles)) { + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; + } session ??= crypto.randomUUID(); return { ok: true, bound: true, session, build }; } @@ -393,7 +412,11 @@ export function selectProjectStoreCandidate(candidates: ProjectStore[]): Project /** Binds one live store found in the Angular view registry using the newest matching verified layout. */ export function bindProjectStore(maps: unknown[], projectId: string): ProjectStoreStatus { const build = readBuildLabel(); - if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; + if (projectInRoute() !== projectId) return { ok: false, error: "project_changed", build }; + if (hasNoCascadedStoreClasses()) { + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; + } if (verifiedStoreLayouts().length === 0) { clearProjectStore(); return { ok: false, error: "collection_store_not_bound", build }; @@ -415,8 +438,8 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto if (!selected) { clearProjectStore(); return candidates.length > 1 - ? { ok: false, error: "ambiguous_collection_store" } - : { ok: false, error: "collection_store_not_bound" }; + ? { ok: false, error: "ambiguous_collection_store", build } + : { ok: false, error: "collection_store_not_bound", build }; } installProjectStore(selected.store, selected.views); return projectStoreStatus(projectId); diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index e4f8d52..7c9690f 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -356,9 +356,9 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { ) { await withLViewMapCapture(() => hoverProbe([host])); } - const lv = resolveLView(host); - if (Array.isArray(lv)) { - const titleFormat = projectTitleFormat(); + const titleFormat = projectTitleFormat(); + const lv = titleFormat ? resolveLView(host) : null; + if (titleFormat && Array.isArray(lv)) { for (const slot of lv) { const emitter = readOwn(slot, titleFormat.saveEmitter) as | { emit?: (v: string) => void } diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 95fea7b..88620b5 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -5,8 +5,9 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; -import { snapshotFormat } from "./frontend_builds"; -import { currentProjectStore, projectInRoute } from "./project_store"; +import { frontendBuild, readBuildLabel, snapshotFormat } from "./frontend_builds"; +import { hasReadableCascadedTiles } from "./frontend_compatibility"; +import { clearProjectStore, currentProjectStore, projectInRoute } from "./project_store"; import { sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, @@ -207,6 +208,10 @@ export function readStoreSnapshot(): StoreSnapshotResult { if (!(tileMap instanceof Map)) { return { ok: false, error: "store_not_bound" }; } + if (!frontendBuild(readBuildLabel()) && !hasReadableCascadedTiles(tileMap)) { + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build: readBuildLabel() }; + } const { assets, collections } = readStoreTiles(tileMap); const titleEl = document.querySelector( diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index 96cc986..4961905 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -7,11 +7,11 @@ import { readOwn } from "./angular"; import { sceneTileFormat } from "./frontend_builds"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; -/** Returns the clip list and history of a scene in the active build. */ +/** Returns the clip list and history of a scene in the active or bound store build. */ export function sceneContents(tile: FlowTile) { const format = sceneTileFormat(); - const clips = readOwn(tile, format.clips) ?? readOwn(tile, "Tc") ?? tile.Oc; - const history = readOwn(tile, format.history) ?? readOwn(tile, "tg") ?? tile.Yf; + const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; + const history = (format && readOwn(tile, format.history)) ?? tile.Yf; const entries: Iterable<[string, FlowMediaPayload[]]> = history instanceof Map ? history.entries() : history && typeof history === "object" ? Object.entries(history) : []; diff --git a/ts/state.ts b/ts/state.ts index 1acae21..53d3660 100644 --- a/ts/state.ts +++ b/ts/state.ts @@ -3,6 +3,7 @@ // Module-scoped browser runtime state replacing loose window globals. +import type { ProjectStoreFormat } from "./frontend_builds"; import type { CachedMediaInfo, FlowStoreHandle, @@ -20,6 +21,8 @@ export interface RuntimeState { routePath: string | null; /** Normalized store mutation and snapshot handle. */ store: FlowStoreHandle | null; + /** Verified layout of the currently bound project store. */ + storeFormat: ProjectStoreFormat | null; /** Cached resolved media URLs keyed by primary media identifier. */ mediaInfoCache: Map; /** Most recently captured prompt validation and submission state controller. */ @@ -32,6 +35,7 @@ export const runtimeState: RuntimeState = { projectId: null, routePath: null, store: null, + storeFormat: null, mediaInfoCache: new Map(), promptState: null, }; @@ -41,4 +45,5 @@ export function clearStore(): void { runtimeState.projectId = null; runtimeState.routePath = null; runtimeState.store = null; + runtimeState.storeFormat = null; } diff --git a/ts/tile_dom.ts b/ts/tile_dom.ts index 26b239b..8e7331f 100644 --- a/ts/tile_dom.ts +++ b/ts/tile_dom.ts @@ -4,6 +4,7 @@ // Locate project tiles in the page, read their state from the bound store, and dispatch page view and text control actions. import { + isAngularSignal, readOwn, resolveLView, withLViewMapCapture, @@ -87,7 +88,10 @@ function objectMatchesTile(cand: unknown, id: string, target: FlowTile): boolean return candId !== undefined && candId !== null && String(candId) === id; } -/** Returns true when one `LView` slot or component input signal binds `id`. */ +/** Verified property and Angular input signal names that hold a grid tile record. */ +const TILE_SLOT_KEYS = ["tile", "Ia", "Oa"] as const; + +/** Returns true when one `LView` slot or allow-listed Angular input signal binds `id`. */ function slotMatchesTile(slot: unknown, id: string, target: FlowTile): boolean { if (objectMatchesTile(slot, id, target)) return true; if ( @@ -101,16 +105,16 @@ function slotMatchesTile(slot: unknown, id: string, target: FlowTile): boolean { ) { return false; } - for (const key of Object.getOwnPropertyNames(slot)) { + for (const key of TILE_SLOT_KEYS) { const desc = Object.getOwnPropertyDescriptor(slot, key); if (!desc || !("value" in desc)) continue; const val: unknown = desc.value; if (objectMatchesTile(val, id, target)) return true; - if (typeof val === "function" && val.length === 0) { + if (typeof val === "function" && val.length === 0 && isAngularSignal(val)) { try { if (objectMatchesTile(val.call(slot), id, target)) return true; } catch { - // Ignore unset Angular required input signals or stateful methods. + // Ignore unset Angular required input signals. } } } @@ -262,19 +266,99 @@ async function locateTile(id: string): Promise> { return located; } -/** Finds the confirm button of an open trash dialog and returns its viewport point. */ -function confirmTrashDialog(): Record { +/** Returns true when `dialog` binds `target` in its Angular `LView` or dialog data slot. */ +function dialogBindsTile(dialog: HTMLElement, id: string, target: FlowTile): boolean { + if (containerMatchesTile(dialog, id, target)) return true; + const hosts = [ + dialog, + ...Array.from(dialog.querySelectorAll("*")).filter( + (el) => el.tagName.includes("-") || "__ngContext__" in el, + ), + ].slice(0, 24); + for (const host of hosts) { + const lv = resolveLView(host); + if (!Array.isArray(lv)) continue; + for (const slot of lv) { + const data = readOwn(slot, "data"); + if ( + objectMatchesTile(data, id, target) || + objectMatchesTile(readOwn(data, "tile"), id, target) + ) { + return true; + } + } + } + return false; +} + +/** Returns true when `dialog` describes moving single tile `target` to trash and not another tile. */ +function dialogMatchesTrashTarget( + dialog: HTMLElement, + id: string, + target: FlowTile, + tileMap: Map, +): boolean { + const dialogText = elText(dialog); + if (!/\bmove\b[\s\S]*\bto trash\b/i.test(dialogText)) return false; + const tileType = String(target.type || "IMAGE").toUpperCase(); + if (tileType !== "COLLECTION" && /\bcollection\b/i.test(dialogText)) return false; + if (/\b(?:chat|project|app|tool)\b/i.test(dialogText)) return false; + if (dialogBindsTile(dialog, id, target)) return true; + let seenOther = 0; + for (const [otherId, otherTile] of tileMap.entries()) { + if (++seenOther > 200) break; + if (otherId === id || !otherTile || isTrashedTile(otherTile)) continue; + if (dialogBindsTile(dialog, otherId, otherTile)) return false; + } + const lowerText = dialogText.toLowerCase(); + const displayName = String(target.displayName || "").trim(); + if (displayName && lowerText.includes(displayName.toLowerCase())) { + return true; + } + seenOther = 0; + for (const [otherId, otherTile] of tileMap.entries()) { + if (++seenOther > 200) break; + if (otherId === id || !otherTile || isTrashedTile(otherTile)) continue; + const otherName = String(otherTile.displayName || "").trim(); + if ( + otherName.length >= 2 && + otherName.toLowerCase() !== displayName.toLowerCase() && + lowerText.includes(otherName.toLowerCase()) + ) { + return false; + } + } + const kindWord = + tileType === "SCENE" + ? "(?:scene|item|asset)" + : tileType === "CHARACTER" + ? "(?:character|item|asset)" + : tileType === "VIDEO" + ? "(?:video|clip|media|item|asset)" + : "(?:image|media|item|asset)"; + return new RegExp(`\\bmove\\s+(?:this\\s+)?${kindWord}\\s+to\\s+trash\\b`, "i").test(dialogText); +} + +/** Finds the confirm button of an open trash dialog for tile `id` and returns its viewport point. */ +function confirmTrashDialog(id: string): Record { + const tileMap = runtimeState.store?.getTileMap?.(); + if (!(tileMap instanceof Map)) return { ok: false, error: "store_not_bound" }; + const target = tileMap.get(id); + if (!target) return { ok: false, error: "tile_not_found" }; const dialogs = Array.from( document.querySelectorAll( '[role="dialog"], [role="alertdialog"], mat-dialog-container', ), - ).filter((el) => el.getClientRects().length > 0); - const pattern = - /^(?:(?:delete|delete_forever|warning)\s+)?(?:move(?: all contents)? to trash|delete)$/i; + ) + .filter((el) => el.getClientRects().length > 0) + .reverse(); + const buttonPattern = + /^(?:(?:delete|delete_forever|warning)\s+)?move(?:\s+(?:this\s+)?(?:item|asset|media|image|video|clip|scene|character))?\s+to\s+trash$/i; for (const dialog of dialogs) { + if (!dialogMatchesTrashTarget(dialog, id, target, tileMap)) continue; for (const btn of Array.from(dialog.querySelectorAll("button"))) { if (!isVisibleEnabled(btn)) continue; - if (pattern.test(elText(btn))) { + if (buttonPattern.test(elText(btn))) { return { ok: true, point: centerOf(btn) }; } } @@ -308,7 +392,7 @@ export async function tileDomOp(req: TileDomOpRequest): Promise { if (action === "open_view") return openView(id); if (action === "text_select") return selectText(); if (action === "text_value") return readText(); - if (action === "confirm_dialog") return confirmTrashDialog(); + if (action === "confirm_dialog") return confirmTrashDialog(id); if (action === "dismiss") { await dismissOverlay(); return { ok: true }; diff --git a/ts/types.ts b/ts/types.ts index cc2dc60..cd09816 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -514,6 +514,8 @@ export interface DiscoverStoreResult { newlyDiscovered: boolean; /** Optional compatibility or discovery error code. */ error?: string; + /** Active front-end build label when compatibility fails. */ + build?: string | null; } /** Asset entry normalized for `readStoreSnapshot`. */ @@ -568,7 +570,7 @@ export interface SnapshotCollectionItem { /** Result returned by `readStoreSnapshot`. */ export type StoreSnapshotResult = - | { ok: false; error: string } + | { ok: false; error: string; build?: string | null } | { ok: true; projectId: string | null;