From ac2bd378f538066811100a0d1b90020933c51f04 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:49:04 +0000 Subject: [PATCH] fix(flow): cascade read-only stores and add UI fallbacks - Cascade verified project stores from newest to oldest for reads - Pair snapshot, scene, upload, and tile slot keys with bound store - Gate internal store mutations and hooks on verified builds only - Guard Angular LView tile locators with signal checks on slot keys - Bind trash confirmation dialogs to target tiles with 40-poll cap - Add confirmed DOM fallbacks for upload, character, and title edits - Split frontend types, character preview, and project CRUD modules --- src/assets.rs | 80 ++--- src/character_bio.rs | 273 ++++++++++++++- src/characters.rs | 163 ++------- src/collections.rs | 23 +- src/main.rs | 1 + src/mcp.rs | 3 +- src/project.rs | 399 +--------------------- src/project_store.rs | 22 +- src/projects_ops.rs | 410 +++++++++++++++++++++++ src/service.rs | 7 +- src/tile_menu.rs | 11 +- src/upload.rs | 106 +++++- src/voices.rs | 2 +- ts/angular.ts | 24 +- ts/asset_ops.ts | 5 +- ts/character_extra.ts | 20 +- ts/character_media.ts | 241 ++------------ ts/character_ops.ts | 152 ++++++++- ts/character_preview.ts | 238 ++++++++++++++ ts/character_voices.ts | 37 ++- ts/discover_store.ts | 41 ++- ts/frontend_builds.ts | 619 +++++++---------------------------- ts/frontend_compatibility.ts | 85 ++++- ts/frontend_types.ts | 499 ++++++++++++++++++++++++++++ ts/open_edit_asset.ts | 4 +- ts/project_store.ts | 115 ++++--- ts/projects_ops.ts | 37 ++- ts/read_store_snapshot.ts | 13 +- ts/scene_ops.ts | 2 - ts/scene_tiles.ts | 6 +- ts/state.ts | 5 + ts/tile_dom.ts | 260 ++++++++++++++- ts/types.ts | 8 +- ts/video_ops.ts | 32 +- 34 files changed, 2474 insertions(+), 1469 deletions(-) create mode 100644 src/projects_ops.rs create mode 100644 ts/character_preview.ts create mode 100644 ts/frontend_types.ts diff --git a/src/assets.rs b/src/assets.rs index c3c8975..01f7e0f 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -10,10 +10,10 @@ 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}; +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 /// 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 { - let collections = ProjectStoreSession::open(engine).await?; + ensure_flow_store(engine).await?; + let mut snap = read_snapshot(engine).await?; + 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(); - 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 { + 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)), - } - continue 'items; + }, + Err(err) => failed.push(rename_error(&entry, &err)), } - Err(err) => { - failed.push(rename_error(&entry, &err)); - continue 'items; + if idx + 1 < total { + tokio::time::sleep(Duration::from_millis(250)).await; } - } - if !asset_store_ready { - ensure_flow_store(engine).await?; - asset_store_ready = true; + 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() @@ -473,6 +477,7 @@ pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec } continue 'items; } + ensure_flow_store(engine).await?; let mut ok = false; for attempt in 0..2 { let res = engine @@ -521,12 +526,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 +542,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 +554,32 @@ 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 = snapshot_collections(&mut snap)?; + 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 = 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"))?; + 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..fb8a414 100644 --- a/src/character_bio.rs +++ b/src/character_bio.rs @@ -1,15 +1,114 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Direct project store operations for character personality notes. +//! Direct project store, character route, and form fallback operations for character profiles. + +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::db::FlowDb; use crate::engine::ChromeEngine; -use crate::project_store::ProjectStoreSession; +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, is_store_write_unavailable}; + +/// Opens `/project//character/` using Angular Router first, then URL navigation. +pub(crate) async fn open_character_editor( + engine: &ChromeEngine, + reference_url: &str, + project_id: &str, + char_id: &str, +) -> Result<()> { + let res = engine + .call_flow_async( + "characterOp", + json!([{ + "action": "open_editor", + "project_id": project_id, + "character_id": char_id, + }]), + ) + .await; + if res + .as_ref() + .ok() + .and_then(|v| v.get("ok")) + .and_then(|v| v.as_bool()) + == Some(true) + { + tokio::time::sleep(Duration::from_millis(300)).await; + let _ = ensure_flow_store(engine).await; + return Ok(()); + } + // Use direct URL navigation if the SPA router does not open the editor. + let char_url = + project_subroute_url(reference_url, project_id, &format!("character/{}", char_id)); + engine.navigate(&char_url).await?; + tokio::time::sleep(Duration::from_millis(1800)).await; + let _ = ensure_flow_store(engine).await; + Ok(()) +} + +/// Exits the character editor back to `/project/` and clears stale Angular store handles. +pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Option<&str>) { + let before_finish = engine.current_url().await.unwrap_or_default(); + let in_character = before_finish.contains("/character/"); + let finish_res = engine + .call_flow_async("characterOp", json!([{ "action": "finish" }])) + .await; + let in_workspace = finish_res + .as_ref() + .ok() + .and_then(|v| v.get("in_workspace")) + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let cur = engine.current_url().await.unwrap_or_default(); + if (in_character && !in_workspace) || cur.contains("/character/") { + if !cur.contains("/character/") { + tokio::time::sleep(Duration::from_millis(400)).await; + } + if let Some(pid) = project_id + .map(str::to_string) + .or_else(|| project_id_from_url(&cur)) + .or_else(|| project_id_from_url(&before_finish)) + { + // Reload `/project/` because exiting a direct `/character/` load leaves an empty shell. + let _ = engine.navigate(&project_workspace_url(&cur, &pid)).await; + tokio::time::sleep(Duration::from_millis(1500)).await; + } + } + let _ = ensure_flow_store(engine).await; +} + +/// 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_store_write_unavailable(&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_store_write_unavailable(&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( @@ -27,29 +126,171 @@ 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 { + let err = res.get("error").and_then(Value::as_str); + if !matches!(err, Some("store_loading" | "store_not_bound")) { + break; + } + 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?; + } + 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(()) +} + +/// 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, 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?; + confirm_character_bio_saved(engine, &target.id, bio).await?; db.upsert_character( target.id.clone(), - Some(store.project_id().to_owned()), + Some(pid), target.name.clone(), - Some(bio.to_owned()), + Some(bio.trim().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_store_write_unavailable(&err) => None, + Err(err) => return Err(err), + } + } + Err(err) if is_store_write_unavailable(&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..954fb65 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -11,17 +11,15 @@ 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::{ + confirm_character_bio_saved, edit_character_bio, exit_character_editor, open_character_editor, + 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}; use crate::generation::inspect_generation_network; -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::project::{ensure_flow_store, ensure_project_workspace_root, project_id_from_url}; use crate::queue::{ProgressCallback, SceneParams}; use crate::voices::{ VoiceRequest, apply_voice_with_fallback, delete_portrait, list_all_voices, scene_voice, @@ -101,74 +99,6 @@ pub(crate) async fn apply_character_look(db: &FlowDb, scene: &mut SceneParams) - Ok(()) } -/// Opens `/project//character/` using Angular Router first, then URL navigation. -pub(crate) async fn open_character_editor( - engine: &ChromeEngine, - reference_url: &str, - project_id: &str, - char_id: &str, -) -> Result<()> { - let res = engine - .call_flow_async( - "characterOp", - json!([{ - "action": "open_editor", - "project_id": project_id, - "character_id": char_id, - }]), - ) - .await; - if res - .as_ref() - .ok() - .and_then(|v| v.get("ok")) - .and_then(|v| v.as_bool()) - == Some(true) - { - tokio::time::sleep(Duration::from_millis(300)).await; - let _ = ensure_flow_store(engine).await; - return Ok(()); - } - // Use direct URL navigation if the SPA router does not open the editor. - let char_url = - project_subroute_url(reference_url, project_id, &format!("character/{}", char_id)); - engine.navigate(&char_url).await?; - tokio::time::sleep(Duration::from_millis(1800)).await; - let _ = ensure_flow_store(engine).await; - Ok(()) -} - -/// Exits the character editor back to `/project/` and clears stale Angular store handles. -pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Option<&str>) { - let before_finish = engine.current_url().await.unwrap_or_default(); - let in_character = before_finish.contains("/character/"); - let finish_res = engine - .call_flow_async("characterOp", json!([{ "action": "finish" }])) - .await; - let in_workspace = finish_res - .as_ref() - .ok() - .and_then(|v| v.get("in_workspace")) - .and_then(|v| v.as_bool()) - .unwrap_or(false); - let cur = engine.current_url().await.unwrap_or_default(); - if (in_character && !in_workspace) || cur.contains("/character/") { - if !cur.contains("/character/") { - tokio::time::sleep(Duration::from_millis(400)).await; - } - if let Some(pid) = project_id - .map(str::to_string) - .or_else(|| project_id_from_url(&cur)) - .or_else(|| project_id_from_url(&before_finish)) - { - // Reload `/project/` because exiting a direct `/character/` load leaves an empty shell. - let _ = engine.navigate(&project_workspace_url(&cur, &pid)).await; - tokio::time::sleep(Duration::from_millis(1500)).await; - } - } - let _ = ensure_flow_store(engine).await; -} - /// Lists available Flow character voices from the character editor voice picker. pub(crate) async fn list_voices( engine: &ChromeEngine, @@ -422,19 +352,12 @@ 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 }; 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 { @@ -542,60 +465,25 @@ 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() + }; + if let Some(bio) = form_bio { + form_bio_to_confirm = Some(bio.to_owned()); } + 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() @@ -805,6 +693,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 a2a2f16..e9626bc 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 })) @@ -184,14 +176,27 @@ 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, req: CollectionsParams, ) -> Result { + if req.action == "list" { + let mut snap = crate::project::read_snapshot(engine).await?; + let collections = snapshot_collections(&mut snap)?; + 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/main.rs b/src/main.rs index d180c44..c592653 100644 --- a/src/main.rs +++ b/src/main.rs @@ -27,6 +27,7 @@ mod platform; mod project; mod project_route; mod project_store; +mod projects_ops; mod queue; mod scenes; mod service; diff --git a/src/mcp.rs b/src/mcp.rs index 2a0eef9..637f8d3 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -28,7 +28,8 @@ use crate::characters::{CharacterEditParams, CharacterParams, VoicesParams}; use crate::collections::CollectionsParams; use crate::db::{DOWNLOAD_ASSET_RESOURCE_PREFIX, DOWNLOAD_RESOURCE_PREFIX, DownloadsParams}; use crate::generation::{EditParams, GenerateParams}; -use crate::project::{NewProjectParams, ProjectsParams, StatusParams}; +use crate::project::StatusParams; +use crate::projects_ops::{NewProjectParams, ProjectsParams}; use crate::queue::{JobIdParams, WaitParams}; use crate::scenes::{ScenesParams, VideoParams}; use crate::service::{self, FlowService, ResourceReadError}; diff --git a/src/project.rs b/src/project.rs index e11643e..477d845 100644 --- a/src/project.rs +++ b/src/project.rs @@ -11,7 +11,7 @@ use anyhow::Result; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use tokio::time::{Duration, Instant}; +use tokio::time::Duration; use crate::auth::{check_page_auth, check_page_signed_in, is_flow_host_url, redirect_sso_if_about}; use crate::config::{FLOW_URL, has_persisted_session}; @@ -31,24 +31,6 @@ pub(crate) struct StatusParams { pub(crate) probe: Option, } -/// Parameters for `flow_new_project`. -#[derive(Debug, Clone, Deserialize, JsonSchema)] -pub(crate) struct NewProjectParams { - /// Project title applied after creation. - pub(crate) title: Option, -} - -/// Parameters for `flow_projects`. -#[derive(Debug, Clone, Deserialize, JsonSchema)] -pub(crate) struct ProjectsParams { - /// Action name: "list" (default), "create", "open", "rename", or "delete". - pub(crate) action: Option, - /// Target project ID (optional for "open", "rename", or "delete"). - pub(crate) id: Option, - /// Project title for "create" or "rename", or case-insensitive title match for "open" or "delete". - pub(crate) title: Option, -} - /// Snapshot of the active Google Flow session and open project. #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct FlowStatus { @@ -138,7 +120,7 @@ pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Resu } /// Opens a Flow page and verifies access with the active Chrome profile. -async fn ensure_signed_in_flow_page(engine: &ChromeEngine) -> Result { +pub(crate) async fn ensure_signed_in_flow_page(engine: &ChromeEngine) -> Result { engine.ensure_page().await?; let mut url = engine.current_url().await?; if !is_flow_host_url(&url) { @@ -165,7 +147,7 @@ async fn ensure_signed_in_flow_page(engine: &ChromeEngine) -> Result { } /// Evaluates `projectNav(action)` in the active browser page. -async fn eval_project_nav(engine: &ChromeEngine, action: &str) -> Result { +pub(crate) async fn eval_project_nav(engine: &ChromeEngine, action: &str) -> Result { engine.call_flow_async("projectNav", json!([action])).await } @@ -377,15 +359,15 @@ 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["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["ok"].as_bool() == Some(true) { - return Ok(()); - } if status_err == Some("store_loading") { tokio::time::sleep(Duration::from_millis(250)).await; continue; @@ -451,7 +433,7 @@ fn store_loading_result(result: Result) -> Result { } /// Returns a message suffix with the front-end build label, or an empty string when the page has no label. -async fn build_suffix(engine: &ChromeEngine) -> String { +pub(crate) async fn build_suffix(engine: &ChromeEngine) -> String { match engine.build_label().await { Some(label) => format!(" Flow front end build: {label}."), None => String::new(), @@ -473,9 +455,9 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { ); } } + 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); @@ -491,6 +473,15 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { 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 @@ -506,357 +497,3 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { build_suffix(engine).await ); } - -/// Navigates to the Flow home page, clicks "New project", and persists `title` when provided. -pub(crate) async fn create_project(engine: &ChromeEngine, title: Option<&str>) -> Result { - engine.ensure_page().await?; - let initial_url = engine.current_url().await.unwrap_or_default(); - let already_on_home = crate::auth::is_signed_in_flow_url(&initial_url) - && project_id_from_url(&initial_url).is_none(); - if !already_on_home { - engine.navigate(FLOW_URL).await?; - tokio::time::sleep(Duration::from_millis(900)).await; - } - let mut url = ensure_signed_in_flow_page(engine).await?; - if project_id_from_url(&url).is_some() { - engine.navigate(FLOW_URL).await?; - tokio::time::sleep(Duration::from_millis(900)).await; - url = ensure_signed_in_flow_page(engine).await?; - } - - let mut clicked = false; - for attempt in 0..50 { - if attempt == 12 && already_on_home { - engine.navigate(FLOW_URL).await?; - tokio::time::sleep(Duration::from_millis(900)).await; - url = ensure_signed_in_flow_page(engine).await?; - } - if eval_project_nav(engine, "click_new_project") - .await? - .as_bool() - .unwrap_or(false) - { - clicked = true; - break; - } - tokio::time::sleep(Duration::from_millis(300)).await; - } - if clicked { - for _ in 0..40 { - tokio::time::sleep(Duration::from_millis(400)).await; - let cur = engine.current_url().await?; - if cur.contains("accounts.google.com") { - anyhow::bail!( - "Google Flow redirected to Google Sign-In ({}). Call flow_login to sign in.", - cur - ); - } - url = cur.clone(); - if project_id_from_url(&cur).is_some() { - let has_ws = eval_project_nav(engine, "has_workspace") - .await - .ok() - .and_then(|v| v.as_bool()) - .unwrap_or(false); - if has_ws { - break; - } - } - } - } - let project_id = project_id_from_url(&url); - let mut final_title = title - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()); - if project_id.is_some() { - let _ = ensure_flow_store(engine).await; - if let Some(desired_title) = final_title.as_deref() { - let res = run_projects_op( - engine, - json!({ - "action": "set_title", - "title": desired_title, - }), - ) - .await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to set project title: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - final_title = Some(confirm_project_title(engine, desired_title).await?); - } - } - Ok(json!({ - "created": clicked && project_id.is_some(), - "clicked": clicked, - "project_id": project_id, - "title": final_title, - "url": url, - })) -} - -/// Invokes `projectsOp(req)` on the active Chrome page. -async fn run_projects_op(engine: &ChromeEngine, req: Value) -> Result { - engine.call_flow_async("projectsOp", json!([req])).await -} - -/// Navigates to the signed-in Google Flow home page. -async fn open_signed_in_home_page(engine: &ChromeEngine) -> Result<()> { - engine.ensure_page().await?; - engine.navigate(FLOW_URL).await?; - tokio::time::sleep(Duration::from_millis(900)).await; - let _ = ensure_signed_in_flow_page(engine).await?; - tokio::time::sleep(Duration::from_millis(500)).await; - Ok(()) -} - -/// Lists all existing Flow projects from the Flow home page. -async fn list_projects(engine: &ChromeEngine) -> Result { - open_signed_in_home_page(engine).await?; - let res = run_projects_op(engine, json!({ "action": "list" })).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to list Flow projects: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - Ok(res) -} - -/// Opens a Flow project by `id` or `title` and binds the project store. -async fn open_project( - engine: &ChromeEngine, - id: Option<&str>, - title: Option<&str>, -) -> Result { - let mut target_id = id.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); - let mut matched_title = title.map(|s| s.trim().to_string()); - - if target_id.is_none() { - let want = title - .map(|s| s.trim().to_ascii_lowercase()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| anyhow::anyhow!("Provide `id` or `title` to open a project"))?; - let listed = list_projects(engine).await?; - let projects = listed - .get("projects") - .and_then(|v| v.as_array()) - .cloned() - .unwrap_or_default(); - let hit = projects.into_iter().find(|p| { - p.get("title") - .and_then(|v| v.as_str()) - .map(|t| t.trim().to_ascii_lowercase().contains(&want)) - .unwrap_or(false) - }); - let Some(p) = hit else { - anyhow::bail!("No Google Flow project matches title '{}'", want); - }; - target_id = p.get("id").and_then(|v| v.as_str()).map(|s| s.to_string()); - if let Some(t) = p.get("title").and_then(|v| v.as_str()) { - matched_title = Some(t.to_string()); - } - } - - let pid = - target_id.ok_or_else(|| anyhow::anyhow!("Resolved project has no valid project ID"))?; - let cur = engine.current_url().await.unwrap_or_default(); - let project_url = project_workspace_url(&cur, &pid); - engine.navigate(&project_url).await?; - tokio::time::sleep(Duration::from_millis(800)).await; - ensure_flow_store(engine).await?; - let snap = read_snapshot(engine).await?; - Ok(json!({ - "opened": true, - "project_id": pid, - "title": snap.get("projectTitle").and_then(|v| v.as_str()).map(|s| s.to_string()).or(matched_title), - "url": engine.current_url().await.unwrap_or(project_url), - "assets_count": snap.get("assets").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0), - "collections_count": snap.get("collections").and_then(|v| v.as_array()).map(|c| c.len()).unwrap_or(0), - })) -} - -/// Polls project snapshots until `projectTitle` holds `desired` after a short settle delay. -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 - .get("projectTitle") - .and_then(Value::as_str) - .map(str::trim) - == Some(desired) - { - return Ok(desired.to_string()); - } - } - tokio::time::sleep(Duration::from_millis(250)).await; - } - anyhow::bail!( - "Failed to confirm project title '{desired}' in the Flow project store{}", - build_suffix(engine).await - ) -} - -/// Counts entries in a `projectsOp` list payload that match `id` or exact `title`. -fn count_matching_project_entries( - entries: &[Value], - id: Option<&str>, - title: Option<&str>, -) -> usize { - let want_id = id.map(str::trim).filter(|s| !s.is_empty()); - let want_title = title.map(str::trim).filter(|s| !s.is_empty()); - entries - .iter() - .filter(|entry| { - if let Some(wid) = want_id - && entry.get("id").and_then(Value::as_str) == Some(wid) - { - return true; - } - if let Some(wtitle) = want_title - && entry - .get("title") - .and_then(Value::as_str) - .is_some_and(|t| t.trim().eq_ignore_ascii_case(wtitle)) - { - return true; - } - false - }) - .count() -} - -/// Polls home-view project entries until the deleted project is absent from the page. -async fn confirm_project_deleted( - engine: &ChromeEngine, - deleted_id: Option<&str>, - title: Option<&str>, - before_matches: usize, -) -> Result<()> { - let want_id = deleted_id.map(str::trim).filter(|s| !s.is_empty()); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline { - let listed = run_projects_op(engine, json!({ "action": "list" })).await?; - if listed.get("ok").and_then(Value::as_bool) == Some(true) - && let Some(projects) = listed.get("projects").and_then(Value::as_array) - { - let gone = match want_id { - Some(did) => !projects - .iter() - .any(|p| p.get("id").and_then(Value::as_str) == Some(did)), - None => count_matching_project_entries(projects, None, title) < before_matches, - }; - if gone { - return Ok(()); - } - } - tokio::time::sleep(Duration::from_millis(250)).await; - } - anyhow::bail!("Failed to confirm project deletion on the Flow home page") -} - -/// Renames the active project (or the project identified by `id`). -async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> Result { - let trimmed = title.trim(); - if trimmed.is_empty() { - anyhow::bail!("New project title must not be empty"); - } - if let Some(pid) = id.map(|s| s.trim()).filter(|s| !s.is_empty()) { - let cur = engine.current_url().await.unwrap_or_default(); - if project_id_from_url(&cur).as_deref() != Some(pid) { - let _ = open_project(engine, Some(pid), None).await?; - } - } else { - 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) { - anyhow::bail!( - "Failed to rename project: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - let confirmed_title = confirm_project_title(engine, trimmed).await?; - let cur = engine.current_url().await.unwrap_or_default(); - Ok(json!({ - "ok": true, - "project_id": project_id_from_url(&cur), - "title": confirmed_title, - })) -} - -/// Deletes a Flow project from the Flow home page by `id` or exact `title`. -async fn delete_project( - engine: &ChromeEngine, - id: Option<&str>, - title: Option<&str>, -) -> Result { - if id.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() - && title.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() - { - anyhow::bail!("Provide `id` or `title` to delete a project"); - } - open_signed_in_home_page(engine).await?; - - let before_list = run_projects_op(engine, json!({ "action": "list" })).await?; - let before_matches = before_list - .get("projects") - .and_then(Value::as_array) - .map_or(1, |projects| { - count_matching_project_entries(projects, id, title) - }); - - let res = run_projects_op( - engine, - json!({ "action": "delete", "project_id": id, "title": title }), - ) - .await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to delete project: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - let deleted_id = res.get("deleted_id").and_then(Value::as_str).or(id); - confirm_project_deleted(engine, deleted_id, title, before_matches).await?; - Ok(res) -} - -/// Dispatches `flow_projects` actions (`list`, `create`, `open`, `rename`, `delete`). -pub(crate) async fn handle_projects(engine: &ChromeEngine, req: ProjectsParams) -> Result { - let action = req.action.as_deref().unwrap_or("list").trim(); - match action { - "list" => list_projects(engine).await, - "create" => create_project(engine, req.title.as_deref()).await, - "open" => open_project(engine, req.id.as_deref(), req.title.as_deref()).await, - "rename" => { - let title = req - .title - .as_deref() - .ok_or_else(|| anyhow::anyhow!("`title` is required for action \"rename\""))?; - rename_project(engine, req.id.as_deref(), title).await - } - "delete" => delete_project(engine, req.id.as_deref(), req.title.as_deref()).await, - other => anyhow::bail!("Unknown project action: {}", other), - } -} 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/projects_ops.rs b/src/projects_ops.rs new file mode 100644 index 0000000..c03ea51 --- /dev/null +++ b/src/projects_ops.rs @@ -0,0 +1,410 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Google Flow project list, create, open, rename, and delete operations. + +use anyhow::Result; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::{Value, json}; +use tokio::time::{Duration, Instant}; + +use crate::config::FLOW_URL; +use crate::engine::ChromeEngine; +use crate::project::{ + build_suffix, ensure_flow_store, ensure_project_workspace_root, ensure_signed_in_flow_page, + eval_project_nav, project_id_from_url, project_workspace_url, read_snapshot, +}; + +/// Parameters for `flow_new_project`. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub(crate) struct NewProjectParams { + /// Project title applied after creation. + pub(crate) title: Option, +} + +/// Parameters for `flow_projects`. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +pub(crate) struct ProjectsParams { + /// Action name: "list" (default), "create", "open", "rename", or "delete". + pub(crate) action: Option, + /// Target project ID (optional for "open", "rename", or "delete"). + pub(crate) id: Option, + /// Project title for "create" or "rename", or case-insensitive title match for "open" or "delete". + pub(crate) title: Option, +} + +/// Navigates to the Flow home page, clicks "New project", and persists `title` when provided. +pub(crate) async fn create_project(engine: &ChromeEngine, title: Option<&str>) -> Result { + engine.ensure_page().await?; + let initial_url = engine.current_url().await.unwrap_or_default(); + let already_on_home = crate::auth::is_signed_in_flow_url(&initial_url) + && project_id_from_url(&initial_url).is_none(); + if !already_on_home { + engine.navigate(FLOW_URL).await?; + tokio::time::sleep(Duration::from_millis(900)).await; + } + let mut url = ensure_signed_in_flow_page(engine).await?; + if project_id_from_url(&url).is_some() { + engine.navigate(FLOW_URL).await?; + tokio::time::sleep(Duration::from_millis(900)).await; + url = ensure_signed_in_flow_page(engine).await?; + } + + let mut clicked = false; + for attempt in 0..50 { + if attempt == 12 && already_on_home { + engine.navigate(FLOW_URL).await?; + tokio::time::sleep(Duration::from_millis(900)).await; + url = ensure_signed_in_flow_page(engine).await?; + } + if eval_project_nav(engine, "click_new_project") + .await? + .as_bool() + .unwrap_or(false) + { + clicked = true; + break; + } + tokio::time::sleep(Duration::from_millis(300)).await; + } + if clicked { + for _ in 0..40 { + tokio::time::sleep(Duration::from_millis(400)).await; + let cur = engine.current_url().await?; + if cur.contains("accounts.google.com") { + anyhow::bail!( + "Google Flow redirected to Google Sign-In ({}). Call flow_login to sign in.", + cur + ); + } + url = cur.clone(); + if project_id_from_url(&cur).is_some() { + let has_ws = eval_project_nav(engine, "has_workspace") + .await + .ok() + .and_then(|v| v.as_bool()) + .unwrap_or(false); + if has_ws { + break; + } + } + } + } + let project_id = project_id_from_url(&url); + let mut final_title = title + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()); + if project_id.is_some() { + let _ = ensure_flow_store(engine).await; + if let Some(desired_title) = final_title.as_deref() { + let res = run_projects_op( + engine, + json!({ + "action": "set_title", + "title": desired_title, + }), + ) + .await?; + if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + anyhow::bail!( + "Failed to set project title: {}", + res.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + final_title = Some(confirm_project_title(engine, desired_title).await?); + } + } + Ok(json!({ + "created": clicked && project_id.is_some(), + "clicked": clicked, + "project_id": project_id, + "title": final_title, + "url": url, + })) +} + +/// Invokes `projectsOp(req)` on the active Chrome page. +async fn run_projects_op(engine: &ChromeEngine, req: Value) -> Result { + engine.call_flow_async("projectsOp", json!([req])).await +} + +/// Navigates to the signed-in Google Flow home page. +async fn open_signed_in_home_page(engine: &ChromeEngine) -> Result<()> { + engine.ensure_page().await?; + engine.navigate(FLOW_URL).await?; + tokio::time::sleep(Duration::from_millis(900)).await; + let _ = ensure_signed_in_flow_page(engine).await?; + tokio::time::sleep(Duration::from_millis(500)).await; + Ok(()) +} + +/// Lists all existing Flow projects from the Flow home page. +async fn list_projects(engine: &ChromeEngine) -> Result { + open_signed_in_home_page(engine).await?; + let res = run_projects_op(engine, json!({ "action": "list" })).await?; + if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + anyhow::bail!( + "Failed to list Flow projects: {}", + res.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + Ok(res) +} + +/// Opens a Flow project by `id` or `title` and binds the project store. +async fn open_project( + engine: &ChromeEngine, + id: Option<&str>, + title: Option<&str>, +) -> Result { + let mut target_id = id.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + let mut matched_title = title.map(|s| s.trim().to_string()); + + if target_id.is_none() { + let want = title + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| anyhow::anyhow!("Provide `id` or `title` to open a project"))?; + let listed = list_projects(engine).await?; + let projects = listed + .get("projects") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + let hit = projects.into_iter().find(|p| { + p.get("title") + .and_then(|v| v.as_str()) + .map(|t| t.trim().to_ascii_lowercase().contains(&want)) + .unwrap_or(false) + }); + let Some(p) = hit else { + anyhow::bail!("No Google Flow project matches title '{}'", want); + }; + target_id = p.get("id").and_then(|v| v.as_str()).map(|s| s.to_string()); + if let Some(t) = p.get("title").and_then(|v| v.as_str()) { + matched_title = Some(t.to_string()); + } + } + + let pid = + target_id.ok_or_else(|| anyhow::anyhow!("Resolved project has no valid project ID"))?; + let cur = engine.current_url().await.unwrap_or_default(); + let project_url = project_workspace_url(&cur, &pid); + engine.navigate(&project_url).await?; + tokio::time::sleep(Duration::from_millis(800)).await; + ensure_flow_store(engine).await?; + let snap = read_snapshot(engine).await?; + Ok(json!({ + "opened": true, + "project_id": pid, + "title": snap.get("projectTitle").and_then(|v| v.as_str()).map(|s| s.to_string()).or(matched_title), + "url": engine.current_url().await.unwrap_or(project_url), + "assets_count": snap.get("assets").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0), + "collections_count": snap.get("collections").and_then(|v| v.as_array()).map(|c| c.len()).unwrap_or(0), + })) +} + +/// 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 { + match read_snapshot(engine).await { + Ok(snap) => { + if 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 + .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; + } + anyhow::bail!( + "Failed to confirm project title '{desired}' in the Flow project store{}", + build_suffix(engine).await + ) +} + +/// Counts entries in a `projectsOp` list payload that match `id` or exact `title`. +fn count_matching_project_entries( + entries: &[Value], + id: Option<&str>, + title: Option<&str>, +) -> usize { + let want_id = id.map(str::trim).filter(|s| !s.is_empty()); + let want_title = title.map(str::trim).filter(|s| !s.is_empty()); + entries + .iter() + .filter(|entry| { + if let Some(wid) = want_id + && entry.get("id").and_then(Value::as_str) == Some(wid) + { + return true; + } + if let Some(wtitle) = want_title + && entry + .get("title") + .and_then(Value::as_str) + .is_some_and(|t| t.trim().eq_ignore_ascii_case(wtitle)) + { + return true; + } + false + }) + .count() +} + +/// Polls home-view project entries until the deleted project is absent from the page. +async fn confirm_project_deleted( + engine: &ChromeEngine, + deleted_id: Option<&str>, + title: Option<&str>, + before_matches: usize, +) -> Result<()> { + let want_id = deleted_id.map(str::trim).filter(|s| !s.is_empty()); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + let listed = run_projects_op(engine, json!({ "action": "list" })).await?; + if listed.get("ok").and_then(Value::as_bool) == Some(true) + && let Some(projects) = listed.get("projects").and_then(Value::as_array) + { + let gone = match want_id { + Some(did) => !projects + .iter() + .any(|p| p.get("id").and_then(Value::as_str) == Some(did)), + None => count_matching_project_entries(projects, None, title) < before_matches, + }; + if gone { + return Ok(()); + } + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + anyhow::bail!("Failed to confirm project deletion on the Flow home page") +} + +/// Renames the active project (or the project identified by `id`). +async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> Result { + let trimmed = title.trim(); + if trimmed.is_empty() { + anyhow::bail!("New project title must not be empty"); + } + if let Some(pid) = id.map(|s| s.trim()).filter(|s| !s.is_empty()) { + let cur = engine.current_url().await.unwrap_or_default(); + if project_id_from_url(&cur).as_deref() != Some(pid) { + let _ = open_project(engine, Some(pid), None).await?; + } + } else { + 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) { + anyhow::bail!( + "Failed to rename project: {}", + res.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + let confirmed_title = confirm_project_title(engine, trimmed).await?; + let cur = engine.current_url().await.unwrap_or_default(); + Ok(json!({ + "ok": true, + "project_id": project_id_from_url(&cur), + "title": confirmed_title, + })) +} + +/// Deletes a Flow project from the Flow home page by `id` or exact `title`. +async fn delete_project( + engine: &ChromeEngine, + id: Option<&str>, + title: Option<&str>, +) -> Result { + if id.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() + && title.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() + { + anyhow::bail!("Provide `id` or `title` to delete a project"); + } + open_signed_in_home_page(engine).await?; + + let before_list = run_projects_op(engine, json!({ "action": "list" })).await?; + let before_matches = before_list + .get("projects") + .and_then(Value::as_array) + .map_or(1, |projects| { + count_matching_project_entries(projects, id, title) + }); + + let res = run_projects_op( + engine, + json!({ "action": "delete", "project_id": id, "title": title }), + ) + .await?; + if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { + anyhow::bail!( + "Failed to delete project: {}", + res.get("error") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + let deleted_id = res.get("deleted_id").and_then(Value::as_str).or(id); + confirm_project_deleted(engine, deleted_id, title, before_matches).await?; + Ok(res) +} + +/// Dispatches `flow_projects` actions (`list`, `create`, `open`, `rename`, `delete`). +pub(crate) async fn handle_projects(engine: &ChromeEngine, req: ProjectsParams) -> Result { + let action = req.action.as_deref().unwrap_or("list").trim(); + match action { + "list" => list_projects(engine).await, + "create" => create_project(engine, req.title.as_deref()).await, + "open" => open_project(engine, req.id.as_deref(), req.title.as_deref()).await, + "rename" => { + let title = req + .title + .as_deref() + .ok_or_else(|| anyhow::anyhow!("`title` is required for action \"rename\""))?; + rename_project(engine, req.id.as_deref(), title).await + } + "delete" => delete_project(engine, req.id.as_deref(), req.title.as_deref()).await, + other => anyhow::bail!("Unknown project action: {}", other), + } +} diff --git a/src/service.rs b/src/service.rs index 4b8223b..a2645b5 100644 --- a/src/service.rs +++ b/src/service.rs @@ -23,7 +23,8 @@ use crate::download; use crate::engine::{ChromeEngine, ENGINE_NAME}; use crate::generation::{self, EditParams, GenerateParams}; use crate::media_files; -use crate::project::{self, ProjectsParams}; +use crate::project; +use crate::projects_ops::{self, ProjectsParams}; use crate::queue::{JobQueue, JobResult, JobRunner, JobView, SceneParams, WaitParams}; use crate::scenes::{self, ScenesParams, VideoParams}; use crate::tile_menu::PageHold; @@ -321,7 +322,7 @@ impl FlowService { /// Opens the Flow home page, clicks "New project", and saves `title` when given. pub(crate) async fn new_project(&self, title: Option<&str>) -> Result { - project::create_project(&self.engine, title).await + projects_ops::create_project(&self.engine, title).await } /// Lists, creates, opens, renames, or deletes Google Flow projects. @@ -331,7 +332,7 @@ impl FlowService { .as_deref() .is_some_and(|a| a.trim().eq_ignore_ascii_case("delete")); let req_id = req.id.clone(); - let res = project::handle_projects(&self.engine, req).await?; + let res = projects_ops::handle_projects(&self.engine, req).await?; if is_delete && let Some(pid) = res .get("deleted_id") diff --git a/src/tile_menu.rs b/src/tile_menu.rs index 3791a9a..d2debf9 100644 --- a/src/tile_menu.rs +++ b/src/tile_menu.rs @@ -211,7 +211,16 @@ 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 = tile_dom_op(engine, "confirm_dialog", id).await?; + if is_ok(&confirm) + && let Some(point) = confirm.get("point") + { + let _ = engine.click_point(point).await?; + } + 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..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"; @@ -44,29 +44,44 @@ 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) { + }) +} + +/// 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 !is_store_write_unavailable(&err) => return Err(err), + Err(_) => {} + } + } + Err(err) if !is_store_write_unavailable(&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 +288,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/src/voices.rs b/src/voices.rs index 8f06abc..fc3c1fb 100644 --- a/src/voices.rs +++ b/src/voices.rs @@ -10,7 +10,7 @@ use serde::Deserialize; use serde_json::{Value, json}; use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; -use crate::characters::{exit_character_editor, open_character_editor}; +use crate::character_bio::{exit_character_editor, open_character_editor}; use crate::config::downloads_dir; use crate::engine::{ChromeEngine, checked_runtime_result}; use crate::platform::{create_private_dir_all, write_private_file_atomic}; diff --git a/ts/angular.ts b/ts/angular.ts index 6c948c0..69e383b 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"; @@ -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,19 @@ 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; - const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView; - const verifiedView = contextField ? readOwn(raw, contextField) : undefined; - return Array.isArray(verifiedView) ? verifiedView : null; + if (isLiveLView(lView)) return lView; + for (const contextField of lContextViewFields()) { + const candidateView = readOwn(raw, contextField); + 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; } return null; } 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 3d5729d..34dd754 100644 --- a/ts/character_extra.ts +++ b/ts/character_extra.ts @@ -127,9 +127,9 @@ function readVoiceCatalog(pane: Element): { entries: VoiceMeta[]; byObject: Map< }; const formHost = document.querySelector("flow-character-form"); - const { voiceMap: voiceMapKey } = characterVoiceFormat(); - const form = formHost ? findComponent(formHost, (v) => typeof readOwn(v, voiceMapKey) === "function") : undefined; - const mapFn = readOwn(form, voiceMapKey); + const voiceMapKey = characterVoiceFormat()?.voiceMap; + const form = formHost && voiceMapKey ? findComponent(formHost, (v) => typeof readOwn(v, voiceMapKey) === "function") : undefined; + const mapFn = voiceMapKey ? readOwn(form, voiceMapKey) : undefined; const rawMap: unknown = typeof mapFn === "function" ? mapFn.call(form) : null; if (rawMap instanceof Map) { for (const [k, v] of rawMap.entries()) { @@ -139,9 +139,9 @@ function readVoiceCatalog(pane: Element): { entries: VoiceMeta[]; byObject: Map< } const pickerHost = pane.querySelector("flow-add-menu-popover-content") ?? pane; - const { pickerAssets } = characterPreviewFormat(); - const menu = findComponent(pickerHost, (v) => typeof readOwn(v, pickerAssets) === "function"); - const listFn = readOwn(menu, pickerAssets); + const pickerAssets = characterPreviewFormat()?.pickerAssets; + const menu = pickerAssets ? findComponent(pickerHost, (v) => typeof readOwn(v, pickerAssets) === "function") : undefined; + const listFn = pickerAssets ? readOwn(menu, pickerAssets) : undefined; const rawList: unknown = typeof listFn === "function" ? listFn.call(menu) : null; if (Array.isArray(rawList)) { for (const item of rawList) { @@ -582,15 +582,15 @@ async function resolveCharacterCustomVoiceUrls(): Promise { if (m?.[1]) candidates.push(m[1]); } const fmt = characterVoiceFormat(); - const form = formHost ? findComponent(formHost, (v) => + const form = formHost && fmt ? findComponent(formHost, (v) => typeof readOwn(v, fmt.selectedVoice) === "function" || typeof readOwn(v, fmt.voiceMap) === "function", ) : undefined; - const recFn = readOwn(form, fmt.selectedRecord); + const recFn = fmt ? readOwn(form, fmt.selectedRecord) : undefined; pushRecord(typeof recFn === "function" ? recFn.call(form) : undefined); - const selFn = readOwn(form, fmt.selectedVoice); + const selFn = fmt ? readOwn(form, fmt.selectedVoice) : undefined; const selVal: unknown = typeof selFn === "function" ? selFn.call(form) : undefined; const selId = typeof selVal === "string" ? selVal.trim() : ""; - const mapFn = readOwn(form, fmt.voiceMap); + const mapFn = fmt ? readOwn(form, fmt.voiceMap) : undefined; const vMap: unknown = typeof mapFn === "function" ? mapFn.call(form) : null; if (selId && vMap instanceof Map) pushRecord(vMap.get(selId) ?? vMap.get(selId.replace(/^voices\//i, ""))); if (selId && !/^voices\//i.test(selId)) candidates.push(selId); diff --git a/ts/character_media.ts b/ts/character_media.ts index ff3fea0..63aaf88 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -4,21 +4,31 @@ // Attach project assets, upload references, and generate character looks. import { - pickerAssetMatches, pickerElementMatches, readOwn, resolveLView, - withLViewMapCapture, type PickerMatchTarget, + pickerAssetMatches, pickerElementMatches, readOwn, resolveLView, type PickerMatchTarget, } from "./angular"; import { clearPreviewSlot } from "./character_extra"; +import { + captureLViewAndClick, + dismissAllSnackbars, + findPreviewSlotButton, + getCharacterPreviewInstance, + isPreviewSlotOccupiedDom, + isPreviewSlotSelected, + normSlot, + probePreviewControls, + readPreviewSlotState, + selectPreviewSlot, + type CharacterPreview, + type CharacterSlot, +} from "./character_preview"; import { clickButtonByRegex, delay, dismissOverlay, elText, findSnackbarMatch, - fifeBase, hoverProbe, isVisibleEnabled, legacyMedia, pickTileUrl, setNativeValue, + fifeBase, isVisibleEnabled, pickTileUrl, setNativeValue, } from "./dom"; import { characterPreviewFormat, frontendBuild, readBuildLabel } 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; @@ -47,213 +57,6 @@ function findPreviewSlotActionButton(re: RegExp): HTMLElement | null { return null; } -/** 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, format.destroyed)) && - 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 soupyBusy = Array.from( - document.querySelectorAll("flow-character-preview-panel flow-soupy-overlay, flow-character-image-preview flow-soupy-overlay"), - ).some((ov) => { - const st = getComputedStyle(ov); - return st.display !== "none" && st.visibility !== "hidden" && ov.getClientRects().length > 0; - }); - const isAreaBusy = - soupyBusy || - Boolean( - document.querySelector( - 'flow-character-preview-panel [aria-busy="true"], flow-character-image-preview [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, @@ -395,8 +198,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); @@ -644,8 +448,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 788055c..c63ea51 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -4,10 +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 } from "./frontend_builds"; +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 { @@ -88,10 +158,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 +165,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" }; } @@ -138,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", @@ -245,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"]', + `flow-character-form, flow-character-image-preview, ${CHARACTER_NAME_INPUT_SELECTOR}, ${CHARACTER_BIO_INPUT_SELECTOR}`, ) ) { break; @@ -263,16 +351,15 @@ 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"]', - ); - 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 })); 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 +369,47 @@ 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" }; + } 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 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); + 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 new file mode 100644 index 0000000..68f1b65 --- /dev/null +++ b/ts/character_preview.ts @@ -0,0 +1,238 @@ +// 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(); + if (!format) return null; + 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, format.destroyed)) && + 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 soupyBusy = Array.from( + document.querySelectorAll( + "flow-character-preview-panel flow-soupy-overlay, flow-character-image-preview flow-soupy-overlay", + ), + ).some((ov) => { + const st = getComputedStyle(ov); + return st.display !== "none" && st.visibility !== "hidden" && ov.getClientRects().length > 0; + }); + const isAreaBusy = + soupyBusy || + Boolean( + document.querySelector( + 'flow-character-preview-panel [aria-busy="true"], flow-character-image-preview [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 8134f6b..f81d25c 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, @@ -55,11 +55,12 @@ export async function characterVoiceOp( const format = characterVoiceFormat(); function isFormBusy(comp: CharacterFormComponent | null): boolean { - const busyFn = format.busy ? readOwn(comp, format.busy) : undefined; + const busyFn = format?.busy ? readOwn(comp, format.busy) : undefined; 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 => { @@ -118,13 +119,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; } @@ -215,7 +217,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; @@ -271,6 +273,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++) { @@ -484,15 +487,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 a6b793e..3708625 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -3,13 +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 } from "./frontend_builds"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { clearProjectStore, currentProjectStore, findProjectStoreInView, + hasNoCascadedStoreClasses, installProjectStore, isCurrent, projectInRoute, @@ -119,17 +120,22 @@ 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(); 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) { @@ -187,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 9f32fc5..ffc9117 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -5,9 +5,54 @@ import type { AgentAttachmentExport } from "./agent_attachments"; import type { AgentExport } from "./agent_protocol"; -import type { AgentWireFormat } from "./agent_wire"; import type { AgentSettingsExport } from "./agent_settings_protocol"; import type { MediaUploadExport } from "./project_upload"; +import type { + AgentAttachmentFormat, + AgentChatFormat, + AgentSettingsFormat, + CharacterCreateFormat, + CharacterPreviewFormat, + CharacterVoiceFormat, + FrontendBuild, + FrontendFormats, + ProjectStoreFormat, + ProjectTitleFormat, + SceneTileFormat, + SnapshotFormat, +} from "./frontend_types"; +export type { + AgentAttachmentFields, + AgentAttachmentFormat, + AgentChatFormat, + AgentSettingsFormat, + AgentSettingsLocalFormat, + AgentSettingsWireFormat, + AssetTrashFormat, + CharacterBioFormat, + CharacterCreateFormat, + CharacterPreviewFormat, + CharacterVoiceFormat, + CollectionWriteFormat, + FrontendBuild, + FrontendBuildFields, + FrontendFormats, + MediaUploadFields, + MediaUploadFormat, + ProjectMutationFormat, + ProjectStoreFormat, + ProjectTitleFormat, + ProjectUploadFormat, + SceneTileFormat, + SnapshotCharacterFormat, + SnapshotCreditsFormat, + SnapshotFormat, + SnapshotMediaFormat, + SnapshotTileFormat, + SnapshotTileTypesFormat, + SnapshotTrimFormat, + VoiceConfirmationFormat, +} from "./frontend_types"; import { NOVEMBER_29_BIO, NOVEMBER_29_COLLECTION, @@ -22,54 +67,7 @@ import { import { NOVEMBER_29_AGENT } from "./frontend_nov29_agent"; import { NOVEMBER_29_AGENT_SETTINGS } from "./frontend_nov29_settings"; import { NOVEMBER_29_ATTACHMENTS, NOVEMBER_29_PAGE } from "./frontend_nov29_upload"; - -/** Field names for the collection write requests of one build. */ -export interface CollectionWriteFormat { - /** Tile ID in a single-tile request. */ - tileId: string; - /** Change in a single-tile request. */ - tileChange: string; - /** Destination in a collection move request. */ - moveTarget: string; - /** Tiles in a collection move request. */ - moveTiles: string; - /** Collection IDs in a verified deletion request. */ - deleteCollections?: string; -} - -/** Field names for the asset trash requests of one build. */ -export interface AssetTrashFormat { - /** Entries in a batch trash request. */ - entries: string; - /** Tile in a batch trash entry. */ - tile: string; - /** Trash flag in a batch entry. */ - trashed: string; - /** Timestamp in the batch request. */ - date: string; - /** Trash destination in a batch entry. */ - destination: string; - /** Workflow IDs in a scene clip deletion request. */ - sceneWorkflows: string; -} - -/** Request formats verified for internal Flow operations. */ -export interface FrontendFormats { - /** Direct Flow Agent session and turn operations. */ - agent_chat: AgentChatFormat; - /** Agent references and local media uploads. */ - agent_attachments: AgentAttachmentFormat; - /** Local media uploads to a project library. */ - project_upload: ProjectUploadFormat; - /** Project-level Agent preferences and memory. */ - agent_settings: AgentSettingsFormat; - /** Direct collection writes. */ - collection_write: CollectionWriteFormat; - /** Asset trash through the project store. */ - asset_trash_store: AssetTrashFormat; - /** Character personality note update. */ - character_bio: CharacterBioFormat; -} +import { runtimeState } from "./state"; /** Managed operations that every verified Flow build must cover. */ export const FRONTEND_OPERATIONS = [ @@ -167,238 +165,11 @@ export const AGENT_ATTACHMENT_EXPORTS = [ "confirmUpload", ] as const satisfies readonly AgentAttachmentExport[]; -/** Browser exports and service fields for Agent settings. */ -export interface AgentSettingsFormat { - /** Project metadata service's query client. */ - queryClient: string; - /** Project metadata service's request client. */ - requestClient: string; - /** Browser exports for native settings requests. */ - exports: Readonly>; - /** New names for project settings methods and catalogue fields. */ - wire?: AgentSettingsWireFormat; - /** Values that the build keeps inside its modules and does not export. */ - local?: AgentSettingsLocalFormat; -} - -/** Values that the runtime builds for a build with no export for them. */ -export interface AgentSettingsLocalFormat { - /** Query key of the model catalogue. */ - modelKey: readonly unknown[]; - /** Method on the model service that loads the catalogue. */ - fetchModels: string; - /** Fields of the settings update method descriptor. */ - updateMethod: { - /** Plain values by descriptor field. */ - values: Readonly>; - /** Namespace exports by descriptor field. */ - exports: Readonly>; - /** Namespace export with the marker symbol. */ - marker: string; - }; -} - -/** Methods and fields used to read and encode one build's Agent settings. */ -export interface AgentSettingsWireFormat { - /** Method that gets the settings from the metadata response. */ - metadata: string; - /** Method that encodes the request descriptor and message. */ - encode: string; - /** New names of the settings message methods. */ - methods: Readonly>; - /** Model group in the catalogue. */ - groups: string; - /** Image model group. */ - imageModels: string; - /** Video model group. */ - videoModels: string; - /** Account tier defaults in the catalogue. */ - tierDefaults: string; - /** Model list in the options request. */ - families: string; - /** Usage codes in the options filter. */ - usages: string; - /** Model ID in an option. */ - modelId: string; - /** Preferred model ID in the selection request. */ - preferredModel: string; -} - -/** Project page and browser exports for Agent chat. */ -export interface AgentChatFormat { - /** Exported project page component class. */ - page: string; - /** Agent transport service on the project page. */ - transport: string; - /** Angular injector on the project page. */ - injector: string; - /** Exported Agent composer controller. */ - composer: string; - /** Method on the composer that reports whether the page can send. Default `wb`. */ - canSend?: string; - /** Exported permission response service. */ - permissions: string; - /** Exported question response service. */ - questions: string; - /** Signal with the page's project ID. */ - project: string; - /** Lifecycle controller on the project page. */ - lifecycle: string; - /** Destroyed flag on the lifecycle controller. */ - destroyed: string; - /** Browser exports for the native Agent protocol. */ - exports: Readonly>; - /** Changes to the native Agent fields and methods. */ - wire?: AgentWireFormat; -} - -/** Native services and request fields for local media uploads. */ -export interface MediaUploadFormat { - /** Project store on the page component. */ - store: string; - /** Signal with all project tiles. */ - tiles: string; - /** Query that loads the tiles for the active project. */ - tileQuery: string; - /** Project mutation dispatcher. */ - dispatcher: string; - /** Angular injector on the project page. */ - injector: string; - /** Exported upload consent service. */ - consent: string; - /** Functions that the verified build uses for uploads. */ - exports: Readonly>; - /** Fields in the native upload format. */ - fields: MediaUploadFields; -} - /** Upload functions that do not depend on Agent message support. */ export const MEDIA_UPLOAD_EXPORTS = [ "id", "validateFiles", "isVideo", "mimeType", "imageSize", "videoInfo", "confirmUpload", ] as const satisfies readonly MediaUploadExport[]; -/** Fields in the native request and reply for a local media upload. */ -export interface MediaUploadFields { - /** Accepted files in the validation result. */ - accepted: string; - /** Error messages in the validation result. */ - errors: string; - /** Duration in the video metadata. */ - duration: string; - /** Workflow ID in the upload request. */ - workflow: string; - /** Media ID in the upload request. */ - media: string; - /** Local file in the upload request. */ - file: string; - /** Date in the upload request. */ - date: string; - /** Image dimensions in the upload request. */ - dimensions: string; - /** Completion callbacks in the upload request. */ - completion: string; - /** Project ID in the upload request. */ - project: string; -} - -/** Project page fields and exports for Agent attachments. */ -export interface AgentAttachmentFormat extends MediaUploadFormat { - /** Functions for uploads and Agent message attachments. */ - exports: Readonly>; - /** Fields for uploads and Agent message attachments. */ - fields: AgentAttachmentFields; -} - -/** Additional fields in the Agent attachment protocol. */ -export interface AgentAttachmentFields extends MediaUploadFields { - /** Character ID in a native reference. */ - character: string; - /** Text content in the message request. */ - text: string; - /** Attachment references in the message request. */ - references: string; -} - -/** Project page and upload formats for an independent library upload. */ -export interface ProjectUploadFormat { - /** Class and lifecycle fields of the page that owns the upload services. */ - page: Pick; - /** Native upload fields shared with Agent attachments. */ - media: MediaUploadFormat; -} - -/** Field names for a character personality update. */ -export interface CharacterBioFormat { - /** Character ID in a single-tile request. */ - tileId: string; - /** Change in a single-tile request. */ - tileChange: string; - /** Text in a personality change. */ - notes: string; -} - -/** Field names for the active project store and its tile query. */ -export interface ProjectStoreFormat { - /** Class of the project shell store. */ - storeClass: string; - /** Lifecycle controller on the store. */ - lifecycle: string; - /** Destroyed flag on the lifecycle controller. */ - destroyed: string; - /** Project ID signal. */ - projectId: string; - /** Service that owns the tile query and writes. */ - tilesService: string; - /** Query client on the tile service. */ - queryClient: string; - /** Project mutation dispatcher. */ - dispatcher: string; - /** Tile rows in the query result. */ - rows: string; - /** Signal query that loads the tiles of the active project. */ - tileQuery: string; - /** Mutation runner on the project store. */ - mutator: string; - /** Error observable on the store mutation queue. */ - errorStream: string; - /** Component slots that hold the injected project store. */ - componentSlots: readonly string[]; - /** Angular LView slot on an upgraded LContext wrapper. */ - lContextView: string; - /** Field names of a scene tile and its workflow history. */ - scene?: SceneTileFormat; - /** Native names for mutations that use the general store adapter. */ - mutations?: ProjectMutationFormat; -} - -/** Fields that identify the contents of a scene tile. */ -export interface SceneTileFormat { - /** Clip array on a scene tile. */ - clips: string; - /** Workflow history map on a scene tile. */ - history: string; -} - -/** Names of fields used by the general project mutations. */ -export interface ProjectMutationFormat { - /** Tile ID in a single-tile request. */ - tileId: string; - /** Change in a single-tile request. */ - tileChange: string; - /** Workflow IDs used to create a scene or add clips. */ - sceneWorkflows: string; - /** Collection ID in a scene creation request. */ - sceneCollection: string; - /** Scene tile in a successful creation response. */ - sceneCreated: string; - /** Scene ID in a request to add workflows. */ - sceneId: string; - /** Start time in a video trim request. */ - trimStart: string; - /** End time in a video trim request. */ - trimEnd: string; -} - /** Project store format of build 20261117.10. */ const NOVEMBER_17_STORE: ProjectStoreFormat = { storeClass: "VN", @@ -630,110 +401,6 @@ const NOVEMBER_20_ATTACHMENTS: AgentAttachmentFormat = { }, }; -/** Verified media payload fields used during snapshot reads. */ -export interface SnapshotMediaFormat { - /** Primary media payload property on an image or video tile. */ - container: string; - /** Direct media URL property on a media payload or history item. */ - url: string; - /** Lifecycle status property on a media payload. */ - status: string; - /** Error payload property on a media payload. */ - error: string; - /** Dimensions object property on a media payload. */ - dimensions: string; - /** Video duration property in seconds on a media payload. */ - duration: string; - /** Creation date property on a tile or media payload. */ - date: string; - /** Boolean property that is true on uploaded media that Flow finished. */ - uploaded: string; - /** Namespace export with the source symbol of uploaded media. */ - uploadSource: string; -} - -/** Verified character tile and entity protobuf fields used during snapshot reads. */ -export interface SnapshotCharacterFormat { - /** Serialized entity message property on a character tile. */ - entity: string; - /** Look workflow map property on a character tile. */ - looks: string; - /** Preview media ID property on a character tile. */ - previewMediaId: string; - /** Protobuf field number for `entity_info` on the entity message. */ - entityInfoField: number; - /** Protobuf field number for `character_info` on `entity_info`. */ - characterInfoField: number; - /** Protobuf field number for `audio_references` on `character_info`. */ - audioReferencesField: number; - /** Protobuf field number for a preset voice ID on an audio reference. */ - presetVoiceField: number; - /** Protobuf field number for a custom voice workflow ID on an audio reference. */ - customVoiceField: number; - /** Protobuf field number for `personality_notes` on `character_info`. */ - notesField: number; -} - -/** Verified tile type discriminants in the project tile store. */ -export interface SnapshotTileTypesFormat { - /** Collection tile type value. */ - collection: string; - /** Asset tile type values included in project asset lists. */ - assets: readonly string[]; - /** Non-asset tile type values excluded from project asset lists and counts. */ - ignored: readonly string[]; -} - -/** Verified account credits service and balance accessors. */ -export interface SnapshotCreditsFormat { - /** Exported credits service class on the Angular frontend namespace. */ - service: string; - /** Signal method returning the spendable total credit balance. */ - total: string; - /** Query property on the credits service. */ - query: string; - /** Method on the credits query message returning total credits. */ - balanceMethod: string; -} - -/** Verified tile fields that every project tile carries. */ -export interface SnapshotTileFormat { - /** Soft-trash flag on a tile. */ - trashed: string; - /** Parent collection ID on a tile. */ - parentCollection: string; -} - -/** Verified trim bounds on a video media payload and scene clip fields. */ -export interface SnapshotTrimFormat { - /** Trim start in seconds on a trimmed video media payload. */ - mediaStart: string; - /** Trim end in seconds on a trimmed video media payload. */ - mediaEnd: string; - /** Start of a scene clip in seconds. */ - clipStart: string; - /** End of a scene clip in seconds. */ - clipEnd: string; - /** Duration of a scene clip in seconds. */ - clipDuration: string; -} - -/** Verified snapshot field map for one frontend build. */ -export interface SnapshotFormat { - /** Tile-level flags and references. */ - tile: SnapshotTileFormat; - /** Trim and scene clip time fields. */ - trim: SnapshotTrimFormat; - /** Media payload and URL properties. */ - media: SnapshotMediaFormat; - /** Character look, preview, and entity properties. */ - character: SnapshotCharacterFormat; - /** Tile type discriminants for assets, collections, and non-asset items. */ - tileTypes: SnapshotTileTypesFormat; - /** Credits service class and balance accessors. */ - credits: SnapshotCreditsFormat; -} - /** Snapshot format of build 20261120.00. */ const NOVEMBER_20_SNAPSHOT: SnapshotFormat = { tile: { trashed: "Cb", parentCollection: "Dc" }, @@ -773,116 +440,6 @@ const NOVEMBER_20_SNAPSHOT: SnapshotFormat = { }, }; -/** Verified operations and store format of one build. */ -interface FrontendBuildFields { - /** Layout for the project store. */ - projectStore: ProjectStoreFormat; - /** Snapshot field descriptors for verified store reads. */ - snapshot?: SnapshotFormat; - /** Native fields used to confirm a character voice assignment. */ - voiceConfirmation?: VoiceConfirmationFormat; - /** Native fields of the character preview panel and controls. */ - characterPreview?: CharacterPreviewFormat; - /** Native fields of the character voice form. */ - characterVoice?: CharacterVoiceFormat; - /** Native fields for character creation and store lifecycle checks. */ - characterCreate?: CharacterCreateFormat; - /** Native fields of editable project titles. */ - projectTitle?: ProjectTitleFormat; -} - -/** A verified build with full or pre-Agent operation coverage. */ -export type FrontendBuild = FrontendBuildFields & ( - | { legacy?: false; operations: FrontendFormats } - | { legacy: true; operations: Pick & Partial } -); - -/** Native methods of the character preview panel and look controls. */ -export interface CharacterPreviewFormat { - /** Lifecycle controller on the panel. */ - lifecycle: string; - /** Destroyed flag on the lifecycle controller. */ - destroyed: string; - /** Method that opens the native file picker for the active slot. */ - upload: string; - /** Method that identifies the preview panel. */ - marker: string; - /** Signal with the portrait media record. */ - portrait: string; - /** Signal with the body media record. */ - body: string; - /** Signal with the active slot image URL. */ - source: string; - /** Signal that reports whether the preview is busy. */ - busy: string; - /** Footer signal that reports whether look generation is busy. */ - footerBusy: string; - /** Popover method that lists project assets in the add menu. */ - pickerAssets: string; - /** Popover method that selects a project asset in the add menu. */ - pickerSelect: string; -} - -/** Native signals and outputs of the character voice form. */ -export interface CharacterVoiceFormat { - /** Lifecycle controller on the form component. */ - lifecycle: string; - /** Destroyed flag on the lifecycle controller. */ - destroyed: string; - /** Signal with the loaded voice map. */ - voiceMap: string; - /** Signal with the selected voice ID. */ - selectedVoice: string; - /** Signal with the selected raw voice entry. */ - selectedRecord: string; - /** Output emitter that commits a voice change. */ - changeEmitter: string; - /** Signal that reports whether the form is busy, when the build has one. */ - busy?: string; - /** True when the build keeps the form voice map empty while idle. */ - emptyMap: boolean; -} - -/** Field names for character creation and store lifecycle checks. */ -export interface CharacterCreateFormat { - /** Lifecycle controller on the bound store service. */ - lifecycle: string; - /** Destroyed flag on the lifecycle controller. */ - destroyed: string; - /** Entity kind fields set to `1` in a `create_entity` request. */ - entityKinds: readonly string[]; - /** Collection fields set to `undefined` in a `create_entity` request. */ - collections: readonly string[]; - /** Completion callback fields in a `create_entity` request. */ - completions: readonly string[]; - /** Created tile fields in a `create_entity` response. */ - created: readonly string[]; -} - -/** Native fields of `flow-editable-text` used to commit a project title. */ -export interface ProjectTitleFormat { - /** Output emitter that commits the edited title text. */ - saveEmitter: string; - /** Signal that sets the component back to viewing mode. */ - stateSignal: string; -} - -/** Character editor and query fields used to read the saved voice. */ -export interface VoiceConfirmationFormat { - /** Exported character editor class. */ - editor: string; - /** Query that loads the character entity. */ - entityQuery: string; - /** Editor method that reads the voice ID from that entity. */ - savedVoice: string; - /** Form method that reads the locally selected voice ID. */ - selectedVoice: string; - /** Event that reports the saved voice media and workflow IDs. */ - previewSaved: string; - /** Signal with the voice that the picker will add to the character. */ - pickerSelection: string; -} - /** Character preview format of earlier builds. */ const LEGACY_CHARACTER_PREVIEW: CharacterPreviewFormat = { lifecycle: "Ca", destroyed: "Va", upload: "JR", marker: "Si", portrait: "ka", body: "ma", @@ -909,7 +466,10 @@ 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: { @@ -925,8 +485,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: { @@ -995,6 +557,14 @@ 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(CASCADED_BUILDS.map((b) => b.projectStore)), +); + /** Returns the exact label published by the active page. */ export function readBuildLabel(): string | null { const label = window.WIZ_global_data?.cfb2h; @@ -1006,11 +576,50 @@ 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; } +/** 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 for the active or cascaded store. */ +export function lContextViewFields(): readonly string[] { + const paired = boundOrActiveBuild()?.projectStore; + if (paired) return [paired.lContextView]; + return Array.from(new Set(CASCADED_PROJECT_STORES.map((s) => s.lContextView))); +} + +/** Returns verified property and Angular input signal names that hold a grid tile record. */ +export function tileSlotKeys(): readonly string[] { + const paired = boundOrActiveBuild()?.operations.asset_trash_store?.tile; + if (paired) return ["tile", paired]; + const cascaded = CASCADED_BUILDS + .map((b) => b.operations.asset_trash_store?.tile) + .filter((k): k is string => Boolean(k)); + return ["tile", ...new Set(cascaded)]; +} + +/** 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()); @@ -1042,33 +651,33 @@ 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/frontend_types.ts b/ts/frontend_types.ts new file mode 100644 index 0000000..115ca68 --- /dev/null +++ b/ts/frontend_types.ts @@ -0,0 +1,499 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Type declarations for verified builds of the Google Flow front end. + +import type { AgentAttachmentExport } from "./agent_attachments"; +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"; + +/** Field names for the collection write requests of one build. */ +export interface CollectionWriteFormat { + /** Tile ID in a single-tile request. */ + tileId: string; + /** Change in a single-tile request. */ + tileChange: string; + /** Destination in a collection move request. */ + moveTarget: string; + /** Tiles in a collection move request. */ + moveTiles: string; + /** Collection IDs in a verified deletion request. */ + deleteCollections?: string; +} + +/** Field names for the asset trash requests of one build. */ +export interface AssetTrashFormat { + /** Entries in a batch trash request. */ + entries: string; + /** Tile in a batch trash entry. */ + tile: string; + /** Trash flag in a batch entry. */ + trashed: string; + /** Timestamp in the batch request. */ + date: string; + /** Trash destination in a batch entry. */ + destination: string; + /** Workflow IDs in a scene clip deletion request. */ + sceneWorkflows: string; +} + +/** Request formats verified for internal Flow operations. */ +export interface FrontendFormats { + /** Direct Flow Agent session and turn operations. */ + agent_chat: AgentChatFormat; + /** Agent references and local media uploads. */ + agent_attachments: AgentAttachmentFormat; + /** Local media uploads to a project library. */ + project_upload: ProjectUploadFormat; + /** Project-level Agent preferences and memory. */ + agent_settings: AgentSettingsFormat; + /** Direct collection writes. */ + collection_write: CollectionWriteFormat; + /** Asset trash through the project store. */ + asset_trash_store: AssetTrashFormat; + /** Character personality note update. */ + character_bio: CharacterBioFormat; +} + +/** Browser exports and service fields for Agent settings. */ +export interface AgentSettingsFormat { + /** Project metadata service's query client. */ + queryClient: string; + /** Project metadata service's request client. */ + requestClient: string; + /** Browser exports for native settings requests. */ + exports: Readonly>; + /** New names for project settings methods and catalogue fields. */ + wire?: AgentSettingsWireFormat; + /** Values that the build keeps inside its modules and does not export. */ + local?: AgentSettingsLocalFormat; +} + +/** Values that the runtime builds for a build with no export for them. */ +export interface AgentSettingsLocalFormat { + /** Query key of the model catalogue. */ + modelKey: readonly unknown[]; + /** Method on the model service that loads the catalogue. */ + fetchModels: string; + /** Fields of the settings update method descriptor. */ + updateMethod: { + /** Plain values by descriptor field. */ + values: Readonly>; + /** Namespace exports by descriptor field. */ + exports: Readonly>; + /** Namespace export with the marker symbol. */ + marker: string; + }; +} + +/** Methods and fields used to read and encode one build's Agent settings. */ +export interface AgentSettingsWireFormat { + /** Method that gets the settings from the metadata response. */ + metadata: string; + /** Method that encodes the request descriptor and message. */ + encode: string; + /** New names of the settings message methods. */ + methods: Readonly>; + /** Model group in the catalogue. */ + groups: string; + /** Image model group. */ + imageModels: string; + /** Video model group. */ + videoModels: string; + /** Account tier defaults in the catalogue. */ + tierDefaults: string; + /** Model list in the options request. */ + families: string; + /** Usage codes in the options filter. */ + usages: string; + /** Model ID in an option. */ + modelId: string; + /** Preferred model ID in the selection request. */ + preferredModel: string; +} + +/** Project page and browser exports for Agent chat. */ +export interface AgentChatFormat { + /** Exported project page component class. */ + page: string; + /** Agent transport service on the project page. */ + transport: string; + /** Angular injector on the project page. */ + injector: string; + /** Exported Agent composer controller. */ + composer: string; + /** Method on the composer that reports whether the page can send. Default `wb`. */ + canSend?: string; + /** Exported permission response service. */ + permissions: string; + /** Exported question response service. */ + questions: string; + /** Signal with the page's project ID. */ + project: string; + /** Lifecycle controller on the project page. */ + lifecycle: string; + /** Destroyed flag on the lifecycle controller. */ + destroyed: string; + /** Browser exports for the native Agent protocol. */ + exports: Readonly>; + /** Changes to the native Agent fields and methods. */ + wire?: AgentWireFormat; +} + +/** Native services and request fields for local media uploads. */ +export interface MediaUploadFormat { + /** Project store on the page component. */ + store: string; + /** Signal with all project tiles. */ + tiles: string; + /** Query that loads the tiles for the active project. */ + tileQuery: string; + /** Project mutation dispatcher. */ + dispatcher: string; + /** Angular injector on the project page. */ + injector: string; + /** Exported upload consent service. */ + consent: string; + /** Functions that the verified build uses for uploads. */ + exports: Readonly>; + /** Fields in the native upload format. */ + fields: MediaUploadFields; +} + +/** Fields in the native request and reply for a local media upload. */ +export interface MediaUploadFields { + /** Accepted files in the validation result. */ + accepted: string; + /** Error messages in the validation result. */ + errors: string; + /** Duration in the video metadata. */ + duration: string; + /** Workflow ID in the upload request. */ + workflow: string; + /** Media ID in the upload request. */ + media: string; + /** Local file in the upload request. */ + file: string; + /** Date in the upload request. */ + date: string; + /** Image dimensions in the upload request. */ + dimensions: string; + /** Completion callbacks in the upload request. */ + completion: string; + /** Project ID in the upload request. */ + project: string; +} + +/** Project page fields and exports for Agent attachments. */ +export interface AgentAttachmentFormat extends MediaUploadFormat { + /** Functions for uploads and Agent message attachments. */ + exports: Readonly>; + /** Fields for uploads and Agent message attachments. */ + fields: AgentAttachmentFields; +} + +/** Additional fields in the Agent attachment protocol. */ +export interface AgentAttachmentFields extends MediaUploadFields { + /** Character ID in a native reference. */ + character: string; + /** Text content in the message request. */ + text: string; + /** Attachment references in the message request. */ + references: string; +} + +/** Project page and upload formats for an independent library upload. */ +export interface ProjectUploadFormat { + /** Class and lifecycle fields of the page that owns the upload services. */ + page: Pick; + /** Native upload fields shared with Agent attachments. */ + media: MediaUploadFormat; +} + +/** Field names for a character personality update. */ +export interface CharacterBioFormat { + /** Character ID in a single-tile request. */ + tileId: string; + /** Change in a single-tile request. */ + tileChange: string; + /** Text in a personality change. */ + notes: string; +} + +/** Field names for the active project store and its tile query. */ +export interface ProjectStoreFormat { + /** Class of the project shell store. */ + storeClass: string; + /** Lifecycle controller on the store. */ + lifecycle: string; + /** Destroyed flag on the lifecycle controller. */ + destroyed: string; + /** Project ID signal. */ + projectId: string; + /** Service that owns the tile query and writes. */ + tilesService: string; + /** Query client on the tile service. */ + queryClient: string; + /** Project mutation dispatcher. */ + dispatcher: string; + /** Tile rows in the query result. */ + rows: string; + /** Signal query that loads the tiles of the active project. */ + tileQuery: string; + /** Mutation runner on the project store. */ + mutator: string; + /** Error observable on the store mutation queue. */ + errorStream: string; + /** Component slots that hold the injected project store. */ + componentSlots: readonly string[]; + /** Angular LView slot on an upgraded LContext wrapper. */ + lContextView: string; + /** Field names of a scene tile and its workflow history. */ + scene?: SceneTileFormat; + /** Native names for mutations that use the general store adapter. */ + mutations?: ProjectMutationFormat; +} + +/** Fields that identify the contents of a scene tile. */ +export interface SceneTileFormat { + /** Clip array on a scene tile. */ + clips: string; + /** Workflow history map on a scene tile. */ + history: string; +} + +/** Names of fields used by the general project mutations. */ +export interface ProjectMutationFormat { + /** Tile ID in a single-tile request. */ + tileId: string; + /** Change in a single-tile request. */ + tileChange: string; + /** Workflow IDs used to create a scene or add clips. */ + sceneWorkflows: string; + /** Collection ID in a scene creation request. */ + sceneCollection: string; + /** Scene tile in a successful creation response. */ + sceneCreated: string; + /** Scene ID in a request to add workflows. */ + sceneId: string; + /** Start time in a video trim request. */ + trimStart: string; + /** End time in a video trim request. */ + trimEnd: string; +} + +/** Verified media payload fields used during snapshot reads. */ +export interface SnapshotMediaFormat { + /** Primary media payload property on an image or video tile. */ + container: string; + /** Direct media URL property on a media payload or history item. */ + url: string; + /** Lifecycle status property on a media payload. */ + status: string; + /** Error payload property on a media payload. */ + error: string; + /** Dimensions object property on a media payload. */ + dimensions: string; + /** Video duration property in seconds on a media payload. */ + duration: string; + /** Creation date property on a tile or media payload. */ + date: string; + /** Boolean property that is true on uploaded media that Flow finished. */ + uploaded: string; + /** Namespace export with the source symbol of uploaded media. */ + uploadSource: string; +} + +/** Verified character tile and entity protobuf fields used during snapshot reads. */ +export interface SnapshotCharacterFormat { + /** Serialized entity message property on a character tile. */ + entity: string; + /** Look workflow map property on a character tile. */ + looks: string; + /** Preview media ID property on a character tile. */ + previewMediaId: string; + /** Protobuf field number for `entity_info` on the entity message. */ + entityInfoField: number; + /** Protobuf field number for `character_info` on `entity_info`. */ + characterInfoField: number; + /** Protobuf field number for `audio_references` on `character_info`. */ + audioReferencesField: number; + /** Protobuf field number for a preset voice ID on an audio reference. */ + presetVoiceField: number; + /** Protobuf field number for a custom voice workflow ID on an audio reference. */ + customVoiceField: number; + /** Protobuf field number for `personality_notes` on `character_info`. */ + notesField: number; +} + +/** Verified tile type discriminants in the project tile store. */ +export interface SnapshotTileTypesFormat { + /** Collection tile type value. */ + collection: string; + /** Asset tile type values included in project asset lists. */ + assets: readonly string[]; + /** Non-asset tile type values excluded from project asset lists and counts. */ + ignored: readonly string[]; +} + +/** Verified account credits service and balance accessors. */ +export interface SnapshotCreditsFormat { + /** Exported credits service class on the Angular frontend namespace. */ + service: string; + /** Signal method returning the spendable total credit balance. */ + total: string; + /** Query property on the credits service. */ + query: string; + /** Method on the credits query message returning total credits. */ + balanceMethod: string; +} + +/** Verified tile fields that every project tile carries. */ +export interface SnapshotTileFormat { + /** Soft-trash flag on a tile. */ + trashed: string; + /** Parent collection ID on a tile. */ + parentCollection: string; +} + +/** Verified trim bounds on a video media payload and scene clip fields. */ +export interface SnapshotTrimFormat { + /** Trim start in seconds on a trimmed video media payload. */ + mediaStart: string; + /** Trim end in seconds on a trimmed video media payload. */ + mediaEnd: string; + /** Start of a scene clip in seconds. */ + clipStart: string; + /** End of a scene clip in seconds. */ + clipEnd: string; + /** Duration of a scene clip in seconds. */ + clipDuration: string; +} + +/** Verified snapshot field map for one frontend build. */ +export interface SnapshotFormat { + /** Tile-level flags and references. */ + tile: SnapshotTileFormat; + /** Trim and scene clip time fields. */ + trim: SnapshotTrimFormat; + /** Media payload and URL properties. */ + media: SnapshotMediaFormat; + /** Character look, preview, and entity properties. */ + character: SnapshotCharacterFormat; + /** Tile type discriminants for assets, collections, and non-asset items. */ + tileTypes: SnapshotTileTypesFormat; + /** Credits service class and balance accessors. */ + credits: SnapshotCreditsFormat; +} + +/** Verified operations and store format of one build. */ +export interface FrontendBuildFields { + /** Layout for the project store. */ + projectStore: ProjectStoreFormat; + /** Snapshot field descriptors for verified store reads. */ + snapshot?: SnapshotFormat; + /** Native fields used to confirm a character voice assignment. */ + voiceConfirmation?: VoiceConfirmationFormat; + /** Native fields of the character preview panel and controls. */ + characterPreview?: CharacterPreviewFormat; + /** Native fields of the character voice form. */ + characterVoice?: CharacterVoiceFormat; + /** Native fields for character creation and store lifecycle checks. */ + characterCreate?: CharacterCreateFormat; + /** Native fields of editable project titles. */ + projectTitle?: ProjectTitleFormat; +} + +/** A verified build with full or pre-Agent operation coverage. */ +export type FrontendBuild = FrontendBuildFields & ( + | { legacy?: false; operations: FrontendFormats } + | { legacy: true; operations: Pick & Partial } +); + +/** Native methods of the character preview panel and look controls. */ +export interface CharacterPreviewFormat { + /** Lifecycle controller on the panel. */ + lifecycle: string; + /** Destroyed flag on the lifecycle controller. */ + destroyed: string; + /** Method that opens the native file picker for the active slot. */ + upload: string; + /** Method that identifies the preview panel. */ + marker: string; + /** Signal with the portrait media record. */ + portrait: string; + /** Signal with the body media record. */ + body: string; + /** Signal with the active slot image URL. */ + source: string; + /** Signal that reports whether the preview is busy. */ + busy: string; + /** Footer signal that reports whether look generation is busy. */ + footerBusy: string; + /** Popover method that lists project assets in the add menu. */ + pickerAssets: string; + /** Popover method that selects a project asset in the add menu. */ + pickerSelect: string; +} + +/** Native signals and outputs of the character voice form. */ +export interface CharacterVoiceFormat { + /** Lifecycle controller on the form component. */ + lifecycle: string; + /** Destroyed flag on the lifecycle controller. */ + destroyed: string; + /** Signal with the loaded voice map. */ + voiceMap: string; + /** Signal with the selected voice ID. */ + selectedVoice: string; + /** Signal with the selected raw voice entry. */ + selectedRecord: string; + /** Output emitter that commits a voice change. */ + changeEmitter: string; + /** Signal that reports whether the form is busy, when the build has one. */ + busy?: string; + /** True when the build keeps the form voice map empty while idle. */ + emptyMap: boolean; +} + +/** Field names for character creation and store lifecycle checks. */ +export interface CharacterCreateFormat { + /** Lifecycle controller on the bound store service. */ + lifecycle: string; + /** Destroyed flag on the lifecycle controller. */ + destroyed: string; + /** Entity kind fields set to `1` in a `create_entity` request. */ + entityKinds: readonly string[]; + /** Collection fields set to `undefined` in a `create_entity` request. */ + collections: readonly string[]; + /** Completion callback fields in a `create_entity` request. */ + completions: readonly string[]; + /** Created tile fields in a `create_entity` response. */ + created: readonly string[]; +} + +/** Native fields of `flow-editable-text` used to commit a project title. */ +export interface ProjectTitleFormat { + /** Output emitter that commits the edited title text. */ + saveEmitter: string; + /** Signal that sets the component back to viewing mode. */ + stateSignal: string; +} + +/** Character editor and query fields used to read the saved voice. */ +export interface VoiceConfirmationFormat { + /** Exported character editor class. */ + editor: string; + /** Query that loads the character entity. */ + entityQuery: string; + /** Editor method that reads the voice ID from that entity. */ + savedVoice: string; + /** Form method that reads the locally selected voice ID. */ + selectedVoice: string; + /** Event that reports the saved voice media and workflow IDs. */ + previewSaved: string; + /** Signal with the voice that the picker will add to the character. */ + pickerSelection: string; +} diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..7779fab 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,7 +8,7 @@ import { findRouter, navigateSpa, readOwn, - type NgContextCarrier, + resolveLView, } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; import { clearStore } from "./state"; @@ -119,7 +119,7 @@ export async function openEditAsset( } } } - const ng = (el as NgContextCarrier).__ngContext__; + const ng = resolveLView(el); if (Array.isArray(ng)) { for (let i = 0; i < ng.length; i++) { const item = ng[i]; diff --git a/ts/project_store.ts b/ts/project_store.ts index 983195b..6a8fc0b 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -3,10 +3,16 @@ // 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, readBuildLabel, withMutationAliases } from "./frontend_builds"; +import { + activeProjectStoreFormat, + projectStoreFormats, + readBuildLabel, + 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"; @@ -167,11 +173,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, @@ -257,7 +258,6 @@ async function dispatchStoreMutation( rawPayload: Record, ): Promise { if (!activeProjectStoreFormat()) { - clearProjectStore(); throw new Error("unsupported_front_end"); } if (activeBoundStore() !== store || !isCurrent(store)) { @@ -315,16 +315,30 @@ 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. */ @@ -334,23 +348,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; @@ -359,41 +377,55 @@ 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()) { + if (projectInRoute() !== projectId) return { ok: false, error: "project_changed", build }; + if (hasNoCascadedStoreClasses()) { 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" }; + 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 }; + 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()) { + if (projectInRoute() !== projectId) return { ok: false, error: "project_changed", build }; + if (hasNoCascadedStoreClasses()) { 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(); @@ -412,8 +444,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); @@ -443,6 +475,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..7c9690f 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,9 +350,15 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { (titleInput.value || "").trim() !== desired) ) { try { - const lv = resolveLView(host); - if (Array.isArray(lv)) { - const titleFormat = projectTitleFormat(); + if ( + !(runtimeState.ngLViewMap instanceof Map) && + typeof (host as NgContextCarrier).__ngContext__ === "number" + ) { + await withLViewMapCapture(() => hoverProbe([host])); + } + 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 } @@ -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 ff0c6fb..f27c82d 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 { activeProjectStoreFormat, 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, @@ -183,10 +184,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; @@ -212,6 +209,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_ops.ts b/ts/scene_ops.ts index 58c1cb7..889f201 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -8,7 +8,6 @@ import { delay, findMediaContainer, isTrashedTile, legacyTile } from "./dom"; import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; import { beginProjectMutation, - clearProjectStore, currentProjectStore, fetchProjectStore, projectMutationPending, @@ -168,7 +167,6 @@ function sceneClipsConfirmed( export async function sceneOp(req: SceneOpRequest): Promise { const build = readBuildLabel(); if (!activeProjectStoreFormat()) { - clearProjectStore(); return { ok: false, error: "unsupported_front_end", build }; } const helper = runtimeState.store; diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..4961905 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -4,12 +4,12 @@ // 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. */ +/** Returns the clip list and history of a scene in the active or bound store build. */ export function sceneContents(tile: FlowTile) { - const format = frontendBuild(readBuildLabel())?.projectStore.scene; + const format = sceneTileFormat(); 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 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 4a7c450..24680e5 100644 --- a/ts/tile_dom.ts +++ b/ts/tile_dom.ts @@ -3,10 +3,27 @@ // 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 { + isAngularSignal, + readOwn, + resolveLView, + withLViewMapCapture, + type NgContextCarrier, +} from "./angular"; +import { + collectionIdOf, + delay, + dismissOverlay, + elText, + hoverProbe, + isTrashedTile, + isVisibleEnabled, + legacyTile, +} from "./dom"; +import { tileSlotKeys } from "./frontend_builds"; 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 +52,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 allow-listed Angular 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 tileSlotKeys()) { + 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 && isAngularSignal(val)) { + try { + if (objectMatchesTile(val.call(slot), id, target)) return true; + } catch { + // Ignore unset Angular required input signals. + } + } + } + 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 +242,126 @@ 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; +} + +/** 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) + .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 (buttonPattern.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 +390,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(id); if (action === "dismiss") { await dismissOverlay(); return { ok: true }; diff --git a/ts/types.ts b/ts/types.ts index 6e1c59b..8e2d9b1 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -520,6 +520,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`. */ @@ -574,7 +576,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; @@ -687,6 +689,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. */ @@ -763,7 +767,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) {