diff --git a/src/agent.rs b/src/agent.rs index ffa450c..28aa0fb 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -379,21 +379,37 @@ impl AgentPage { self.page.navigate(&route).await?; self.project_id.clear(); let mut last = Value::Null; - for _ in 0..BIND_ATTEMPTS { + for attempt in 0..BIND_ATTEMPTS { if let Ok(status) = self.page.call("agentStatus", json!([project_id])).await { if status["ok"].as_bool() == Some(true) { if self.page.bind_agent(project_id).await? { self.project_id = project_id.to_string(); return Ok(()); } + if attempt >= 8 + && let Ok(ui) = self.page.call("agentUiBind", json!([project_id])).await + && ui["ok"].as_bool() == Some(true) + { + self.project_id = project_id.to_string(); + return Ok(()); + } } else if status["error"].as_str() == Some("unsupported_front_end") { - checked_runtime_result(status)?; + if let Ok(ui) = self.page.call("agentUiBind", json!([project_id])).await + && ui["ok"].as_bool() == Some(true) + { + self.project_id = project_id.to_string(); + return Ok(()); + } + last = status; } else { last = status; } } sleep(BIND_INTERVAL).await; } + if last["error"].as_str() == Some("unsupported_front_end") { + return checked_runtime_result(last).map(|_| ()); + } anyhow::bail!( "Cannot open the Flow Agent page. Check Flow sign-in and project access. {last}" ); diff --git a/src/assets.rs b/src/assets.rs index d2ace78..6e30879 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -14,12 +14,16 @@ use std::collections::HashMap; use tokio::sync::broadcast::error::RecvError; use tokio::time::{Duration, Instant}; +use crate::characters::{exit_character_editor, open_character_editor}; use crate::collections::{FlowCollection, find_collection}; +use crate::collections_ui::{delete_collection_ui, is_collection_ui, rename_collection_ui}; use crate::db::FlowDb; use crate::download::eval_resolve_media_url; use crate::engine::ChromeEngine; -use crate::project::{ensure_flow_store, is_flow_mutation_rpc_ok, read_snapshot}; -use crate::project_store::ProjectStoreSession; +use crate::project::{ + ensure_flow_store_or_dom, is_flow_mutation_rpc_ok, project_id_from_url, read_snapshot, +}; +use crate::project_store::{ProjectStoreSession, can_use_ui_fallback}; use crate::tile_menu::{rename_through_menu, tile_state, trash_through_menu}; /// Maximum number of URL lookups that can run at the same time. @@ -383,34 +387,78 @@ fn snapshot_has_renamed(snap: &Value, id: &str, name: &str) -> bool { }) } -/// Renames collections through the collection store and other tiles through the page or store. +/// Renames a character tile by opening the character editor page and updating its display name. +async fn rename_character_via_editor( + engine: &ChromeEngine, + character_id: &str, + name: &str, +) -> Result { + let cur_url = engine.current_url().await.unwrap_or_default(); + let Some(pid) = project_id_from_url(&cur_url) else { + return Ok(false); + }; + open_character_editor(engine, &cur_url, &pid, character_id).await?; + let res = engine + .call_flow_async( + "characterOp", + json!([{ + "action": "update", + "character_id": character_id, + "name": name, + }]), + ) + .await; + exit_character_editor(engine, Some(&pid)).await; + Ok(res?.get("ok").and_then(Value::as_bool) == Some(true)) +} + +/// Renames collections through the collection store or UI, 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?; + let collections = match ProjectStoreSession::open(engine).await { + Ok(session) => Some(session), + Err(err) if can_use_ui_fallback(&err) => None, + Err(err) => return Err(err), + }; + let initial_snap = read_snapshot(engine).await.ok(); let total = items.len(); let mut renamed = Vec::new(); let mut failed = Vec::new(); - let mut asset_store_ready = false; + let mut store_bound = false; + let mut store_checked = false; 'items: for (idx, entry) in items.into_iter().enumerate() { - match collections.is_collection(&entry.id).await { - Ok(false) => {} - Ok(true) => { - match collections.rename(&entry.id, &entry.name).await { - Ok(result) => renamed.push(json!({ - "id": entry.id, "name": entry.name, "method": result["method"] - })), - Err(err) => failed.push(rename_error(&entry, &err)), + let is_col = if let Some(session) = &collections { + match session.is_collection(&entry.id).await { + Ok(flag) => flag, + Err(err) if can_use_ui_fallback(&err) => { + is_collection_ui(engine, &entry.id).await.unwrap_or(false) + } + Err(err) => { + failed.push(rename_error(&entry, &err)); + continue 'items; } - continue 'items; } - Err(err) => { - failed.push(rename_error(&entry, &err)); - continue 'items; + } else { + is_collection_ui(engine, &entry.id).await.unwrap_or(false) + }; + if is_col { + let res = if let Some(session) = &collections { + session.rename(&entry.id, &entry.name).await + } else { + rename_collection_ui(engine, &entry.id, &entry.name).await + }; + match res { + Ok(result) => renamed.push(json!({ + "id": entry.id, "name": entry.name, "method": result["method"] + })), + Err(err) => failed.push(rename_error(&entry, &err)), } + continue 'items; } - if !asset_store_ready { - ensure_flow_store(engine).await?; - asset_store_ready = true; + + if !store_checked { + store_bound = ensure_flow_store_or_dom(engine).await?; + store_checked = true; } // Use the rename control of the page first. The page then builds its own mutation. if tile_state(engine, &entry.id).await.is_present() @@ -425,6 +473,38 @@ pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec } continue 'items; } + + let is_character = initial_snap + .as_ref() + .and_then(|s| s.get("assets")) + .and_then(Value::as_array) + .is_some_and(|arr| { + arr.iter().any(|a| { + a.get("id").and_then(Value::as_str) == Some(entry.id.as_str()) + && a.get("kind").and_then(Value::as_str) == Some("character") + }) + }); + + if !store_bound { + if is_character + && matches!( + rename_character_via_editor(engine, &entry.id, &entry.name).await, + Ok(true) + ) + { + renamed.push( + json!({ "id": entry.id, "name": entry.name, "method": "ui:character_editor" }), + ); + } else { + failed.push(json!({ + "id": entry.id, + "name": entry.name, + "error": "tile rename menu unavailable and project store not bound", + })); + } + continue 'items; + } + let mut ok = false; for attempt in 0..2 { // Subscribe before calling rename so the listener catches store RPC responses. @@ -440,6 +520,19 @@ pub(crate) async fn rename_assets(engine: &ChromeEngine, items: Vec ) .await?; if let Some(e) = res.get("err").and_then(|v| v.as_str()) { + if is_character + && matches!( + rename_character_via_editor(engine, &entry.id, &entry.name).await, + Ok(true) + ) + { + renamed.push(json!({ + "id": entry.id, + "name": entry.name, + "method": "ui:character_editor", + })); + continue 'items; + } failed.push(json!({ "id": entry.id, "name": entry.name, "error": e })); continue 'items; } @@ -514,23 +607,30 @@ fn rename_error(entry: &RenameEntry, err: &anyhow::Error) -> Value { /// Moves an asset to trash through the tile menu or the pinned project store. async fn invoke_trash_tile( engine: &ChromeEngine, - session: &ProjectStoreSession<'_>, + session: Option<&ProjectStoreSession<'_>>, 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 { - Ok(true) => { - return Ok( - json!({ "ok": true, "method": "menu:move_to_trash", "confirmed": true }), - ); - } - Ok(false) => None, - Err(err) => Some(format!("{err:#}")), + let menu_error = if ensure_flow_store_or_dom(engine).await.is_ok() + && tile_state(engine, id).await.is_present() + { + match trash_through_menu(engine, id).await { + Ok(true) => { + return Ok( + json!({ "ok": true, "method": "menu:move_to_trash", "confirmed": true }), + ); } - } else { - None - }; + Ok(false) => None, + Err(err) => Some(format!("{err:#}")), + } + } else { + None + }; + let Some(session) = session else { + anyhow::bail!( + "Could not move tile '{id}' to trash through the workspace menu{}", + menu_error.map(|e| format!(" ({e})")).unwrap_or_default() + ); + }; let mut result = session .call("trashAssetOp", json!(id), Some("trash asset")) .await?; @@ -542,32 +642,69 @@ 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 Flow menu or store. pub(crate) async fn trash_asset( engine: &ChromeEngine, db: &FlowDb, match_str: &str, ) -> Result { - let collections = ProjectStoreSession::open(engine).await?; + let collections = match ProjectStoreSession::open(engine).await { + Ok(session) => Some(session), + Err(err) if can_use_ui_fallback(&err) => None, + Err(err) => return Err(err), + }; let query = match_str.trim(); - if collections.is_collection(query).await? { - return collections.delete(query).await; + let direct_col = if let Some(session) = &collections { + match session.is_collection(query).await { + Ok(flag) => flag, + Err(err) if can_use_ui_fallback(&err) => is_collection_ui(engine, query).await?, + Err(err) => return Err(err), + } + } else { + is_collection_ui(engine, query).await? + }; + if direct_col { + return if let Some(session) = &collections { + session.delete(query).await + } else { + delete_collection_ui(engine, query).await + }; } - let mut tiles = collections - .run_collections(json!({ "action": "assets" })) - .await?; - let assets: Vec = serde_json::from_value(tiles["assets"].take())?; + let mut tiles = if let Some(session) = &collections { + match session.run_collections(json!({ "action": "assets" })).await { + Ok(val) => val, + Err(err) if can_use_ui_fallback(&err) => read_snapshot(engine).await?, + Err(err) => return Err(err), + } + } else { + read_snapshot(engine).await? + }; + let assets: Vec = serde_json::from_value( + tiles + .get_mut("assets") + .map(Value::take) + .unwrap_or_else(|| Value::Array(Vec::new())), + )?; let Some(asset) = match_asset(&assets, query, true) else { - let summaries: Vec = serde_json::from_value(tiles["collections"].take())?; + let summaries: Vec = serde_json::from_value( + tiles + .get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| Value::Array(Vec::new())), + )?; let collection = find_collection(&summaries, query, true)? .with_context(|| format!("No asset or collection matches '{query}' for flow_trash"))?; - return collections.delete(&collection.id).await; + return if let Some(session) = &collections { + session.delete(&collection.id).await + } else { + delete_collection_ui(engine, &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, collections.as_ref(), 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..5a2f6a5 100644 --- a/src/character_bio.rs +++ b/src/character_bio.rs @@ -1,15 +1,42 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Direct project store operations for character personality notes. +//! Direct project store and character editor UI operations for character personality notes. use anyhow::{Context, Result}; -use serde_json::json; +use serde_json::{Value, json}; -use crate::assets::{FlowAsset, match_asset}; +use crate::assets::{FlowAsset, list_assets_with_project, match_asset}; +use crate::characters::{exit_character_editor, open_character_editor}; use crate::db::FlowDb; use crate::engine::ChromeEngine; -use crate::project_store::ProjectStoreSession; +use crate::project::project_id_from_url; +use crate::project_store::{ProjectStoreSession, can_use_ui_fallback}; + +/// Opens a verified direct store session for personality notes, or returns `Ok(None)` when UI fallback should be used. +pub(crate) async fn open_character_bio_store<'a>( + engine: &'a ChromeEngine, + project_id: Option<&str>, +) -> Result>> { + match ProjectStoreSession::open(engine).await { + Ok(store) => { + anyhow::ensure!( + 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 can_use_ui_fallback(&err) => Ok(None), + Err(err) => Err(err), + } + } + Err(err) if can_use_ui_fallback(&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,24 +54,102 @@ pub(crate) async fn set_character_bio( Ok(()) } -/// Finds a character for an edit and saves its notes without opening the editor. +/// Opens the character editor page, writes personality notes into the editor UI, and returns to the workspace. +pub(crate) async fn set_character_bio_ui( + engine: &ChromeEngine, + project_id: Option<&str>, + character_id: &str, + bio: &str, +) -> Result<()> { + let cur_url = engine.current_url().await.unwrap_or_default(); + let url_pid = project_id_from_url(&cur_url); + let pid = project_id + .or(url_pid.as_deref()) + .context("Missing project ID for character editor UI")?; + open_character_editor(engine, &cur_url, pid, character_id).await?; + let res = engine + .call_flow_async( + "characterOp", + json!([{ + "action": "update", + "character_id": character_id, + "bio": bio, + }]), + ) + .await; + exit_character_editor(engine, Some(pid)).await; + let res = res?; + if res.get("ok").and_then(Value::as_bool) != Some(true) { + anyhow::bail!( + "Failed to update personality notes for '{character_id}' via UI: {}", + res.get("error") + .and_then(Value::as_str) + .unwrap_or("unknown") + ); + } + Ok(()) +} + +/// Finds a character and saves its notes through the direct store or character editor UI fallback. pub(crate) async fn edit_character_bio( engine: &ChromeEngine, db: &FlowDb, selector: &str, bio: &str, ) -> Result { - let store = ProjectStoreSession::open(engine).await?; - let mut result = store - .call("characterBioOp", json!({ "action": "list" }), None) - .await?; - let assets: Vec = serde_json::from_value(result["characters"].take())?; - let target = match_asset(&assets, selector, false) + let fallback_to_ui = 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).with_context(|| { + format!("No character matches '{selector}' in active project") + })?; + match set_character_bio(&store, &target.id, bio).await { + Ok(()) => { + db.upsert_character( + target.id.clone(), + Some(store.project_id().to_owned()), + target.name.clone(), + Some(bio.to_owned()), + None, + None, + ) + .await?; + return Ok(target.id.clone()); + } + Err(err) if can_use_ui_fallback(&err) => true, + Err(err) => return Err(err), + } + } + Err(err) if can_use_ui_fallback(&err) => true, + Err(err) => return Err(err), + } + } + Err(err) if can_use_ui_fallback(&err) => true, + Err(err) => return Err(err), + }; + + if !fallback_to_ui { + anyhow::bail!("Could not update character personality notes"); + } + + let snap = list_assets_with_project(engine).await?; + let chars: Vec = snap + .assets + .into_iter() + .filter(|a| a.kind == "character") + .collect(); + let target = match_asset(&chars, selector, false) .with_context(|| format!("No character matches '{selector}' in active project"))?; - set_character_bio(&store, &target.id, bio).await?; + set_character_bio_ui(engine, snap.project_id.as_deref(), &target.id, bio).await?; db.upsert_character( target.id.clone(), - Some(store.project_id().to_owned()), + snap.project_id, target.name.clone(), Some(bio.to_owned()), None, diff --git a/src/characters.rs b/src/characters.rs index d30614d..c083067 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -11,16 +11,16 @@ use std::collections::HashMap; use tokio::time::{Duration, Instant}; use crate::assets::{FlowAsset, list_assets_with_project, match_asset, trash_asset}; -use crate::character_bio::{edit_character_bio, set_character_bio}; +use crate::character_bio::{edit_character_bio, open_character_bio_store, set_character_bio}; 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, + ensure_flow_store, ensure_flow_store_or_dom, ensure_project_workspace_root, + project_id_from_url, project_subroute_url, project_workspace_url, }; -use crate::project_store::ProjectStoreSession; +use crate::project_store::can_use_ui_fallback; use crate::queue::{ProgressCallback, SceneParams}; use crate::voices::{ VoiceRequest, apply_voice_with_fallback, delete_portrait, list_all_voices, scene_voice, @@ -393,20 +393,12 @@ pub(crate) async fn create_or_update_character_job( validate_local_files(scene.refs.as_deref(), "Character reference image").await?; ensure_project_workspace_root(engine).await?; - ensure_flow_store(engine).await?; + ensure_flow_store_or_dom(engine).await?; let snap = list_assets_with_project(engine).await?; 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_character_bio_store(engine, project_id.as_deref()).await? } else { None }; @@ -450,10 +442,13 @@ pub(crate) async fn create_or_update_character_job( .map(str::to_string) .ok_or_else(|| anyhow::anyhow!("Character creation returned no character ID"))?; + let mut ui_bio = effective_bio.as_deref(); if let (Some(store), Some(bio)) = (bio_store.take(), effective_bio.as_deref()) { - set_character_bio(&store, &cid, bio).await.map_err(|err| { - anyhow::anyhow!("Failed to save personality notes for '{cid}': {err:#}") - })?; + match set_character_bio(&store, &cid, bio).await { + Ok(()) => ui_bio = None, + Err(err) if can_use_ui_fallback(&err) => {} + Err(err) => anyhow::bail!("Failed to save personality notes for '{cid}': {err:#}"), + } } let need_update_on_page = res @@ -461,7 +456,7 @@ pub(crate) async fn create_or_update_character_job( .and_then(|v| v.as_bool()) .unwrap_or(false); let mut submitted_meta = None; - editor_opened = need_update_on_page || has_refs; + editor_opened = need_update_on_page || has_refs || ui_bio.is_some(); if editor_opened { let cur_url = engine.current_url().await.unwrap_or_default(); let fallback_pid = project_id_from_url(&cur_url); @@ -470,6 +465,14 @@ pub(crate) async fn create_or_update_character_job( .or(fallback_pid.as_deref()) .ok_or_else(|| anyhow::anyhow!("Missing project ID for character route"))?; open_character_editor(engine, &cur_url, pid, &cid).await?; + if let Some(bio) = ui_bio { + let _ = engine + .call_flow_async( + "characterOp", + json!([{ "action": "update", "character_id": cid, "bio": bio }]), + ) + .await?; + } if need_update_on_page { let media_res = apply_character_page_media( @@ -518,8 +521,13 @@ 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)); + let mut ui_bio = effective_bio.as_deref(); if let (Some(store), Some(bio)) = (bio_store.take(), effective_bio.as_deref()) { - set_character_bio(&store, &target.id, bio).await?; + match set_character_bio(&store, &target.id, bio).await { + Ok(()) => ui_bio = None, + Err(err) if can_use_ui_fallback(&err) => {} + Err(err) => return Err(err), + } } editor_opened = true; @@ -527,6 +535,7 @@ pub(crate) async fn create_or_update_character_job( "action": "update", "character_id": target.id, "name": scene.new_name, + "bio": ui_bio, }); let mut res = engine .call_flow_async("characterOp", json!([payload.clone()])) diff --git a/src/collections.rs b/src/collections.rs index a2a2f16..db69d27 100644 --- a/src/collections.rs +++ b/src/collections.rs @@ -1,25 +1,26 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Collection operations on the active Google Flow project store. +//! Collection operations on the active Google Flow project store with workspace UI fallbacks. use anyhow::{Context, Result}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use crate::collections_ui::{delete_collection_ui, handle_collections_ui, rename_collection_ui}; use crate::engine::ChromeEngine; -use crate::project_store::ProjectStoreSession; +use crate::project_store::{ProjectStoreSession, can_use_ui_fallback}; /// Collection summary in the active Flow project. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct FlowCollection { /// Collection tile ID. pub(crate) id: String, /// Collection display name. pub(crate) name: String, /// Asset count in this collection. - count: usize, + pub(crate) count: usize, } /// Parameters for `flow_collections`. @@ -65,16 +66,30 @@ impl ProjectStoreSession<'_> { Ok(res.get("collection").and_then(Value::as_bool) == Some(true)) } - /// Requests a verified rename for a collection ID. + /// Requests a verified rename for a collection ID, falling back to the tile menu on unverified shapes. pub(crate) async fn rename(&self, id: &str, name: &str) -> Result { - self.run_collections(json!({ "action": "rename", "id": id, "name": name })) + match self + .run_collections(json!({ "action": "rename", "id": id, "name": name })) .await + { + Ok(val) => Ok(val), + Err(err) if can_use_ui_fallback(&err) => { + rename_collection_ui(self.engine(), id, name).await + } + Err(err) => Err(err), + } } - /// Requests deletion of a collection ID through the collection path. + /// Requests deletion of a collection ID, falling back to the workspace menu when direct delete is unavailable. pub(crate) async fn delete(&self, id: &str) -> Result { - self.run_collections(json!({ "action": "delete", "id": id })) + match self + .run_collections(json!({ "action": "delete", "id": id })) .await + { + Ok(val) => Ok(val), + Err(err) if can_use_ui_fallback(&err) => delete_collection_ui(self.engine(), id).await, + Err(err) => Err(err), + } } /// Resolves an existing collection or creates and verifies a new one. @@ -184,12 +199,11 @@ fn move_ids(ids: Option>, action: &str) -> Result> { }) } -/// Dispatches the six actions of `flow_collections`. -pub(crate) async fn handle_collections( - engine: &ChromeEngine, +/// Runs one `flow_collections` action against an open direct store session. +async fn handle_collections_store( + session: &ProjectStoreSession<'_>, req: CollectionsParams, ) -> Result { - let session = ProjectStoreSession::open(engine).await?; match req.action.as_str() { "list" => Ok(json!({ "collections": session.list().await? })), "create" => { @@ -205,7 +219,7 @@ pub(crate) async fn handle_collections( let to = req.to.context("flow_collections rename requires 'to'")?; let to = to.trim(); anyhow::ensure!(!to.is_empty(), "Target collection name must not be empty"); - let id = require_collection(&session, &from).await?; + let id = require_collection(session, &from).await?; let mut result = session.rename(&id, to).await?; result["renamed"] = json!(true); result["from"] = json!(from); @@ -231,9 +245,28 @@ pub(crate) async fn handle_collections( .or(req.name) .or(req.from) .context("flow_collections delete requires 'collection', 'name', or 'from'")?; - let id = require_collection(&session, &target).await?; + let id = require_collection(session, &target).await?; session.delete(&id).await } other => anyhow::bail!("Unknown collections action: {other}"), } } + +/// Dispatches the six actions of `flow_collections`, falling back to workspace UI when direct store access is unavailable. +pub(crate) async fn handle_collections( + engine: &ChromeEngine, + req: CollectionsParams, +) -> Result { + match ProjectStoreSession::open(engine).await { + Ok(session) => match handle_collections_store(&session, req.clone()).await { + Ok(val) => Ok(val), + Err(err) if can_use_ui_fallback(&err) => { + drop(session); + handle_collections_ui(engine, req).await + } + Err(err) => Err(err), + }, + Err(err) if can_use_ui_fallback(&err) => handle_collections_ui(engine, req).await, + Err(err) => Err(err), + } +} diff --git a/src/collections_ui.rs b/src/collections_ui.rs new file mode 100644 index 0000000..0f9b0a9 --- /dev/null +++ b/src/collections_ui.rs @@ -0,0 +1,266 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +//! Workspace UI fallbacks for collection listing, creation, renaming, membership, and deletion. + +use anyhow::{Context, Result}; +use serde_json::{Value, json}; + +use crate::assets::FlowAsset; +use crate::collections::{CollectionsParams, FlowCollection, find_collection}; +use crate::engine::ChromeEngine; +use crate::project::read_snapshot; +use crate::tile_menu::{ + create_collection_through_ui, move_tile_collection_through_menu, + rename_collection_through_page, rename_through_menu, trash_through_menu, +}; + +/// Reads the active collections from a store or DOM snapshot. +pub(crate) async fn list_collections_ui(engine: &ChromeEngine) -> Result> { + let mut snap = read_snapshot(engine).await?; + let raw = snap + .get_mut("collections") + .map(Value::take) + .unwrap_or_else(|| Value::Array(Vec::new())); + Ok(serde_json::from_value(raw)?) +} + +/// Returns true when `id` matches a collection in the current snapshot. +pub(crate) async fn is_collection_ui(engine: &ChromeEngine, id: &str) -> Result { + let cols = list_collections_ui(engine).await?; + Ok(cols.iter().any(|c| c.id == id)) +} + +/// Resolves an existing collection by `name` or creates a new collection through the workspace UI. +pub(crate) async fn create_collection_ui(engine: &ChromeEngine, name: &str) -> Result { + let name = name.trim(); + anyhow::ensure!(!name.is_empty(), "Collection name must not be empty"); + let collections = list_collections_ui(engine).await?; + let mut exact = collections + .iter() + .filter(|c| c.name.eq_ignore_ascii_case(name)); + if let Some(first) = exact.next() { + anyhow::ensure!( + exact.next().is_none(), + "ambiguous_collection: More than one collection matches '{name}'. Use a collection ID." + ); + return Ok(json!({ + "created": false, + "collection": first, + "collections": collections, + })); + } + + let created_id = create_collection_through_ui(engine, name) + .await? + .with_context(|| { + format!("Could not create collection '{name}' through the workspace UI") + })?; + let updated = list_collections_ui(engine).await?; + let collection = updated + .iter() + .find(|c| c.id == created_id) + .cloned() + .unwrap_or(FlowCollection { + id: created_id.clone(), + name: name.to_string(), + count: 0, + }); + Ok(json!({ + "id": created_id, + "created": true, + "method": "ui:create_collection", + "collection": collection, + "collections": updated, + })) +} + +/// Renames collection `id` to `name` through the workspace tile menu or collection page header. +pub(crate) async fn rename_collection_ui( + engine: &ChromeEngine, + id: &str, + name: &str, +) -> Result { + let name = name.trim(); + anyhow::ensure!(!name.is_empty(), "Target collection name must not be empty"); + let current = list_collections_ui(engine) + .await + .ok() + .and_then(|cols| cols.into_iter().find(|c| c.id == id).map(|c| c.name)) + .unwrap_or_default(); + let mut method = "menu:rename"; + let mut ok = rename_through_menu(engine, id, name).await?; + if !ok && !current.is_empty() { + ok = rename_collection_through_page(engine, id, ¤t, name).await?; + if ok { + method = "page:title"; + } + } + anyhow::ensure!( + ok, + "Could not rename collection '{id}' through the workspace menu" + ); + let collections = list_collections_ui(engine).await?; + Ok(json!({ + "id": id, + "name": name, + "method": method, + "confirmed": true, + "collections": collections, + })) +} + +/// Moves `ids` into collection `target` (creating it if needed) or out to the project root (`None`). +pub(crate) async fn move_assets_ui( + engine: &ChromeEngine, + ids: Vec, + target: Option<&str>, +) -> Result { + anyhow::ensure!(!ids.is_empty(), "At least one asset ID is required"); + let (target_id, target_name) = if let Some(raw_target) = target { + let trimmed = raw_target.trim(); + anyhow::ensure!(!trimmed.is_empty(), "Collection name must not be empty"); + let collections = list_collections_ui(engine).await?; + if let Some(col) = find_collection(&collections, trimmed, false)? { + (Some(col.id.clone()), Some(col.name.clone())) + } else { + let created = create_collection_ui(engine, trimmed).await?; + let cid = created + .get("id") + .or_else(|| created.pointer("/collection/id")) + .and_then(Value::as_str) + .context("UI collection creation did not return a collection ID")? + .to_string(); + (Some(cid), Some(trimmed.to_string())) + } + } else { + (None, None) + }; + + for id in &ids { + let moved = move_tile_collection_through_menu( + engine, + id, + target_id.as_deref(), + target_name.as_deref(), + ) + .await?; + anyhow::ensure!( + moved, + "Could not move tile '{id}' through the workspace collection menu" + ); + } + + let collections = list_collections_ui(engine).await?; + Ok(json!({ + "moved": ids.len(), + "ids": ids, + "collection": target_id, + "method": "menu:move_collection", + "confirmed": true, + "collections": collections, + })) +} + +/// Empties any member tiles from collection `id` and deletes the folder through its menu. +pub(crate) async fn delete_collection_ui(engine: &ChromeEngine, id: &str) -> Result { + let snap = read_snapshot(engine).await?; + let assets: Vec = serde_json::from_value( + snap.get("assets") + .cloned() + .unwrap_or_else(|| Value::Array(Vec::new())), + )?; + let members: Vec = assets + .into_iter() + .filter(|a| a.collection_id.as_deref() == Some(id)) + .map(|a| a.id) + .collect(); + for member_id in &members { + let moved = move_tile_collection_through_menu(engine, member_id, None, None).await?; + anyhow::ensure!( + moved, + "Could not move member asset '{member_id}' out of collection '{id}' before deletion" + ); + } + + let trashed = trash_through_menu(engine, id).await?; + anyhow::ensure!( + trashed, + "Could not delete collection '{id}' through the workspace menu" + ); + let collections = list_collections_ui(engine).await.unwrap_or_default(); + Ok(json!({ + "id": id, + "deleted": true, + "unassigned": members.len(), + "method": "menu:delete_collection", + "confirmed": true, + "collections": collections, + })) +} + +/// Resolves a collection ID by exact ID or unambiguous name from the UI snapshot. +async fn require_collection_ui(engine: &ChromeEngine, query: &str) -> Result { + let collections = list_collections_ui(engine).await?; + Ok(find_collection(&collections, query.trim(), false)? + .with_context(|| format!("Collection not found: {query}"))? + .id + .clone()) +} + +/// Dispatches `flow_collections` actions through workspace UI fallbacks. +pub(crate) async fn handle_collections_ui( + engine: &ChromeEngine, + req: CollectionsParams, +) -> Result { + match req.action.as_str() { + "list" => Ok(json!({ "collections": list_collections_ui(engine).await? })), + "create" => { + let name = req + .name + .context("flow_collections create requires 'name'")?; + create_collection_ui(engine, &name).await + } + "rename" => { + let from = req + .from + .context("flow_collections rename requires 'from'")?; + let to = req.to.context("flow_collections rename requires 'to'")?; + let to = to.trim(); + anyhow::ensure!(!to.is_empty(), "Target collection name must not be empty"); + let id = require_collection_ui(engine, &from).await?; + let mut result = rename_collection_ui(engine, &id, to).await?; + result["renamed"] = json!(true); + result["from"] = json!(from); + result["to"] = json!(to); + Ok(result) + } + "add" => { + let target = req + .collection + .context("flow_collections add requires 'collection'")?; + let ids = req + .ids + .filter(|v| !v.is_empty()) + .context("flow_collections add requires at least one asset ID in 'ids'")?; + move_assets_ui(engine, ids, Some(&target)).await + } + "remove" => { + let ids = req + .ids + .filter(|v| !v.is_empty()) + .context("flow_collections remove requires at least one asset ID in 'ids'")?; + move_assets_ui(engine, ids, None).await + } + "delete" => { + let target = req + .collection + .or(req.name) + .or(req.from) + .context("flow_collections delete requires 'collection', 'name', or 'from'")?; + let id = require_collection_ui(engine, &target).await?; + delete_collection_ui(engine, &id).await + } + other => anyhow::bail!("Unknown collections action: {other}"), + } +} diff --git a/src/main.rs b/src/main.rs index adcf386..f381359 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,6 +13,7 @@ mod characters; mod chrome; mod cli; mod collections; +mod collections_ui; mod config; mod cookies; mod db; diff --git a/src/project.rs b/src/project.rs index eb6f535..736f1ba 100644 --- a/src/project.rs +++ b/src/project.rs @@ -321,12 +321,14 @@ pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowSt .call_flow_js("readStoreSnapshot", json!([])) .await .unwrap_or(Value::Null); - if snap.get("ok").and_then(|v| v.as_bool()) != Some(true) - && !probe - && ensure_flow_store(engine).await.is_ok() - { + if snap.get("ok").and_then(|v| v.as_bool()) != Some(true) && !probe { + let method_args = if ensure_flow_store(engine).await.is_ok() { + json!([]) + } else { + json!([true]) + }; snap = engine - .call_flow_js("readStoreSnapshot", json!([])) + .call_flow_js("readStoreSnapshot", method_args) .await .unwrap_or(Value::Null); } @@ -438,6 +440,9 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { } return Ok(()); } + if discovery.get("cooldownSkipped").and_then(Value::as_bool) == Some(true) { + break; + } if attempt == 2 && !input_pending { let pos = eval_project_nav(engine, "first_tile_center") .await @@ -490,6 +495,22 @@ async fn build_suffix(engine: &ChromeEngine) -> String { } } +/// Binds `lService` when available, or permits DOM-backed fallbacks when a `/project/` workspace is open. +pub(crate) async fn ensure_flow_store_or_dom(engine: &ChromeEngine) -> Result { + match ensure_flow_store(engine).await { + Ok(()) => Ok(true), + Err(err) if crate::project_store::can_use_ui_fallback(&err) => { + let cur = engine.current_url().await.unwrap_or_default(); + if project_id_from_url(&cur).is_some() { + Ok(false) + } else { + Err(err) + } + } + Err(err) => Err(err), + } +} + /// Binds the Flow store if needed and returns a JSON snapshot of assets, collections, title, and credits. pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { if engine.has_page().await @@ -500,7 +521,17 @@ pub(crate) async fn read_snapshot(engine: &ChromeEngine) -> Result { } let mut last_err = "store_not_bound".to_string(); for _ in 0..25 { - ensure_flow_store(engine).await?; + if let Err(err) = ensure_flow_store(engine).await { + if crate::project_store::can_use_ui_fallback(&err) + && let Ok(dom_snap) = engine + .call_flow_js("readStoreSnapshot", json!([true])) + .await + && dom_snap.get("ok").and_then(|v| v.as_bool()) == Some(true) + { + return Ok(dom_snap); + } + return Err(err); + } 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); @@ -691,7 +722,7 @@ async fn open_project( 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 _ = ensure_flow_store_or_dom(engine).await?; let snap = read_snapshot(engine).await?; Ok(json!({ "opened": true, @@ -715,7 +746,7 @@ async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> let _ = open_project(engine, Some(pid), None).await?; } } else { - ensure_flow_store(engine).await?; + let _ = ensure_flow_store_or_dom(engine).await?; } let mut net_rx = engine.subscribe_network().await.ok(); let res = run_projects_op(engine, json!({ "action": "set_title", "title": trimmed })).await?; diff --git a/src/project_store.rs b/src/project_store.rs index 0f5ee0d..59c84e1 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -46,6 +46,11 @@ impl<'a> ProjectStoreSession<'a> { }) } + /// Returns the browser engine for this session. + pub(crate) fn engine(&self) -> &'a ChromeEngine { + self.engine + } + /// Returns the active project ID at the time of binding. pub(crate) fn project_id(&self) -> &str { &self.project_id @@ -92,3 +97,30 @@ async fn bind_current_store(engine: &ChromeEngine, project_id: &str) -> Result bool { + let text = format!("{err:#}"); + if text.contains("outcome_unknown") + || text.contains("Open a Google Flow project") + || text.contains("not signed in") + || text.contains("No Google Flow project is open") + { + return false; + } + [ + "unsupported_front_end", + "collection_store_not_bound", + "ambiguous_collection_store", + "collection_delete_unavailable", + "unverified_mutation_shape", + "ambiguous_mutation_shape", + "project_upload_page_not_ready", + "Failed to find the Flow project store", + "The browser did not return the project store session", + "store_not_bound", + "mutation_unavailable", + ] + .iter() + .any(|code| text.contains(code)) +} diff --git a/src/tile_menu.rs b/src/tile_menu.rs index 93ac606..23b9437 100644 --- a/src/tile_menu.rs +++ b/src/tile_menu.rs @@ -1,24 +1,31 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -//! Tile operations through the "More options" menu of the Google Flow page. +//! Tile and collection operations through the "More options" menu of the Google Flow page. //! -//! Each operation finds the tile through the project store, sends trusted -//! clicks to the menu of the page, and reads the store to confirm the result. -//! The page builds its own mutation, so a front-end build that renames the -//! mutation fields does not break these operations. +//! Each operation finds the tile through the project store or rendered grid DOM, sends +//! trusted clicks to the menu of the page, and reads the store or DOM to confirm the result. +//! The page builds its own mutation, so a front-end build that renames the mutation fields +//! does not break these operations. use anyhow::Result; use serde_json::{Value, json}; +use std::collections::HashSet; use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::time::Duration; use crate::engine::ChromeEngine; -use crate::project::ensure_flow_store; +use crate::project::{ensure_flow_store, read_snapshot}; /// Menu item text that moves a tile to trash. const TRASH_MENU_ITEM: &str = "Move to trash"; +/// Menu item and dialog button text that deletes a collection folder on Google Flow. +const DELETE_COLLECTION_ITEM: &str = "Move all contents to trash"; + +/// Alternate menu item text that deletes a collection folder. +const DELETE_MENU_ITEM: &str = "Delete"; + /// Menu item text that opens the rename control of a tile. const RENAME_MENU_ITEM: &str = "Rename"; @@ -48,10 +55,10 @@ fn page_is_free() -> bool { PAGE_JOBS.load(Ordering::Acquire) == 0 } -/// Store state of one tile. +/// Store or DOM state of one tile. #[derive(Debug, Clone, Default)] pub(crate) struct TileState { - /// `present`, `trashed`, or `gone`. Empty when the store is not readable. + /// `present`, `trashed`, or `gone`. Empty when neither store nor DOM is readable. pub(crate) state: String, /// Display name of a present tile. pub(crate) name: String, @@ -60,12 +67,12 @@ pub(crate) struct TileState { } impl TileState { - /// Returns true when the tile map shows the tile and the tile is not in trash. + /// Returns true when the tile map or DOM shows the tile and the tile is not in trash. pub(crate) fn is_present(&self) -> bool { self.state == "present" } - /// Returns true when the tile is in trash or the tile map does not show it. + /// Returns true when the tile is in trash or no longer shown. fn is_trashed_or_gone(&self) -> bool { self.state == "trashed" || self.state == "gone" } @@ -86,7 +93,7 @@ fn is_ok(res: &Value) -> bool { res.get("ok").and_then(|v| v.as_bool()) == Some(true) } -/// Reads the store state of tile `id`. Returns the default state when the store is not readable. +/// Reads the store or DOM state of tile `id`. Returns the default state when not readable. pub(crate) async fn tile_state(engine: &ChromeEngine, id: &str) -> TileState { let Ok(res) = tile_dom_op(engine, "state", id).await else { return TileState::default(); @@ -99,7 +106,7 @@ pub(crate) async fn tile_state(engine: &ChromeEngine, id: &str) -> TileState { } } -/// Polls the store state of tile `id` every 250 ms, and returns true when `done` accepts it within `tries` polls. +/// Polls the state of tile `id` every 250 ms, and returns true when `done` accepts it within `tries` polls. async fn wait_tile_state( engine: &ChromeEngine, id: &str, @@ -115,7 +122,7 @@ async fn wait_tile_state( false } -/// Returns true when the store shows tile `id` as trashed or removed within `tries` polls of 250 ms. +/// Returns true when the store or DOM shows tile `id` as trashed or removed within `tries` polls of 250 ms. pub(crate) async fn wait_trashed(engine: &ChromeEngine, id: &str, tries: u32) -> bool { wait_tile_state(engine, id, tries, TileState::is_trashed_or_gone).await } @@ -125,10 +132,8 @@ async fn dismiss_overlay(engine: &ChromeEngine) { let _ = tile_dom_op(engine, "dismiss", "").await; } -/// Hovers the tile that `loc` describes, opens its "More options" menu, and clicks the menu item `item`. -/// -/// Returns false when the page does not show the tile, the menu, or the menu item. It closes the menu in that case. -async fn click_menu_item_at(engine: &ChromeEngine, loc: &Value, item: &str) -> Result { +/// Hovers the tile that `loc` describes and opens its "More options" menu. +async fn open_tile_menu_at(engine: &ChromeEngine, loc: &Value) -> Result { if !is_ok(loc) { return Ok(false); } @@ -142,15 +147,24 @@ async fn click_menu_item_at(engine: &ChromeEngine, loc: &Value, item: &str) -> R engine.mouse_move(x, y).await?; tokio::time::sleep(Duration::from_millis(300)).await; } - if !engine.click_point(menu).await? { + engine.click_point(menu).await +} + +/// Hovers the tile that `loc` describes, opens its "More options" menu, and clicks one of `items`. +/// +/// Returns false when the page does not show the tile, the menu, or any matching menu item. +async fn click_menu_items_at(engine: &ChromeEngine, loc: &Value, items: &[&str]) -> Result { + if !open_tile_menu_at(engine, loc).await? { return Ok(false); } for _ in 0..15 { - let point = engine - .call_flow_js("locatePoint", json!([{ "by": "menuitem", "name": item }])) - .await?; - if engine.click_point(&point).await? { - return Ok(true); + for item in items { + let point = engine + .call_flow_js("locatePoint", json!([{ "by": "menuitem", "name": item }])) + .await?; + if engine.click_point(&point).await? { + return Ok(true); + } } tokio::time::sleep(Duration::from_millis(150)).await; } @@ -158,10 +172,10 @@ async fn click_menu_item_at(engine: &ChromeEngine, loc: &Value, item: &str) -> R Ok(false) } -/// Opens the "More options" menu of tile `id` and clicks the menu item `item`. -async fn click_tile_menu_item(engine: &ChromeEngine, id: &str, item: &str) -> Result { +/// Opens the "More options" menu of tile `id` and clicks one of `items`. +async fn click_tile_menu_items(engine: &ChromeEngine, id: &str, items: &[&str]) -> Result { let loc = tile_dom_op(engine, "locate", id).await?; - click_menu_item_at(engine, &loc, item).await + click_menu_items_at(engine, &loc, items).await } /// Page view to restore after an operation: `Some(collection ID)`, with an empty ID for the main grid. @@ -204,17 +218,54 @@ async fn restore_view(engine: &ChromeEngine, saved: SavedView) { } } -/// Moves a media tile to trash through its menu, and returns true when the store confirms it. -/// -/// Returns false when the page does not show the tile, the menu, or the menu item, so that the caller can use the store mutation. +/// Returns true when the page shows the main grid (`collection` is `None`) or the page of that collection. +async fn view_is(engine: &ChromeEngine, collection: Option<&str>) -> bool { + let Ok(view) = page_op(engine, json!({ "action": "view" })).await else { + return false; + }; + view.get("grid").and_then(|v| v.as_bool()) == Some(true) + && view.get("collection").and_then(|v| v.as_str()) == collection +} + +/// Clicks a confirmation button inside an open alert or confirmation dialog when present. +async fn confirm_trash_dialog_if_present(engine: &ChromeEngine) -> Result { + for _ in 0..10 { + for label in [ + DELETE_COLLECTION_ITEM, + TRASH_MENU_ITEM, + DELETE_MENU_ITEM, + "Confirm", + ] { + let point = engine + .call_flow_js("locatePoint", json!([{ "by": "text", "name": label }])) + .await?; + if engine.click_point(&point).await? { + return Ok(true); + } + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + Ok(false) +} + +/// Moves a tile or collection folder to trash through its menu, and returns true when confirmed. async fn trash_in_view(engine: &ChromeEngine, id: &str) -> Result { - if !click_tile_menu_item(engine, id, TRASH_MENU_ITEM).await? { + if !click_tile_menu_items( + engine, + id, + &[TRASH_MENU_ITEM, DELETE_COLLECTION_ITEM, DELETE_MENU_ITEM], + ) + .await? + { return Ok(false); } - if wait_trashed(engine, id, 40).await { + if wait_trashed(engine, id, 4).await { + return Ok(true); + } + let _ = confirm_trash_dialog_if_present(engine).await; + if wait_trashed(engine, id, 36).await { return Ok(true); } - // The page can show a dialog after the click. Close it before the caller sends the store mutation. dismiss_overlay(engine).await; Ok(false) } @@ -239,11 +290,17 @@ async fn press_enter(engine: &ChromeEngine) -> Result<()> { Ok(()) } -/// Types `name` into the focused rename control and submits it with the Enter key. -async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { +/// Types `name` into the focused rename control (`control`, `current`) and submits it with Enter. +async fn type_into_control( + engine: &ChromeEngine, + control: &str, + current: &str, + name: &str, +) -> Result { + let req = |action: &str| json!({ "action": action, "control": control, "name": current }); let mut selected = false; for _ in 0..15 { - let res = page_op(engine, json!({ "action": "text_select" })).await?; + let res = page_op(engine, req("text_select")).await?; if is_ok(&res) && res.get("focused").and_then(|v| v.as_bool()) == Some(true) { selected = true; break; @@ -258,9 +315,8 @@ async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { .cdp_call("Input.insertText", json!({ "text": name })) .await?; tokio::time::sleep(Duration::from_millis(150)).await; - let typed = page_op(engine, json!({ "action": "text_value" })).await?; + let typed = page_op(engine, req("text_value")).await?; if typed.get("value").and_then(|v| v.as_str()) != Some(name) { - // The control does not hold the new name. Do not submit a wrong name. dismiss_overlay(engine).await; return Ok(false); } @@ -268,9 +324,14 @@ async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { Ok(true) } -/// Renames a media tile in the current view through the "Rename" item of its menu. +/// Types `name` into the focused tile or dialog rename control and submits it with the Enter key. +async fn type_rename(engine: &ChromeEngine, name: &str) -> Result { + type_into_control(engine, "", "", name).await +} + +/// Renames a tile in the current view through the "Rename" item of its menu. async fn rename_in_view(engine: &ChromeEngine, id: &str, name: &str) -> Result { - if !click_tile_menu_item(engine, id, RENAME_MENU_ITEM).await? { + if !click_tile_menu_items(engine, id, &[RENAME_MENU_ITEM]).await? { return Ok(false); } if !type_rename(engine, name).await? { @@ -283,22 +344,54 @@ async fn rename_in_view(engine: &ChromeEngine, id: &str, name: &str) -> Result Result { if !page_is_free() { return Ok(false); } let saved = enter_tile_view(engine, id).await; let res = trash_in_view(engine, id).await; + let deleted_saved = matches!(res, Ok(true)) && saved.as_deref() == Some(id); + if !deleted_saved { + restore_view(engine, saved).await; + } + res +} + +/// Opens the page of collection `id` and renames its editable page title from `current` to `name`. +pub(crate) async fn rename_collection_through_page( + engine: &ChromeEngine, + id: &str, + current: &str, + name: &str, +) -> Result { + if !page_is_free() { + return Ok(false); + } + let saved = enter_view(engine, Some(id)).await; + let res = if view_is(engine, Some(id)).await { + let point_res = page_op( + engine, + json!({ "action": "text_point", "control": "title", "name": current }), + ) + .await?; + if let Some(point) = point_res.get("point").filter(|_| is_ok(&point_res)) + && engine.click_point(point).await? + { + let typed = type_into_control(engine, "title", current, name).await?; + tokio::time::sleep(Duration::from_millis(600)).await; + Ok(typed) + } else { + Ok(false) + } + } else { + Ok(false) + }; restore_view(engine, saved).await; res } -/// Renames a media tile through the "Rename" item of its menu, and returns true when the store shows `name`. -/// -/// Opens the view that shows the tile first, and restores the view after the operation. Returns false when the page does not show the tile, the menu item, or the rename control, or when the control does not hold `name` after the text input. The caller can then use the store mutation. +/// Renames a tile or collection folder through the "Rename" item of its menu, and returns true when confirmed. pub(crate) async fn rename_through_menu( engine: &ChromeEngine, id: &str, @@ -312,3 +405,117 @@ pub(crate) async fn rename_through_menu( restore_view(engine, saved).await; res } + +/// Moves a tile into `target_id` or out of its collection (`None`) through its tile menu. +pub(crate) async fn move_tile_collection_through_menu( + engine: &ChromeEngine, + id: &str, + target_id: Option<&str>, + target_name: Option<&str>, +) -> Result { + if !page_is_free() { + return Ok(false); + } + let saved = enter_tile_view(engine, id).await; + let loc = tile_dom_op(engine, "locate", id).await?; + if !open_tile_menu_at(engine, &loc).await? { + restore_view(engine, saved).await; + return Ok(false); + } + tokio::time::sleep(Duration::from_millis(150)).await; + let res = page_op( + engine, + json!({ + "action": "move_collection_menu", + "id": id, + "target_id": target_id.unwrap_or(""), + "name": target_name.unwrap_or(""), + }), + ) + .await; + let clicked = res.as_ref().is_ok_and(is_ok); + if clicked { + let _ = wait_tile_state(engine, id, 12, |s| s.collection.as_deref() == target_id).await; + } else { + dismiss_overlay(engine).await; + } + restore_view(engine, saved).await; + Ok(clicked) +} + +/// Creates a new collection through the workspace UI and returns its ID when observed. +pub(crate) async fn create_collection_through_ui( + engine: &ChromeEngine, + name: &str, +) -> Result> { + if !page_is_free() { + return Ok(None); + } + let saved = enter_view(engine, None).await; + let before_ids: HashSet = read_snapshot(engine) + .await + .ok() + .and_then(|snap| snap.get("collections").and_then(Value::as_array).cloned()) + .unwrap_or_default() + .into_iter() + .filter_map(|c| c.get("id").and_then(Value::as_str).map(str::to_string)) + .collect(); + + let res = page_op( + engine, + json!({ "action": "create_collection_ui", "name": name }), + ) + .await?; + if !is_ok(&res) { + restore_view(engine, saved).await; + return Ok(None); + } + let typed = res.get("typed").and_then(Value::as_bool) == Some(true); + if !typed { + let _ = type_rename(engine, name).await; + } + + let mut created_id: Option = None; + let mut needs_rename = false; + for _ in 0..25 { + tokio::time::sleep(Duration::from_millis(250)).await; + let Ok(snap) = engine + .call_flow_js("readStoreSnapshot", json!([true])) + .await + else { + continue; + }; + let Some(cols) = snap.get("collections").and_then(Value::as_array) else { + continue; + }; + if let Some(found) = cols.iter().find(|c| { + c.get("id") + .and_then(Value::as_str) + .is_some_and(|id| !before_ids.contains(id)) + }) { + let cid = found + .get("id") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let cname = found.get("name").and_then(Value::as_str).unwrap_or(""); + needs_rename = cname != name; + created_id = Some(cid); + break; + } + if let Some(named) = cols + .iter() + .find(|c| c.get("name").and_then(Value::as_str) == Some(name)) + .and_then(|c| c.get("id").and_then(Value::as_str)) + { + created_id = Some(named.to_string()); + break; + } + } + + if needs_rename && let Some(cid) = created_id.as_deref() { + let _ = rename_in_view(engine, cid, name).await; + } + restore_view(engine, saved).await; + Ok(created_id) +} diff --git a/src/upload.rs b/src/upload.rs index ef17eb8..7007493 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -3,8 +3,8 @@ //! Prepares local file paths and uploads media to Flow. //! -//! Project uploads use the browser runtime in the active project. Menu uploads intercept the -//! file chooser and assign files to the input that Flow creates. +//! Project uploads use the browser runtime in the active project when supported, and fall back +//! to the workspace upload menu or file chooser when direct upload services are unavailable. use std::collections::HashSet; use std::time::Duration; @@ -13,7 +13,8 @@ use anyhow::{Context, Result}; use serde_json::{Value, json}; use crate::engine::{ChromeEngine, validate_local_files}; -use crate::project_store::ProjectStoreSession; +use crate::project::ensure_flow_store_or_dom; +use crate::project_store::{ProjectStoreSession, can_use_ui_fallback}; /// Menu button that adds ingredients to the prompt box. pub(crate) const PROMPT_INGREDIENTS_MENU: &str = "Add ingredients to the prompt box"; @@ -38,28 +39,121 @@ 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 { - let project = ProjectStoreSession::open(engine).await?; - let has_video = files.iter().any(|file| { +/// Returns true when any file path in `files` has a video MIME type. +fn contains_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 returns the saved assets, falling back to UI upload on unsupported builds. +pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { + if contains_video_file(files) + && eval_value(engine, "document.hidden") + .await + .unwrap_or(Value::Null) + == 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"), - ) + 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(val) => Ok(val), + Err(err) if can_use_ui_fallback(&err) => { + drop(project); + upload_project_files_ui(engine, files).await + } + Err(err) => Err(err), + } + } + Err(err) if can_use_ui_fallback(&err) => upload_project_files_ui(engine, files).await, + Err(err) => Err(err), + } +} + +/// Uploads local images and videos through the workspace menu or file input and waits for new assets. +async fn upload_project_files_ui(engine: &ChromeEngine, files: &[String]) -> Result { + ensure_flow_store_or_dom(engine).await?; + let before_snap = crate::assets::list_assets_with_project(engine).await?; + let project_id = before_snap.project_id; + let before: HashSet = before_snap.assets.into_iter().map(|a| a.id).collect(); + + if upload_through_menu(engine, LIBRARY_MEDIA_MENU, LIBRARY_UPLOAD_ITEM, files) .await + .is_err() + { + let cap = engine + .call_flow_js("uploadUiAction", json!(["capture_project_file_input"])) + .await?; + let selector = if cap.as_bool() == Some(true) { + r#"input[type="file"][data-flow-mcp-upload="project"]"# + } else { + cap.get("selector") + .and_then(Value::as_str) + .context("Could not find a workspace upload button or file input")? + }; + engine + .upload_files(selector, files) + .await + .context("Failed to assign files to the workspace upload input")?; + } + + let mut matched = Vec::new(); + for _ in 0..80 { + tokio::time::sleep(Duration::from_millis(750)).await; + let _ = engine + .call_flow_js("uploadUiAction", json!(["accept_consent"])) + .await; + let snap = engine + .call_flow_js("readStoreSnapshot", json!([true])) + .await?; + let Some(raw_assets) = snap.get("assets").and_then(Value::as_array) else { + continue; + }; + matched = raw_assets + .iter() + .filter(|a| { + let id = a.get("id").and_then(Value::as_str).unwrap_or(""); + let kind = a.get("kind").and_then(Value::as_str).unwrap_or(""); + !id.is_empty() && !before.contains(id) && matches!(kind, "image" | "video") + }) + .map(|a| { + json!({ + "id": a.get("id"), + "primary_media_id": a.get("primary_media_id"), + "name": a.get("name"), + "kind": a.get("kind"), + }) + }) + .collect(); + if matched.len() >= files.len() { + return Ok(json!({ + "project_id": project_id, + "count": matched.len(), + "assets": matched, + "method": "ui:upload", + })); + } + } + anyhow::bail!( + "outcome_unknown (project upload UI): observed {} of {} uploaded assets within 60 seconds", + matched.len(), + files.len() + ) } /// Script that keeps the next file input that the page clicks in `window.__fmUploadInput`. @@ -104,7 +198,26 @@ async fn click_when_visible(engine: &ChromeEngine, by: &str, name: &str) -> Resu anyhow::bail!("{} is not visible", name) } -/// Clicks `menu` and its `upload ` entry, and assigns `files` to the file input that the page opens. +/// Clicks an upload menu entry matching either `upload ` or ``. +async fn click_upload_menu_entry(engine: &ChromeEngine, item: &str) -> Result<()> { + let prefixed = format!("upload {item}"); + for _ in 0..20 { + for spec in [ + json!([{ "by": "text", "name": prefixed }]), + json!([{ "by": "menuitem", "name": item }]), + json!([{ "by": "text", "name": item }]), + ] { + let point = engine.call_flow_js("locatePoint", spec).await?; + if engine.click_point(&point).await? { + return Ok(()); + } + } + tokio::time::sleep(Duration::from_millis(150)).await; + } + anyhow::bail!("{} is not visible", item) +} + +/// Clicks `menu` and its upload entry, and assigns `files` to the file input that the page opens. async fn upload_steps( engine: &ChromeEngine, menu: &str, @@ -113,7 +226,7 @@ async fn upload_steps( ) -> Result<()> { click_when_visible(engine, "aria-label", menu).await?; tokio::time::sleep(Duration::from_millis(500)).await; - click_when_visible(engine, "text", &format!("upload {item}")).await?; + click_upload_menu_entry(engine, item).await?; let mut opened = false; for _ in 0..30 { let v = eval_value(engine, "!!window.__fmUploadInput").await?; diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 6984ee5..2e7d118 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -4,19 +4,12 @@ // Flow Agent session queries, live turns, and user responses. import { buildAttachmentMessage } from "./agent_attachments"; +import { agentSettingsUiOp } from "./agent_settings_ui"; +import { agentUiAllocate, agentUiBind, agentUiBound, agentUiBusy, agentUiOp } from "./agent_ui"; import { MEDIA_UPLOAD_TIMEOUT_MS, takeMediaFiles, waitForMedia } from "./project_upload"; import type { - AgentDecision, - AgentRequest, - FlowAgentExports, - FlowAnswer, - LiveTurn, - PendingAction, - QuestionResponder, - ReplyBlock, - Session, - StoredTurn, - Transport, + AgentDecision, AgentRequest, FlowAgentExports, FlowAnswer, LiveTurn, PendingAction, + QuestionResponder, ReplyBlock, Session, StoredTurn, Transport, } from "./agent_protocol"; import { agentSettingsOp, settingsWritePending } from "./agent_settings"; import type { AgentInjector } from "./agent_settings"; @@ -59,29 +52,20 @@ const LEGACY_PERMISSION_ID = "legacy-permission"; const AGENT_SURFACE = "SIDE_PANEL"; /** Permission decisions and the labels that Flow uses in the legacy transport. */ -const PERMISSION_DECISIONS: Partial< - Record -> = { +const PERMISSION_DECISIONS: Partial> = { approve: { code: 1, label: "Approve" }, approve_and_remember: { code: 2, label: "Always approve" }, deny: { code: 3, label: "Reject" }, }; /** Plan decisions that Flow accepts. */ -const PLAN_DECISIONS: Partial< - Record -> = { +const PLAN_DECISIONS: Partial> = { run_full_plan: { aja: 1, label: "Run full plan" }, previz: { aja: 2, label: "Previz" }, }; /** Phase of a turn before the tool checks for pending actions. */ -type TurnStatus = - | "in_progress" - | "completed" - | "failed" - | "stopped" - | "unknown"; +type TurnStatus = "in_progress" | "completed" | "failed" | "stopped" | "unknown"; /** Position and phase of a turn in the conversation. */ interface TurnPosition { @@ -110,34 +94,31 @@ function namespace(): Record { /** Checks that the page route still belongs to the requested project. */ function onProject(projectId: string): boolean { - return ( - location.pathname.match(/(?:^|\/)project\/([^/]+)\/?$/)?.[1] === projectId - ); + return location.pathname.match(/(?:^|\/)project\/([^/]+)\/?$/)?.[1] === projectId; } /** Returns the binding if the project page is still active. */ function liveBinding(projectId: string): Binding | undefined { - if (!binding || binding.projectId !== projectId || !onProject(projectId)) - return; + if (!binding || binding.projectId !== projectId || !onProject(projectId)) return; const { page, format } = binding; - const life = Reflect.get(page, format.lifecycle) as - | Record - | undefined; + const life = Reflect.get(page, format.lifecycle) as Record | undefined; if (life?.[format.destroyed] !== false) return; const project = Reflect.get(page, format.project); - if (typeof project === "function" && project.call(page) === projectId) - return binding; + if (typeof project === "function" && project.call(page) === projectId) return binding; } +export { agentUiBind }; + /** Returns true if the active document has a binding for this project. */ export function agentBound(projectId: string): boolean { - return liveBinding(projectId) !== undefined; + return liveBinding(projectId) !== undefined || agentUiBound(projectId); } /** Returns true while a turn uses the live transport. */ export function agentBusy(projectId: string): boolean { const bound = liveBinding(projectId); - return Boolean(bound && (bound.transport.ha.size > 0 || settingsWritePending)); + if (bound) return Boolean(bound.transport.ha.size > 0 || settingsWritePending); + return agentUiBusy(projectId); } /** Checks the frontend build and verifies the native Agent exports. */ @@ -225,14 +206,7 @@ export function bindAgent( ) continue; binding = { - projectId, - format, - page, - injector, - transport, - questions, - permissions, - flow, + projectId, format, page, injector, transport, questions, permissions, flow, canSend: () => composer.wb?.() === true, drafts: binding?.page === page ? binding.drafts : new Set(), }; @@ -247,7 +221,11 @@ export function bindAgent( /** Allocates an ID without submitting a message or changing remote state. */ export async function agentAllocate(projectId: string) { const bound = liveBinding(projectId); - if (!bound) return failure("agent_project_changed"); + if (!bound) { + return agentUiBound(projectId) + ? agentUiAllocate(projectId) + : failure("agent_project_changed"); + } const { id } = await bound.flow.allocate(); return { ok: true as const, session_id: id }; } @@ -780,16 +758,25 @@ export async function agentOp(request: AgentRequest) { if (files.length !== (request.file_count ?? 0)) return failure("agent_attachment_files_unavailable"); const bound = liveBinding(request.project_id); - if (!bound) return failure("agent_project_changed"); + if (!bound) { + if (agentUiBound(request.project_id)) { + return agentUiOp(request, files); + } + return failure("agent_project_changed"); + } const { projectId, transport } = bound; if (request.action === "get_settings" || request.action === "update_settings") { if (request.action === "update_settings" && transport.ha.size > 0) return failure("agent_turn_active"); - return agentSettingsOp({ + const nativeSettings = await agentSettingsOp({ projectId, injector: bound.injector, isCurrent: () => liveBinding(projectId) === bound, }, request.settings ?? undefined); + if (!nativeSettings.ok && nativeSettings.error === "unsupported_front_end") { + return agentSettingsUiOp(projectId, request.settings ?? undefined); + } + return nativeSettings; } const id = request.session_id; if (request.action === "list_sessions") { @@ -806,7 +793,11 @@ export async function agentOp(request: AgentRequest) { request.action === "create_session" || request.action === "send_message" ) { - return sendUserMessage(bound, request, id, files); + const sent = await sendUserMessage(bound, request, id, files); + if (!sent.ok && sent.error === "unsupported_front_end") { + return agentUiOp(request, files); + } + return sent; } const session = await getSession(bound, id); if (!session) return failure("agent_session_not_found", { session_id: id }); diff --git a/ts/agent_settings_ui.ts b/ts/agent_settings_ui.ts new file mode 100644 index 0000000..eaaf8aa --- /dev/null +++ b/ts/agent_settings_ui.ts @@ -0,0 +1,581 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Read and update Flow Agent confirmation policy, media defaults, and memory cards via panel UI. + +import { clickButtonByRegex, delay, dismissOverlay, elText, isVisibleEnabled, setNativeValue } from "./dom"; +import type { + AgentSettingsPatch, + ConfirmPolicy, + GenerationDefaultsPatch, + MemoryCardFields, + MemoryPatch, +} from "./agent_settings_protocol"; + +/** Normalized media defaults section read from the Agent settings UI. */ +interface UiMediaDefaults { + /** Selected model identifier or null if unset. */ + model: string | null; + /** Selected aspect ratio label. */ + aspect_ratio: string; + /** Selected output count per generation. */ + output_count: number; + /** Available model choices exposed in the control. */ + available_models: Array<{ id: string; name: string; aspect_ratios: string[] }>; +} + +/** Normalized memory card read from the Agent settings UI. */ +type UiMemoryCard = MemoryCardFields & { id: string }; + +/** True while a UI settings update is running so `agentBusy` reports busy status. */ +export let uiSettingsWritePending = false; + +/** Finds the workspace Agent panel root element. */ +export function findAgentPanelRoot(): HTMLElement | null { + const candidates = document.querySelectorAll( + "flow-agent-panel, .agent-panel-wrapper, [data-agent-panel], aside.agent-panel", + ); + for (const el of candidates) { + if (el.getClientRects().length > 0) return el; + } + const promptBox = document.querySelector("flow-creative-agent-prompt-box"); + if (promptBox && promptBox.getClientRects().length > 0) { + return promptBox.closest("aside, section, .agent-panel-wrapper") ?? promptBox.parentElement; + } + return null; +} + +/** Opens the workspace Agent side panel if it is currently collapsed. */ +export async function ensureAgentPanelOpen(): Promise { + const existing = findAgentPanelRoot(); + if (existing) return existing; + const toggles = Array.from( + document.querySelectorAll( + 'flow-agent-mode-toggle-chip button, button[aria-label*="Agent" i], button[aria-label*="Creative agent" i], [data-action="toggle-agent"], button', + ), + ).filter((el) => { + if (!isVisibleEnabled(el)) return false; + const label = `${el.getAttribute("aria-label") || ""} ${elText(el)}`.trim(); + return /^(?:agent|open agent|show agent|creative agent|flow agent)$/i.test(label); + }); + if (toggles[0]) { + toggles[0].click(); + for (let i = 0; i < 30; i++) { + await delay(100); + const opened = findAgentPanelRoot(); + if (opened) return opened; + } + } + return findAgentPanelRoot(); +} + +/** Finds the rendered Agent settings container if open. */ +function findSettingsContainer(): HTMLElement | null { + const selectors = [ + "flow-agent-settings", + "[data-agent-settings]", + ".agent-settings-panel", + '[role="dialog"][aria-label*="Agent" i]', + '[role="dialog"][aria-label*="settings" i]', + ]; + for (const sel of selectors) { + const el = document.querySelector(sel); + if (el && el.getClientRects().length > 0) return el; + } + return null; +} + +/** Opens the Agent settings view from the Agent panel header and returns its root container. */ +async function openSettingsView(panel: HTMLElement): Promise<{ root: HTMLElement; openedNow: boolean } | null> { + const already = findSettingsContainer(); + if (already) return { root: already, openedNow: false }; + + const btn = Array.from( + panel.querySelectorAll('button, [role="button"]'), + ).find((el) => { + if (!isVisibleEnabled(el)) return false; + const label = `${el.getAttribute("aria-label") || ""} ${el.getAttribute("title") || ""} ${elText(el)}`.trim(); + return /\b(?:agent settings|project settings|settings|preferences|tune)\b/i.test(label); + }); + if (!btn) return null; + btn.click(); + for (let i = 0; i < 25; i++) { + await delay(100); + const found = findSettingsContainer(); + if (found) return { root: found, openedNow: true }; + } + return null; +} + +/** Reads confirmation policy (`"always"` or `"never"`) from the settings root. */ +function readConfirmationPolicy(root: HTMLElement): ConfirmPolicy { + const select = root.querySelector( + 'select[data-setting="confirm_before_generating"], select[data-setting="confirmation_policy"], select[name="confirm_before_generating"], select[name="confirmation_policy"]', + ); + if (select) return /never|auto/i.test(select.value) ? "never" : "always"; + const checkedRadio = root.querySelector( + 'input[type="radio"][name*="confirm" i]:checked, input[type="radio"][name*="policy" i]:checked', + ); + if (checkedRadio) { + const val = `${checkedRadio.value} ${checkedRadio.getAttribute("aria-label") || ""}`; + return /never|auto/i.test(val) ? "never" : "always"; + } + const activeBtn = Array.from( + root.querySelectorAll( + '[data-policy][aria-pressed="true"], [data-policy][aria-checked="true"], [data-policy].active, [role="radio"][aria-checked="true"]', + ), + ).find((el) => el.getClientRects().length > 0); + if (activeBtn) { + const val = `${activeBtn.getAttribute("data-policy") || ""} ${elText(activeBtn)}`; + return /never|auto/i.test(val) ? "never" : "always"; + } + const toggle = root.querySelector( + '[data-setting="confirm_before_generating"][role="switch"], [data-setting="confirmation_policy"][role="switch"], input[type="checkbox"][data-setting="confirm_before_generating"], input[type="checkbox"][data-setting="confirmation_policy"]', + ); + if (toggle instanceof HTMLInputElement) return toggle.checked ? "always" : "never"; + if (toggle?.getAttribute("aria-checked") === "false") return "never"; + return "always"; +} + +/** Updates confirmation policy in the settings root. */ +async function writeConfirmationPolicy(root: HTMLElement, policy: ConfirmPolicy): Promise { + const select = root.querySelector( + 'select[data-setting="confirm_before_generating"], select[data-setting="confirmation_policy"], select[name="confirm_before_generating"], select[name="confirmation_policy"]', + ); + if (select) { + const opt = Array.from(select.options).find((o) => + policy === "never" ? /never|auto/i.test(`${o.value} ${o.text}`) : /always|ask/i.test(`${o.value} ${o.text}`), + ); + if (!opt) return false; + select.value = opt.value; + select.dispatchEvent(new Event("change", { bubbles: true })); + await delay(100); + return true; + } + const targetPattern = + policy === "never" + ? /\b(?:never|auto[-\s]?approve|don't ask|automatic)\b/i + : /\b(?:always|ask before|confirm)\b/i; + const control = Array.from( + root.querySelectorAll('button, [role="radio"], label, input[type="radio"]'), + ).find((el) => { + if (el.getClientRects().length === 0) return false; + const txt = `${el.getAttribute("data-policy") || ""} ${el.getAttribute("value") || ""} ${el.getAttribute("aria-label") || ""} ${elText(el)}`; + return targetPattern.test(txt); + }); + if (control) { + control.click(); + await delay(120); + return true; + } + return false; +} + +/** Locates the media defaults card (`"image"` or `"video"`) inside the settings root. */ +function findMediaSection(root: HTMLElement, kind: "image" | "video"): HTMLElement | null { + const direct = root.querySelector( + `[data-media-defaults="${kind}"], [data-setting-section="${kind}"], .${kind}-defaults-card`, + ); + if (direct) return direct; + const headingRe = kind === "image" ? /\bimage\b/i : /\bvideo\b/i; + for (const card of root.querySelectorAll("section, fieldset, .settings-card, .defaults-card")) { + const heading = card.querySelector("h2, h3, h4, legend, .card-title"); + if (heading && headingRe.test(elText(heading))) return card; + } + return null; +} + +/** Reads one media defaults section from the settings root. */ +function readMediaCard(root: HTMLElement, kind: "image" | "video"): UiMediaDefaults { + const sec = findMediaSection(root, kind); + const defaultModel = kind === "image" ? "imagen-3" : "veo-2"; + const defaultAspect = "16:9"; + const fallbackRatios = kind === "image" ? ["16:9", "9:16", "1:1", "4:3", "3:4"] : ["16:9", "9:16"]; + if (!sec) { + return { + model: defaultModel, + aspect_ratio: defaultAspect, + output_count: kind === "image" ? 2 : 1, + available_models: [{ id: defaultModel, name: defaultModel, aspect_ratios: fallbackRatios }], + }; + } + const aspectSelect = sec.querySelector( + 'select[data-field="aspect_ratio"], select[name*="aspect" i]', + ); + let aspect = sec.getAttribute("data-aspect-ratio") || defaultAspect; + let knownRatios = fallbackRatios; + if (aspectSelect) { + aspect = aspectSelect.value || aspect; + const opts = Array.from(aspectSelect.options).map((o) => o.value || o.text.trim()).filter(Boolean); + if (opts.length > 0) knownRatios = opts; + } else { + const aspectBtns = Array.from(sec.querySelectorAll("[data-aspect-ratio]")); + if (aspectBtns.length > 0) { + knownRatios = aspectBtns.map((b) => b.getAttribute("data-aspect-ratio") || elText(b).trim()).filter(Boolean); + const activeAspect = aspectBtns.find( + (b) => b.getAttribute("aria-pressed") === "true" || b.classList.contains("active"), + ); + if (activeAspect) aspect = activeAspect.getAttribute("data-aspect-ratio") || aspect; + } + } + + const modelSelect = sec.querySelector('select[data-field="model"], select[name*="model" i]'); + let model: string | null = sec.getAttribute("data-model") || defaultModel; + let available: Array<{ id: string; name: string; aspect_ratios: string[] }> = []; + if (modelSelect) { + model = modelSelect.value || defaultModel; + available = Array.from(modelSelect.options).map((o) => ({ + id: o.value, + name: (o.textContent || o.value).trim(), + aspect_ratios: knownRatios, + })); + } else { + const modelBtns = Array.from(sec.querySelectorAll("[data-model-id]")); + if (modelBtns.length > 0) { + available = modelBtns.map((b) => ({ + id: b.getAttribute("data-model-id") || elText(b).trim(), + name: elText(b).trim() || b.getAttribute("data-model-id") || "", + aspect_ratios: knownRatios, + })); + const active = modelBtns.find( + (b) => + b.getAttribute("aria-pressed") === "true" || + b.getAttribute("aria-selected") === "true" || + b.classList.contains("active"), + ); + if (active) model = active.getAttribute("data-model-id") || model; + } + } + if (available.length === 0 && model) { + available = [{ id: model, name: model, aspect_ratios: knownRatios }]; + } + + const countSelect = sec.querySelector( + 'select[data-field="output_count"], input[data-field="output_count"], select[name*="count" i], input[name*="count" i]', + ); + let count = Number.parseInt(sec.getAttribute("data-output-count") || String(kind === "image" ? 2 : 1), 10) || 1; + if (countSelect) { + count = Number.parseInt(countSelect.value || "1", 10) || 1; + } else { + const activeCount = sec.querySelector( + '[data-output-count][aria-pressed="true"], [data-output-count].active', + ); + if (activeCount) count = Number.parseInt(activeCount.getAttribute("data-output-count") || "1", 10) || 1; + } + + return { model, aspect_ratio: aspect, output_count: count, available_models: available }; +} + +/** Applies updates to an image or video defaults section in the settings UI. */ +async function writeMediaCard( + root: HTMLElement, + kind: "image" | "video", + patch: GenerationDefaultsPatch, +): Promise { + const sec = findMediaSection(root, kind); + if (!sec) return `${kind}_defaults_section_not_found`; + + if (patch.model != null) { + const want = patch.model.trim(); + const modelSelect = sec.querySelector('select[data-field="model"], select[name*="model" i]'); + if (modelSelect) { + const opt = Array.from(modelSelect.options).find( + (o) => o.value === want || (o.textContent || "").trim().toLowerCase() === want.toLowerCase(), + ); + if (!opt) return "invalid_agent_settings"; + modelSelect.value = opt.value; + modelSelect.dispatchEvent(new Event("change", { bubbles: true })); + } else { + const btn = Array.from(sec.querySelectorAll("[data-model-id], button")).find( + (b) => + b.getAttribute("data-model-id") === want || + elText(b).trim().toLowerCase() === want.toLowerCase(), + ); + if (!btn) return "invalid_agent_settings"; + btn.click(); + } + await delay(100); + } + + if (patch.aspect_ratio != null) { + const want = patch.aspect_ratio.trim(); + const aspectSelect = sec.querySelector( + 'select[data-field="aspect_ratio"], select[name*="aspect" i]', + ); + if (aspectSelect) { + const opt = Array.from(aspectSelect.options).find( + (o) => o.value === want || (o.textContent || "").includes(want), + ); + if (!opt) return "invalid_agent_settings"; + aspectSelect.value = opt.value; + aspectSelect.dispatchEvent(new Event("change", { bubbles: true })); + } else { + const btn = Array.from(sec.querySelectorAll("[data-aspect-ratio], button")).find( + (b) => b.getAttribute("data-aspect-ratio") === want || elText(b).trim() === want, + ); + if (!btn) return "invalid_agent_settings"; + btn.click(); + } + await delay(100); + } + + if (patch.output_count != null) { + const want = String(patch.output_count); + const countCtrl = sec.querySelector( + 'select[data-field="output_count"], input[data-field="output_count"], select[name*="count" i], input[name*="count" i]', + ); + if (countCtrl instanceof HTMLSelectElement) { + const opt = Array.from(countCtrl.options).find((o) => o.value === want || o.textContent?.trim() === want); + if (!opt) return "invalid_agent_settings"; + countCtrl.value = opt.value; + countCtrl.dispatchEvent(new Event("change", { bubbles: true })); + } else if (countCtrl instanceof HTMLInputElement) { + setNativeValue(countCtrl, want, true); + } else { + const btn = Array.from(sec.querySelectorAll("[data-output-count], button")).find( + (b) => b.getAttribute("data-output-count") === want || elText(b).trim() === want || elText(b).trim() === `x${want}`, + ); + if (!btn) return "invalid_agent_settings"; + btn.click(); + } + await delay(100); + } + return null; +} + +/** Splits comma-separated attribute values into non-empty IDs. */ +function readCsvAttr(el: Element, attr: string): string[] { + const raw = el.getAttribute(attr); + return raw ? raw.split(",").map((s) => s.trim()).filter(Boolean) : []; +} + +/** Reads memory cards from the settings root. */ +function readMemories(root: HTMLElement): UiMemoryCard[] { + const cards = root.querySelectorAll( + "flow-agent-memory-card, .agent-memory-card, [data-memory-id]", + ); + const out: UiMemoryCard[] = []; + let idx = 0; + for (const card of cards) { + if (card.getClientRects().length === 0) continue; + idx += 1; + const id = card.getAttribute("data-memory-id") || card.getAttribute("data-id") || `memory-${idx}`; + const titleEl = card.querySelector(".memory-title, [data-memory-title], h4, strong"); + const descEl = card.querySelector(".memory-description, .memory-content, [data-memory-description], [data-memory-content], p"); + const enabledToggle = card.querySelector( + 'input[type="checkbox"][data-field="enabled"], [role="switch"][data-field="enabled"], input[type="checkbox"]', + ); + let enabled = card.getAttribute("data-enabled") !== "false"; + if (enabledToggle instanceof HTMLInputElement) enabled = enabledToggle.checked; + else if (enabledToggle?.getAttribute("aria-checked")) enabled = enabledToggle.getAttribute("aria-checked") !== "false"; + out.push({ + id, + title: titleEl ? elText(titleEl).trim() : "", + description: descEl ? elText(descEl).trim() : "", + enabled, + image_media_ids: readCsvAttr(card, "data-image-media-ids"), + character_ids: readCsvAttr(card, "data-character-ids"), + likeness_ids: readCsvAttr(card, "data-likeness-ids"), + }); + } + return out; +} + +/** Applies a `create`, `update`, or `delete` action on Agent memory cards in the settings UI. */ +async function applyMemoryChange( + root: HTMLElement, + memory: MemoryPatch, +): Promise<{ error?: string; memoryId?: string }> { + if (memory.action === "create") { + const beforeIds = new Set(readMemories(root).map((m) => m.id)); + const addBtn = Array.from(root.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:add memory|new memory|create memory|add instruction|add note|add card)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${elText(b)}`, + ), + ); + if (!addBtn) return { error: "agent_memory_add_button_not_found" }; + addBtn.click(); + await delay(150); + const formScope = + document.querySelector('[data-memory-editor], [role="dialog"]') ?? root; + const titleInput = formScope.querySelector( + 'input[data-field="memory_title"], input[data-field="title"], input[placeholder*="title" i], input[aria-label*="title" i], input[type="text"]', + ); + const descInput = formScope.querySelector( + 'textarea[data-field="memory_description"], textarea[data-field="description"], textarea[data-field="memory_content"], textarea', + ); + if (!descInput && !titleInput) return { error: "agent_memory_editor_not_found" }; + if (titleInput && memory.card.title != null) { + titleInput.focus(); + setNativeValue(titleInput, memory.card.title, true); + } + if (descInput && memory.card.description != null) { + descInput.focus(); + setNativeValue(descInput, memory.card.description, true); + } + const enabledToggle = formScope.querySelector( + 'input[type="checkbox"][data-field="enabled"], [role="switch"][data-field="enabled"]', + ); + if (enabledToggle && memory.card.enabled != null) { + const current = + enabledToggle instanceof HTMLInputElement + ? enabledToggle.checked + : enabledToggle.getAttribute("aria-checked") !== "false"; + if (current !== memory.card.enabled) enabledToggle.click(); + } + clickButtonByRegex(/^(?:save|add|create|done)$/i, formScope); + await delay(200); + const freshRoot = findSettingsContainer() ?? root; + const created = readMemories(freshRoot).find((m) => !beforeIds.has(m.id)); + return { memoryId: created?.id ?? `memory-${beforeIds.size + 1}` }; + } + + const card = Array.from( + root.querySelectorAll("flow-agent-memory-card, .agent-memory-card, [data-memory-id]"), + ).find( + (c) => c.getAttribute("data-memory-id") === memory.id || c.getAttribute("data-id") === memory.id, + ); + if (!card) return { error: "invalid_agent_settings" }; + + if (memory.action === "delete") { + const delBtn = Array.from(card.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:delete|remove|trash)\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!delBtn) return { error: "agent_memory_delete_button_not_found" }; + delBtn.click(); + await delay(150); + const dialog = document.querySelector('[role="dialog"], [role="alertdialog"]'); + if (dialog) clickButtonByRegex(/^(?:delete|remove|confirm|yes)$/i, dialog); + await delay(150); + return { memoryId: memory.id }; + } + + const editBtn = Array.from(card.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:edit|modify)\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + editBtn?.click(); + await delay(150); + const scope = + card.querySelector("textarea, input[type='text']") + ? card + : (document.querySelector('[data-memory-editor], [role="dialog"]') ?? root); + if (memory.card.title != null) { + const titleInput = scope.querySelector( + 'input[data-field="memory_title"], input[data-field="title"], input[placeholder*="title" i], input[aria-label*="title" i], input[type="text"]', + ); + if (titleInput) { + titleInput.focus(); + setNativeValue(titleInput, memory.card.title, true); + } + } + if (memory.card.description != null) { + const descInput = scope.querySelector( + 'textarea[data-field="memory_description"], textarea[data-field="description"], textarea[data-field="memory_content"], textarea', + ); + if (!descInput) return { error: "agent_memory_editor_not_found" }; + descInput.focus(); + setNativeValue(descInput, memory.card.description, true); + } + if (memory.card.enabled != null) { + const enabledToggle = scope.querySelector( + 'input[type="checkbox"][data-field="enabled"], [role="switch"][data-field="enabled"], input[type="checkbox"]', + ); + if (enabledToggle) { + const current = + enabledToggle instanceof HTMLInputElement + ? enabledToggle.checked + : enabledToggle.getAttribute("aria-checked") !== "false"; + if (current !== memory.card.enabled) enabledToggle.click(); + } + } + clickButtonByRegex(/^(?:save|update|done)$/i, scope); + await delay(200); + return { memoryId: memory.id }; +} + +/** Reads or updates Agent project settings through the workspace panel UI. */ +export async function agentSettingsUiOp( + _projectId: string, + patch?: AgentSettingsPatch, +): Promise> { + const panel = await ensureAgentPanelOpen(); + if (!panel) return { ok: false, error: "agent_panel_not_found" }; + + const opened = await openSettingsView(panel); + if (!opened) return { ok: false, error: "agent_settings_ui_not_found" }; + const { openedNow } = opened; + let root = opened.root; + let memoryId: string | undefined; + + try { + if (patch) { + uiSettingsWritePending = true; + if (patch.confirm_before_generating != null) { + const applied = await writeConfirmationPolicy(root, patch.confirm_before_generating); + if (!applied) return { ok: false, error: "agent_confirmation_policy_control_not_found" }; + root = findSettingsContainer() ?? root; + } + if (patch.image_defaults) { + const err = await writeMediaCard(root, "image", patch.image_defaults); + if (err) return { ok: false, error: err }; + root = findSettingsContainer() ?? root; + } + if (patch.video_defaults) { + const err = await writeMediaCard(root, "video", patch.video_defaults); + if (err) return { ok: false, error: err }; + root = findSettingsContainer() ?? root; + } + if (patch.memory) { + const memRes = await applyMemoryChange(root, patch.memory); + if (memRes.error) return { ok: false, error: memRes.error }; + memoryId = memRes.memoryId; + root = findSettingsContainer() ?? root; + } + const saveBtn = Array.from(root.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + !b.closest("flow-agent-memory-card, .agent-memory-card, [data-memory-editor]") && + /^(?:save|apply|save settings)$/i.test((b.getAttribute("aria-label") || elText(b)).trim()), + ); + if (saveBtn) { + saveBtn.click(); + await delay(150); + root = findSettingsContainer() ?? root; + } + } + + const settings = { + confirm_before_generating: readConfirmationPolicy(root), + image_defaults: readMediaCard(root, "image"), + video_defaults: readMediaCard(root, "video"), + memory: readMemories(root), + }; + return patch + ? { ok: true, confirmed: true, settings, ...(memoryId ? { memory_id: memoryId } : {}) } + : { ok: true, settings }; + } finally { + uiSettingsWritePending = false; + const closeRoot = findSettingsContainer() ?? root; + if (openedNow) { + const closeBtn = Array.from(closeRoot.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /^(?:close|back|done|close settings)$/i.test( + (b.getAttribute("aria-label") || elText(b)).trim(), + ), + ); + if (closeBtn) { + closeBtn.click(); + await delay(100); + } else { + await dismissOverlay(); + } + } + } +} diff --git a/ts/agent_ui.ts b/ts/agent_ui.ts new file mode 100644 index 0000000..0c1dc9c --- /dev/null +++ b/ts/agent_ui.ts @@ -0,0 +1,479 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Drive Flow Agent chat sessions, turns, and history controls via workspace panel UI. + +import type { AgentRequest, Session } from "./agent_protocol"; +import { + agentSettingsUiOp, + ensureAgentPanelOpen, + findAgentPanelRoot, + uiSettingsWritePending, +} from "./agent_settings_ui"; +import { + attachComposerItems, + findAgentTextbox, + findSendButton, + parseRenderedTurns, + respondViaUi, + uiFailure, + type UiFormattedTurn, +} from "./agent_ui_dom"; +import { + clickButtonByRegex, + delay, + dismissOverlay, + elText, + isVisibleEnabled, + setNativeValue, +} from "./dom"; +import { writePromptBox } from "./prompt_writer"; + +/** UI fallback binding state for a single project workspace. */ +interface UiAgentState { + /** Pinned project ID. */ + projectId: string; + /** Allocated draft session IDs not yet sent. */ + drafts: Set; + /** Alias map from MCP session ID to DOM session ID when Flow assigns its own ID. */ + mcpToDomId: Map; + /** Reverse alias map from DOM session ID to MCP session ID. */ + domToMcpId: Map; + /** Known persisted session metadata keyed by MCP session ID. */ + sessions: Map; + /** Currently displayed MCP session ID in the panel. */ + activeMcpId: string | null; +} + +/** Active UI fallback state for the current document. */ +let uiState: UiAgentState | null = null; + +/** Checks whether the browser route is on `/project/`. */ +function onProject(projectId: string): boolean { + return /(?:^|\/)project\/([^/?#]+)\/?$/.exec(location.pathname || "")?.[1] === projectId; +} + +/** Binds the workspace Agent panel in UI fallback mode for `projectId`. */ +export async function agentUiBind(projectId: string): Promise> { + if (!onProject(projectId)) return uiFailure("agent_page_not_ready"); + const panel = await ensureAgentPanelOpen(); + if (!panel) return uiFailure("agent_page_not_ready"); + if (!uiState || uiState.projectId !== projectId) { + uiState = { + projectId, + drafts: new Set(), + mcpToDomId: new Map(), + domToMcpId: new Map(), + sessions: new Map(), + activeMcpId: null, + }; + } + syncSessionsFromDom(panel, uiState); + return { ok: true, mode: "ui" }; +} + +/** Returns true when `agentUiBind` has bound `projectId` and the panel remains mounted. */ +export function agentUiBound(projectId: string): boolean { + return Boolean( + uiState && uiState.projectId === projectId && onProject(projectId) && findAgentPanelRoot(), + ); +} + +/** Returns true while a turn in the Agent panel is streaming or settings are saving. */ +export function agentUiBusy(projectId: string): boolean { + if (!agentUiBound(projectId)) return false; + if (uiSettingsWritePending) return true; + const panel = findAgentPanelRoot(); + if (!panel) return false; + const turns = parseRenderedTurns(panel); + return turns.at(-1)?.status === "in_progress"; +} + +/** Allocates a draft session ID in UI fallback mode. */ +export function agentUiAllocate(projectId: string): Record { + if (!agentUiBound(projectId) || !uiState) return uiFailure("agent_project_changed"); + const id = crypto.randomUUID(); + uiState.drafts.add(id); + return { ok: true, session_id: id }; +} + +/** Synchronizes DOM session list items with `state`. */ +function syncSessionsFromDom(panel: HTMLElement, state: UiAgentState): Session[] { + const activeDomAttr = panel.getAttribute("data-active-session-id") || ""; + const items = Array.from( + document.querySelectorAll( + 'flow-agent-panel [data-session-id], .agent-panel-wrapper [data-session-id], .cdk-overlay-pane [data-session-id]', + ), + ); + for (const el of items) { + const domId = el.getAttribute("data-session-id") || ""; + if (!domId) continue; + let mcpId = state.domToMcpId.get(domId); + if (!mcpId) { + mcpId = domId; + state.domToMcpId.set(domId, mcpId); + state.mcpToDomId.set(mcpId, domId); + } + state.drafts.delete(mcpId); + const titleEl = el.querySelector(".session-title, [data-session-title]") ?? el; + const rawTitle = (el.getAttribute("data-session-title") || elText(titleEl)).trim(); + state.sessions.set(mcpId, { title: rawTitle }); + if ( + domId === activeDomAttr || + el.getAttribute("aria-selected") === "true" || + el.getAttribute("aria-current") === "true" || + el.classList.contains("active") + ) { + state.activeMcpId = mcpId; + } + } + if (activeDomAttr) { + const mapped = state.domToMcpId.get(activeDomAttr) ?? activeDomAttr; + state.domToMcpId.set(activeDomAttr, mapped); + state.mcpToDomId.set(mapped, activeDomAttr); + state.activeMcpId = mapped; + if (!state.sessions.has(mapped)) { + const headerTitle = panel.querySelector(".agent-session-title, [data-active-session-title]"); + state.sessions.set(mapped, { title: headerTitle ? elText(headerTitle).trim() : "" }); + } + } + + const out: Session[] = []; + for (const draftId of state.drafts) { + out.push({ session_id: draftId, title: "", persisted: false }); + } + for (const [session_id, meta] of state.sessions.entries()) { + if (!state.drafts.has(session_id)) { + out.push({ session_id, title: meta.title, persisted: true }); + } + } + return out; +} + +/** Opens the session switcher menu if present so hidden session entries become inspectable. */ +async function withSessionListOpen( + panel: HTMLElement, + fn: () => Promise, +): Promise { + const trigger = Array.from(panel.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:sessions|chat history|history|previous chats|conversations)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${b.getAttribute("title") || ""} ${elText(b)}`, + ), + ); + if (!trigger) return await fn(); + const alreadyOpen = Boolean( + Array.from( + document.querySelectorAll( + 'flow-agent-panel [data-session-id], .cdk-overlay-pane [data-session-id], [data-session-menu-open="true"]', + ), + ).some((el) => el.getClientRects().length > 0), + ); + if (!alreadyOpen) { + trigger.click(); + await delay(150); + } + try { + return await fn(); + } finally { + if (!alreadyOpen && document.querySelector(".cdk-overlay-pane [data-session-id]")) { + await dismissOverlay(); + } + } +} + +/** Switches the panel UI to display `mcpId`. */ +async function selectUiSession( + panel: HTMLElement, + state: UiAgentState, + mcpId: string, +): Promise { + if (state.activeMcpId === mcpId) return true; + const domId = state.mcpToDomId.get(mcpId) ?? mcpId; + return await withSessionListOpen(panel, async () => { + const item = Array.from( + document.querySelectorAll("[data-session-id]"), + ).find((el) => el.getAttribute("data-session-id") === domId && el.getClientRects().length > 0); + if (!item) return false; + const clickTarget = item.querySelector("button, a, .session-select") ?? item; + clickTarget.click(); + await delay(180); + state.activeMcpId = mcpId; + return true; + }); +} + +/** Submits a new session or follow-up message through the Agent composer UI. */ +async function sendUiMessage( + panel: HTMLElement, + state: UiAgentState, + req: AgentRequest, + files: File[], +): Promise> { + const sessionId = req.session_id || ""; + if (!sessionId) return uiFailure("agent_session_id_required"); + + if (req.action === "create_session") { + const existingTurns = parseRenderedTurns(panel); + if (existingTurns.length > 0 || state.activeMcpId) { + const newChatBtn = Array.from( + panel.querySelectorAll('button, [role="button"]'), + ).find( + (b) => + isVisibleEnabled(b) && + /\b(?:new chat|new session|new conversation|start new)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${b.getAttribute("title") || ""} ${elText(b)}`, + ), + ); + if (newChatBtn) { + newChatBtn.click(); + await delay(180); + } + } + } else { + const switched = await selectUiSession(panel, state, sessionId); + if (!switched && !state.sessions.has(sessionId) && !state.drafts.has(sessionId)) { + return uiFailure("agent_session_not_found", { session_id: sessionId }); + } + } + + const beforeTurns = parseRenderedTurns(panel); + if (beforeTurns.at(-1)?.status === "in_progress") { + return uiFailure("agent_turn_active_or_unavailable"); + } + + const assetIds = req.asset_ids?.map((s) => s.trim()).filter(Boolean) ?? []; + const attached = await attachComposerItems(panel, assetIds, files); + if (!attached.ok) return uiFailure(attached.error, { session_id: sessionId }); + + const tb = findAgentTextbox(panel); + if (!tb) return uiFailure("agent_prompt_textbox_not_found"); + const text = req.message ?? ""; + if (tb instanceof HTMLTextAreaElement || tb instanceof HTMLInputElement) { + tb.focus(); + setNativeValue(tb, text, true); + } else { + const written = await writePromptBox(tb, text, { + seeds: [panel.querySelector("flow-creative-agent-prompt-box"), panel], + strictSync: false, + trySettingsClick: false, + }); + if (!written.ok) { + tb.focus(); + tb.textContent = text; + tb.dispatchEvent(new InputEvent("input", { bubbles: true, data: text })); + } + } + await delay(100); + + const sendBtn = findSendButton(panel); + if (!sendBtn) return uiFailure("agent_send_button_not_found"); + sendBtn.click(); + + const wantTurn = beforeTurns.length + 1; + let observed: UiFormattedTurn | undefined; + for (let i = 0; i < 40; i++) { + await delay(100); + const nowTurns = parseRenderedTurns(panel); + observed = + nowTurns.find((t) => t.turn === wantTurn) ?? + (nowTurns.length > beforeTurns.length ? nowTurns.at(-1) : undefined); + if (observed) break; + } + + let domActiveId = panel.getAttribute("data-active-session-id") || ""; + if (!domActiveId && req.action === "create_session") { + domActiveId = await withSessionListOpen(panel, async () => { + const cur = document.querySelector( + '[data-session-id][aria-current="true"], [data-session-id][aria-selected="true"], [data-session-id].active', + ); + return cur?.getAttribute("data-session-id") || ""; + }); + } + domActiveId = domActiveId || (state.mcpToDomId.get(sessionId) ?? sessionId); + state.drafts.delete(sessionId); + state.mcpToDomId.set(sessionId, domActiveId); + state.domToMcpId.set(domActiveId, sessionId); + state.activeMcpId = sessionId; + const headerTitle = panel.querySelector(".agent-session-title, [data-active-session-title]"); + const title = headerTitle + ? elText(headerTitle).trim() + : (state.sessions.get(sessionId)?.title ?? text.slice(0, 40)); + state.sessions.set(sessionId, { title }); + + if (!observed) { + return uiFailure("agent_submission_not_observed", { session_id: sessionId, turn: wantTurn }); + } + return { + ok: true, + session_id: sessionId, + title, + persisted: true, + turn: observed, + ...(attached.uploadedIds.length > 0 ? { uploaded_asset_ids: attached.uploadedIds } : {}), + }; +} + +/** Executes an `AgentRequest` through the workspace Agent panel UI fallback. */ +export async function agentUiOp( + request: AgentRequest, + files: File[], +): Promise> { + if (!onProject(request.project_id)) return uiFailure("agent_project_changed"); + const panel = await ensureAgentPanelOpen(); + if (!panel) return uiFailure("agent_panel_not_found"); + if (!uiState || uiState.projectId !== request.project_id) { + await agentUiBind(request.project_id); + } + if (!uiState) return uiFailure("agent_project_changed"); + + if (request.action === "get_settings" || request.action === "update_settings") { + if (request.action === "update_settings" && agentUiBusy(request.project_id)) { + return uiFailure("agent_turn_active"); + } + return await agentSettingsUiOp(request.project_id, request.settings ?? undefined); + } + + if (request.action === "list_sessions") { + const sessions = await withSessionListOpen(panel, async () => + syncSessionsFromDom(panel, uiState!), + ); + const canSend = Boolean(findAgentTextbox(panel)) && !agentUiBusy(request.project_id); + return { + ok: true, + project_id: request.project_id, + can_send: canSend, + sessions, + }; + } + + const id = request.session_id; + if (!id) return uiFailure("agent_session_id_required"); + + if (request.action === "create_session" || request.action === "send_message") { + return await sendUiMessage(panel, uiState, request, files); + } + + const allSessions = await withSessionListOpen(panel, async () => + syncSessionsFromDom(panel, uiState!), + ); + const session = allSessions.find((s) => s.session_id === id); + if (!session) return uiFailure("agent_session_not_found", { session_id: id }); + + if (request.action === "rename_session") { + if (!session.persisted) return uiFailure("agent_session_not_saved", { session_id: id }); + await selectUiSession(panel, uiState, id); + const title = request.title?.trim() ?? ""; + const domId = uiState.mcpToDomId.get(id) ?? id; + await withSessionListOpen(panel, async () => { + const row = + document.querySelector(`[data-session-id="${CSS.escape(domId)}"]`) ?? panel; + const renameBtn = Array.from(row.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\brename\b/i.test( + `${b.getAttribute("aria-label") || ""} ${b.getAttribute("title") || ""} ${elText(b)}`, + ), + ); + renameBtn?.click(); + await delay(120); + const input = + document.querySelector( + '[data-session-rename-input], input[aria-label*="Session title" i], input[aria-label*="Rename" i]', + ) ?? row.querySelector("input"); + if (input) { + input.focus(); + setNativeValue(input, title, true); + input.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true }), + ); + input.dispatchEvent(new FocusEvent("blur", { bubbles: true })); + await delay(120); + } + }); + uiState.sessions.set(id, { title }); + return { ok: true, ...session, title }; + } + + if (request.action === "delete_session") { + if (!session.persisted) return uiFailure("agent_session_not_saved", { session_id: id }); + const domId = uiState.mcpToDomId.get(id) ?? id; + await withSessionListOpen(panel, async () => { + const row = + document.querySelector(`[data-session-id="${CSS.escape(domId)}"]`) ?? panel; + const delBtn = Array.from(row.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:delete|remove)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${b.getAttribute("title") || ""} ${elText(b)}`, + ), + ); + delBtn?.click(); + await delay(150); + const dialog = document.querySelector('[role="dialog"], [role="alertdialog"]'); + if (dialog) clickButtonByRegex(/^(?:delete|remove|confirm|yes)$/i, dialog); + await delay(150); + }); + uiState.sessions.delete(id); + uiState.mcpToDomId.delete(id); + uiState.domToMcpId.delete(domId); + if (uiState.activeMcpId === id) uiState.activeMcpId = null; + return { ok: true, ...session, deleted: true }; + } + + await selectUiSession(panel, uiState, id); + if (request.action === "respond") { + return await respondViaUi(panel, session, request); + } + + if (request.action === "stop") { + const turns = parseRenderedTurns(panel); + const latest = turns.at(-1); + if (!latest || latest.status !== "in_progress" || latest.turn !== request.turn) { + return uiFailure("agent_turn_not_active"); + } + const stopBtn = Array.from(panel.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:stop|cancel generation)\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!stopBtn) return uiFailure("agent_stop_button_not_found"); + stopBtn.click(); + await delay(200); + return { ok: true, ...session, turn: parseRenderedTurns(panel).at(-1) }; + } + + if (request.action === "resume") { + const turns = parseRenderedTurns(panel); + const latest = turns.at(-1); + const resumeBtn = Array.from( + panel.querySelectorAll('button, [role="button"]'), + ).find( + (b) => + isVisibleEnabled(b) && + /\b(?:resume|continue|retry)\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!latest || latest.turn !== request.turn || !resumeBtn) { + return uiFailure("agent_turn_cannot_resume"); + } + resumeBtn.click(); + await delay(200); + return { ok: true, ...session, turn: parseRenderedTurns(panel).at(-1) }; + } + + const turns = parseRenderedTurns(panel); + if (request.action === "get_turn") { + const found = turns.find((t) => t.turn === request.turn); + return found ? { ok: true, ...session, turn: found } : uiFailure("agent_turn_not_found"); + } + + const end = request.before_turn ? Math.min(request.before_turn - 1, turns.length) : turns.length; + const start = Math.max(0, end - (request.limit ?? 20)); + return { + ok: true, + ...session, + turns: turns.slice(start, end), + next_before_turn: start > 0 ? start + 1 : null, + }; +} diff --git a/ts/agent_ui_dom.ts b/ts/agent_ui_dom.ts new file mode 100644 index 0000000..82f5bc5 --- /dev/null +++ b/ts/agent_ui_dom.ts @@ -0,0 +1,537 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Parse Agent panel DOM turns and drive composer attachments and decision cards. + +import { pickerElementMatches, type PickerMatchTarget } from "./angular"; +import type { AgentDecision, AgentRequest, PendingAction, Session } from "./agent_protocol"; +import { + clickButtonByRegex, + delay, + dismissOverlay, + elText, + fifeBase, + isVisibleEnabled, + setNativeValue, +} from "./dom"; +import { uploadUiAction } from "./open_upload_trigger"; +import { readStoreSnapshot } from "./read_store_snapshot"; + +/** Normalized turn object returned by `get_turn`, `list_messages`, `send_message`, and `respond`. */ +export interface UiFormattedTurn { + /** One-based turn index in the session. */ + turn: number; + /** Turn lifecycle status. */ + status: "in_progress" | "action_required" | "completed" | "failed" | "stopped" | "unknown"; + /** Optional response ID from DOM attributes. */ + response_id?: string; + /** Connection status when `in_progress`. */ + connected?: boolean; + /** User prompt and attachments on this turn. */ + user: { + text: string; + attachment_media_ids?: string[]; + attachment_character_ids?: string[]; + }; + /** Assistant reply text, generated media, and rich blocks. */ + assistant: { + text: string; + media: Array<{ media_id: string; status: string; error?: string }>; + rich_content: unknown[]; + }; + /** Pending user decisions on the active/latest turn. */ + pending_actions: PendingAction[]; + /** Error message when `status === "failed"`. */ + error?: string; +} + +/** Formats an error payload for MCP callers. */ +export function uiFailure( + error: string, + extra: Record = {}, +): Record { + return { ok: false, error, ...extra }; +} + +/** Reads the composer textbox inside the Agent panel. */ +export function findAgentTextbox(panel: HTMLElement): HTMLElement | null { + const scope = panel.querySelector("flow-creative-agent-prompt-box") ?? panel; + const candidates = Array.from( + scope.querySelectorAll( + '.ProseMirror[contenteditable="true"], [role="textbox"][contenteditable="true"], textarea, input[type="text"]', + ), + ).filter( + (el) => + el.getClientRects().length > 0 && + !el.closest('[data-agent-settings], [data-action-type="question"]'), + ); + return candidates[0] ?? null; +} + +/** Finds the Send / Submit button in the Agent composer. */ +export function findSendButton(panel: HTMLElement): HTMLElement | null { + const scope = panel.querySelector("flow-creative-agent-prompt-box") ?? panel; + return ( + Array.from(scope.querySelectorAll('button, [role="button"]')).find((el) => { + if (!isVisibleEnabled(el)) return false; + const label = `${el.getAttribute("aria-label") || ""} ${el.getAttribute("data-action") || ""} ${elText(el)}`.trim(); + return /\b(?:send|submit|ask agent|arrow_upward|arrow_forward)\b/i.test(label); + }) ?? null + ); +} + +/** Parses pending permission, question, and plan cards inside a turn element. */ +function parsePendingActions(turnEl: Element, isLatest: boolean): PendingAction[] { + if (!isLatest) return []; + const actions: PendingAction[] = []; + + for (const card of turnEl.querySelectorAll( + 'flow-agent-permission-card, [data-action-type="permission"], .permission-card', + )) { + if (card.getClientRects().length === 0 || card.getAttribute("data-resolved") === "true") { + continue; + } + const approveBtn = Array.from(card.querySelectorAll("button")).find((b) => + /\bapprove\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!approveBtn || approveBtn.disabled) continue; + const txt = elText(card); + const credits = + Number.parseInt( + card.getAttribute("data-credits") || /(\d+)\s*credits?/i.exec(txt)?.[1] || "0", + 10, + ) || 0; + const image_count = + Number.parseInt( + card.getAttribute("data-image-count") || /(\d+)\s*images?/i.exec(txt)?.[1] || "0", + 10, + ) || 0; + const video_count = + Number.parseInt( + card.getAttribute("data-video-count") || /(\d+)\s*videos?/i.exec(txt)?.[1] || "0", + 10, + ) || 0; + actions.push({ + type: "permission", + action_id: card.getAttribute("data-action-id") || "ui-permission", + image_count, + video_count, + credits, + }); + } + + for (const card of turnEl.querySelectorAll( + 'flow-agent-question-card, [data-action-type="question"], .question-card', + )) { + if (card.getClientRects().length === 0 || card.getAttribute("data-resolved") === "true") { + continue; + } + const qNodes = card.querySelectorAll("[data-question-id], .agent-question-item"); + const roots = qNodes.length > 0 ? Array.from(qNodes) : [card]; + const questions = roots.map((qEl, idx) => { + const qid = qEl.getAttribute("data-question-id") || `q-${idx + 1}`; + const promptEl = qEl.querySelector(".question-text, [data-question-text], h4, p"); + const multiple = + qEl.getAttribute("data-multiple") === "true" || + Boolean(qEl.querySelector('input[type="checkbox"]')); + const optEls = Array.from( + qEl.querySelectorAll("[data-option-id], .question-option"), + ); + const options = optEls.map((oEl, oIdx) => ({ + option_id: oEl.getAttribute("data-option-id") || `opt-${oIdx + 1}`, + label: (oEl.getAttribute("data-label") || elText(oEl)).trim(), + allows_text: + oEl.getAttribute("data-allows-text") === "true" || + Boolean(oEl.querySelector('input[type="text"], textarea')), + })); + return { + question_id: qid, + text: promptEl ? elText(promptEl).trim() : elText(qEl).trim(), + multiple, + options, + }; + }); + if (questions.some((q) => q.options.length > 0)) { + actions.push({ + type: "question", + action_id: card.getAttribute("data-action-id") || "ui-question", + questions, + }); + } + } + + for (const card of turnEl.querySelectorAll( + 'flow-agent-plan-card, [data-action-type="plan"], .plan-card', + )) { + if (card.getClientRects().length === 0 || card.getAttribute("data-resolved") === "true") { + continue; + } + const hasRunBtn = Array.from(card.querySelectorAll("button")).some( + (b) => + !b.disabled && + /\b(?:run full plan|previz)\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!hasRunBtn) continue; + const titleEl = card.querySelector(".plan-title, [data-plan-title], h3, h4"); + const descEl = card.querySelector(".plan-description, [data-plan-description], p"); + actions.push({ + type: "plan", + action_id: card.getAttribute("data-action-id") || "plan", + title: titleEl ? elText(titleEl).trim() : "Plan", + description: descEl ? elText(descEl).trim() : "", + decisions: ["run_full_plan", "previz"], + }); + } + + return actions; +} + +/** Parses rendered conversation turns from the workspace Agent panel DOM. */ +export function parseRenderedTurns(panel: HTMLElement): UiFormattedTurn[] { + const turnEls = Array.from( + panel.querySelectorAll("flow-agent-turn, [data-turn], .agent-turn"), + ).filter((el) => el.getClientRects().length > 0); + + return turnEls.map((el, idx) => { + const number = Number.parseInt(el.getAttribute("data-turn") || "", 10) || idx + 1; + const isLatest = idx === turnEls.length - 1; + const rawStatus = (el.getAttribute("data-status") || "").toLowerCase(); + const isStreaming = + rawStatus === "in_progress" || + el.getAttribute("aria-busy") === "true" || + Boolean(el.querySelector('.streaming-indicator, [aria-busy="true"]')); + + const userEl = el.querySelector(".user-turn, [data-role='user'], .user-message"); + const assistantEl = el.querySelector( + ".assistant-turn, [data-role='assistant'], .assistant-message", + ); + const userText = userEl ? elText(userEl).trim() : (el.getAttribute("data-user-text") || ""); + const assistantText = assistantEl + ? elText(assistantEl).trim() + : (el.getAttribute("data-assistant-text") || ""); + + const attMedia = Array.from(el.querySelectorAll("[data-attachment-media-id]")) + .map((n) => n.getAttribute("data-attachment-media-id") || "") + .filter(Boolean); + const attChars = Array.from(el.querySelectorAll("[data-attachment-character-id]")) + .map((n) => n.getAttribute("data-attachment-character-id") || "") + .filter(Boolean); + + const media = Array.from( + (assistantEl ?? el).querySelectorAll( + "[data-generated-media-id], [data-media-id]", + ), + ) + .filter((m) => !m.hasAttribute("data-attachment-media-id")) + .map((m) => ({ + media_id: + m.getAttribute("data-generated-media-id") || m.getAttribute("data-media-id") || "", + status: m.getAttribute("data-media-status") || "success", + error: m.getAttribute("data-media-error") || undefined, + })) + .filter((m) => Boolean(m.media_id)); + + const errEl = el.querySelector(".turn-error, [data-turn-error]"); + const errorMsg = + el.getAttribute("data-turn-error") || (errEl ? elText(errEl).trim() : "") || undefined; + + const pending = parsePendingActions(el, isLatest); + let status: UiFormattedTurn["status"] = "completed"; + if (pending.length > 0) status = "action_required"; + else if (isStreaming) status = "in_progress"; + else if (rawStatus === "stopped") status = "stopped"; + else if (rawStatus === "failed" || errorMsg) status = "failed"; + + return { + turn: number, + status, + response_id: el.getAttribute("data-response-id") || undefined, + connected: status === "in_progress" ? true : undefined, + user: { + text: userText, + ...(attMedia.length > 0 ? { attachment_media_ids: attMedia } : {}), + ...(attChars.length > 0 ? { attachment_character_ids: attChars } : {}), + }, + assistant: { + text: assistantText, + media, + rich_content: [], + }, + pending_actions: pending, + ...(errorMsg ? { error: errorMsg } : {}), + }; + }); +} + +/** Attaches project assets/characters and staged local files to the Agent composer via UI controls. */ +export async function attachComposerItems( + panel: HTMLElement, + assetIds: string[], + files: File[], +): Promise<{ ok: true; uploadedIds: string[] } | { ok: false; error: string }> { + const liveComposer = (): HTMLElement => + panel.querySelector("flow-creative-agent-prompt-box") ?? panel; + const snap = assetIds.length > 0 ? readStoreSnapshot(true) : null; + + for (const rawId of assetIds) { + const id = rawId.trim(); + if (!id) continue; + const composer = liveComposer(); + const asset = snap?.ok ? snap.assets?.find((a) => a.id === id) : undefined; + const target: PickerMatchTarget = { + id, + primaryMediaId: asset?.primary_media_id ?? null, + lowName: asset?.name ? asset.name.toLowerCase() : undefined, + url: asset?.url ?? null, + fife: fifeBase(asset?.url ?? ""), + }; + + const addBtn = Array.from(composer.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /\b(?:add|attach|ingredient|reference|asset|\+)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${b.getAttribute("title") || ""} ${elText(b)}`, + ), + ); + if (!addBtn) return { ok: false, error: "agent_attachment_picker_not_found" }; + addBtn.click(); + await delay(180); + + const pickerScope = + document.querySelector( + ".cdk-overlay-pane, [data-agent-asset-picker], .ingredient-picker", + ) ?? document.body; + const items = Array.from( + pickerScope.querySelectorAll( + "[data-asset-id], [data-tile-id], [data-character-id], flow-grid-tile-container, .picker-item, [role='option'], [role='menuitem']", + ), + ).filter((el) => el.getClientRects().length > 0); + const match = + items.find( + (el) => + el.getAttribute("data-asset-id") === id || + el.getAttribute("data-tile-id") === id || + el.getAttribute("data-character-id") === id, + ) ?? items.find((el) => pickerElementMatches(el, target)); + if (!match) { + await dismissOverlay(); + return { ok: false, error: `agent_attachment_not_found:${id}` }; + } + match.click(); + await delay(150); + const confirmPick = pickerScope.querySelector( + 'button[data-action="confirm-attachments"], button[aria-label="Done"]', + ); + if (confirmPick && isVisibleEnabled(confirmPick)) { + confirmPick.click(); + await delay(120); + } + } + + const uploadedIds: string[] = []; + if (files.length > 0) { + const composer = liveComposer(); + const readChipIds = (): string[] => + Array.from(liveComposer().querySelectorAll("[data-uploaded-asset-id], [data-asset-id]")) + .map( + (n) => n.getAttribute("data-uploaded-asset-id") || n.getAttribute("data-asset-id") || "", + ) + .filter(Boolean); + const beforeChips = new Set(readChipIds()); + const snapBefore = readStoreSnapshot(true); + const beforeAssets = new Set(snapBefore.ok ? (snapBefore.assets?.map((a) => a.id) ?? []) : []); + let fileInput = composer.querySelector('input[type="file"]'); + if (!fileInput) { + let captured: HTMLInputElement | null = null; + const origClick = HTMLInputElement.prototype.click; + HTMLInputElement.prototype.click = function (this: HTMLInputElement): void { + if (this.type === "file") { + captured = this; + return; + } + origClick.call(this); + }; + try { + const upTrigger = Array.from( + composer.querySelectorAll('button, [role="button"]'), + ).find( + (b) => + isVisibleEnabled(b) && + /\b(?:upload|attach file|add file|add_photo_alternate|\+)\b/i.test( + `${b.getAttribute("aria-label") || ""} ${elText(b)}`, + ), + ); + upTrigger?.click(); + await delay(120); + if (!captured) { + const menuUp = Array.from( + document.querySelectorAll('[role="menuitem"], .cdk-overlay-pane button'), + ).find( + (b) => + isVisibleEnabled(b) && + /\bupload\b/i.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + menuUp?.click(); + } + } finally { + HTMLInputElement.prototype.click = origClick; + } + fileInput = + captured ?? + document.querySelector( + 'flow-agent-panel input[type="file"], input[type="file"][data-agent-upload]', + ); + } + if (!fileInput) return { ok: false, error: "agent_file_input_not_found" }; + + const dt = new DataTransfer(); + for (const file of files) dt.items.add(file); + fileInput.files = dt.files; + fileInput.dispatchEvent(new Event("input", { bubbles: true })); + fileInput.dispatchEvent(new Event("change", { bubbles: true })); + for (let i = 0; i < 15 && uploadedIds.length < files.length; i++) { + await delay(120); + uploadUiAction("accept_consent"); + for (const cid of readChipIds()) { + if (!beforeChips.has(cid) && !uploadedIds.includes(cid)) uploadedIds.push(cid); + } + const snapAfter = readStoreSnapshot(true); + if (snapAfter.ok) { + for (const a of snapAfter.assets ?? []) { + if (!beforeAssets.has(a.id) && !uploadedIds.includes(a.id)) uploadedIds.push(a.id); + } + } + } + } + + return { ok: true, uploadedIds }; +} + +/** Validates question answers against the pending question action schema. */ +function validateQuestionAnswers( + action: Extract, + answers: NonNullable, +): boolean { + const seen = new Set(); + for (const ans of answers) { + const q = action.questions.find((item) => item.question_id === ans.question_id); + const text = ans.text?.trim(); + const opts = new Set(ans.option_ids); + if ( + !q || + seen.has(ans.question_id) || + opts.size !== ans.option_ids.length || + (!q.multiple && opts.size > 1) || + (!text && opts.size === 0) || + [...opts].some((oid) => !q.options.some((o) => o.option_id === oid)) || + (text && (!q.options.some((o) => o.allows_text) || (!q.multiple && opts.size > 0))) + ) { + return false; + } + seen.add(ans.question_id); + } + return answers.length > 0; +} + +/** Clicks the matching permission, question, or plan decision control in the Agent panel UI. */ +export async function respondViaUi( + panel: HTMLElement, + session: Session, + req: AgentRequest, +): Promise> { + const turns = parseRenderedTurns(panel); + const latest = turns.at(-1); + const action = + latest && latest.turn === req.turn + ? latest.pending_actions.find((a) => a.action_id === req.action_id) + : undefined; + if (!action) return uiFailure("agent_action_not_pending"); + + const turnEls = Array.from( + panel.querySelectorAll("flow-agent-turn, [data-turn], .agent-turn"), + ).filter((el) => el.getClientRects().length > 0); + const latestEl = turnEls.at(-1); + if (!latestEl) return uiFailure("agent_action_not_pending"); + + if (action.type === "permission") { + const labelMap: Partial> = { + approve: /^(?:approve|allow|confirm)$/i, + approve_and_remember: /^(?:always approve|always allow|approve and remember)$/i, + deny: /^(?:reject|deny|cancel)$/i, + }; + const pattern = req.decision ? labelMap[req.decision] : undefined; + if (!pattern) return uiFailure("invalid_agent_permission_decision"); + const card = + latestEl.querySelector( + `[data-action-id="${CSS.escape(action.action_id)}"], flow-agent-permission-card, [data-action-type="permission"], .permission-card`, + ) ?? latestEl; + if (!clickButtonByRegex(pattern, card)) { + return uiFailure("agent_permission_button_not_found"); + } + await delay(200); + return { ok: true, ...session, turn: parseRenderedTurns(panel).at(-1) }; + } + + if (action.type === "question") { + if (!req.answers || !validateQuestionAnswers(action, req.answers)) { + return uiFailure("invalid_agent_question_answers"); + } + const card = + latestEl.querySelector( + `[data-action-id="${CSS.escape(action.action_id)}"], flow-agent-question-card, [data-action-type="question"], .question-card`, + ) ?? latestEl; + for (const ans of req.answers) { + const qScope = + card.querySelector(`[data-question-id="${CSS.escape(ans.question_id)}"]`) ?? + card; + for (const oid of ans.option_ids) { + const optEl = + qScope.querySelector(`[data-option-id="${CSS.escape(oid)}"]`) ?? + Array.from(qScope.querySelectorAll(".question-option, button, label")).find( + (el) => el.getAttribute("data-option-id") === oid, + ); + if (!optEl) return uiFailure("agent_question_option_not_found"); + (optEl.querySelector("button, input") ?? optEl).click(); + await delay(80); + } + if (ans.text?.trim()) { + const freeInput = qScope.querySelector( + 'input[type="text"], textarea', + ); + if (!freeInput) return uiFailure("agent_question_text_input_not_found"); + freeInput.focus(); + setNativeValue(freeInput, ans.text.trim(), true); + await delay(80); + } + } + clickButtonByRegex(/^(?:submit|send|continue|confirm|next)$/i, card); + await delay(200); + return { ok: true, ...session, turn: parseRenderedTurns(panel).at(-1) }; + } + + const planLabels: Partial> = { + run_full_plan: /\brun full plan\b/i, + previz: /\bpreviz\b/i, + }; + const planPattern = req.decision ? planLabels[req.decision] : undefined; + if (!planPattern) return uiFailure("invalid_agent_plan_decision"); + const card = + latestEl.querySelector( + `[data-action-id="${CSS.escape(action.action_id)}"], flow-agent-plan-card, [data-action-type="plan"], .plan-card`, + ) ?? latestEl; + const btn = Array.from(card.querySelectorAll("button, [role='button']")).find( + (b) => + isVisibleEnabled(b) && + planPattern.test(`${b.getAttribute("aria-label") || ""} ${elText(b)}`), + ); + if (!btn) return uiFailure("agent_plan_button_not_found"); + btn.click(); + for (let i = 0; i < 30; i++) { + await delay(100); + const updated = parseRenderedTurns(panel); + if (updated.length > turns.length) { + return { ok: true, ...session, turn: updated.at(-1) }; + } + } + return { ok: true, ...session, turn: parseRenderedTurns(panel).at(-1) }; +} diff --git a/ts/angular.ts b/ts/angular.ts index 671b201..48ec802 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -4,7 +4,7 @@ // Shared Angular Ivy LView traversal, router lookup, and scene creation helpers. import { delay, elText, fifeBase } from "./dom"; -import { frontendBuild, readBuildLabel } from "./frontend_builds"; +import { inferCreateSceneShape } from "./mutation_shapes"; import { runtimeState } from "./state"; import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"; @@ -210,13 +210,19 @@ export function findRouter(): AngularRouter | null { } /** Maximum time to confirm scene creation and the initial clip load. */ -const SCENE_CREATE_TIMEOUT_MS = 30_000; +const SCENE_CREATE_TIMEOUT_MS = 15_000; /** Reads the ID from a native scene creation result. */ function readSceneId(scene: unknown): string | undefined { if (typeof scene === "string" && scene) return scene; + if (!scene || typeof scene !== "object") return undefined; const id = readOwn(scene, "id"); - return typeof id === "string" && id ? id : undefined; + if (typeof id === "string" && id) return id; + for (const key of Object.keys(scene)) { + const nestedId = readOwn(readOwn(scene, key), "id"); + if (typeof nestedId === "string" && nestedId) return nestedId; + } + return undefined; } /** Returns the IDs of the confirmed scenes in the store. */ @@ -231,28 +237,39 @@ export async function createScene( getMap: () => Map | null | undefined, workflowIds: string[], ): Promise<{ ok: boolean; id?: string; error?: string }> { + const shape = inferCreateSceneShape(); + if (!shape.ok) { + return { + ok: false, + error: `${shape.reason}:${shape.check.name}:${shape.check.detail}`, + }; + } const before = new Set(sceneIds(getMap())); - const resultField = frontendBuild(readBuildLabel())?.projectStore.mutations?.sceneCreated ?? "VWa"; + const resultField = shape.format.sceneCreated; let confirmedId: string | undefined; let failure: string | undefined; const completion = { - resolve: (scene: unknown) => { confirmedId ??= readSceneId(scene); }, + resolve: (scene: unknown) => { + confirmedId ??= readSceneId(scene); + }, reject: (error: unknown) => { failure ??= error instanceof Error ? error.message : String(error ?? "create_scene_failed"); }, }; const deadline = performance.now() + SCENE_CREATE_TIMEOUT_MS; - void Promise.resolve().then(() => helper.mutate({ - type: "create_scene", - rg: workflowIds, - Fc: undefined, - wc: undefined, - aspectRatio: 1, - De: completion, - ve: completion, - })).then((response) => { - completion.resolve(readOwn(response, resultField)); - }, completion.reject); + void Promise.resolve() + .then(() => + helper.mutate({ + type: "create_scene", + workflows: workflowIds, + aspectRatio: 1, + completion, + }), + ) + .then((response) => { + const fromField = resultField ? readOwn(response, resultField) : undefined; + completion.resolve(fromField ?? response); + }, completion.reject); while (performance.now() < deadline) { if (confirmedId) return { ok: true, id: confirmedId }; diff --git a/ts/asset_trash.ts b/ts/asset_trash.ts index 934b0e9..973ab58 100644 --- a/ts/asset_trash.ts +++ b/ts/asset_trash.ts @@ -3,7 +3,9 @@ // Move an asset to trash through the active project store. +import { readOwn } from "./angular"; import { isTrashedTile } from "./dom"; +import { readBuildLabel } from "./frontend_builds"; import { assetTrashCompatibility } from "./frontend_compatibility"; import { mutateAndVerify, projectMutationPending, projectsToRefresh, projectStore, readProjectStore, refreshAfterUnknown } from "./project_store"; import { sceneContents } from "./scene_tiles"; @@ -38,10 +40,23 @@ export async function trashAssetOp(projectId: string, session: string, id: strin const { format } = support; const tile = tiles.get(id); if (tile?.type === "COLLECTION") return { ok: false, error: "collection_path_required" }; - if (tile && isTrashedTile(tile)) return { ok: true, method: "already_trashed", confirmed: true }; + if (tile && (isTrashedTile(tile) || readOwn(tile, format.trashed) === true)) { + return { ok: true, method: "already_trashed", confirmed: true }; + } if (tile ? tile.isPending || !TRASHABLE_TYPES.has(tile.type ?? "") : !isSceneClip(tiles.values(), id)) { return { ok: false, error: "asset_not_found", id }; } + if (!tile && !format.sceneWorkflows) { + return { + ok: false, + error: "unsupported_front_end", + build: readBuildLabel(), + operation: "asset_trash_store", + failed_checks: [ + { name: "scene_clip_delete_shape", ok: false, detail: "no verified sceneWorkflows field" }, + ], + }; + } const payload = tile ? { type: "batch_set_tiles_trashed", @@ -51,7 +66,7 @@ export async function trashAssetOp(projectId: string, session: string, id: strin const after = await mutateAndVerify(store, payload, (fresh) => { if (!tile) return !isSceneClip(fresh.values(), id); const state = fresh.get(id); - return !state || isTrashedTile(state); + return !state || isTrashedTile(state) || readOwn(state, format.trashed) === true; }); const method = tile ? `batch_set_tiles_trashed:${format.entries}` : "batch_delete_tiles:scene_clip"; return after diff --git a/ts/character_bio.ts b/ts/character_bio.ts index eaacd4e..3ce7a7d 100644 --- a/ts/character_bio.ts +++ b/ts/character_bio.ts @@ -30,21 +30,67 @@ function entityField(message: unknown, field: number): unknown { : readOwn(sparse, String(field)) ?? message[field - 1]; } +/** Extracts personality notes from a candidate character entity with `toJSON` or `toObject`. */ +function readEntityNotes(entity: unknown): string | null { + if (!entity || typeof entity !== "object") return null; + const serialize = readOwn(entity, "toJSON"); + if (typeof serialize === "function") { + try { + // The nested fields are entity_info (4), character_info (3), and personality_notes (3). + const info = entityField(entityField(serialize.call(entity), 4), 3); + if (Array.isArray(info)) { + const notes = entityField(info, 3); + if (notes == null) return ""; + if (typeof notes === "string") return notes; + } + } catch { + // Fall through to toObject check. + } + } + const toObj = readOwn(entity, "toObject"); + if (typeof toObj === "function") { + try { + const obj = toObj.call(entity) as unknown; + if (Array.isArray(obj) && obj.length >= 4 && (obj[3] == null || typeof obj[3] === "string")) { + return obj[3] ?? ""; + } + const charInfo = readOwn(readOwn(obj, "entityInfo"), "characterInfo"); + const notes = readOwn(charInfo, "personalityNotes"); + if (typeof notes === "string") return notes; + } catch { + return null; + } + } + return null; +} + /** Reads the notes from the character entity. Returns null when the entity cannot be read. */ export function characterPersonalityNotes(tile: FlowTile): string | null { - const entity = readOwn(tile, "Rc"); - const serialize = readOwn(entity, "toJSON"); - if (typeof serialize !== "function") return null; - try { - // The nested fields are entity_info (4), character_info (3), and personality_notes (3). - const info = entityField(entityField(serialize.call(entity), 4), 3); - if (!Array.isArray(info)) return null; - const notes = entityField(info, 3); - if (notes == null) return ""; - return typeof notes === "string" ? notes : null; - } catch { - return null; + if (!tile || typeof tile !== "object") return null; + const known = readEntityNotes(readOwn(tile, "Rc")); + if (known !== null) return known; + const matches = new Set(); + const inspect = (val: unknown): void => { + const extracted = readEntityNotes(val); + if (extracted !== null) matches.add(extracted); + }; + for (const key of Object.keys(tile)) { + const val = readOwn(tile, key); + if (!val || typeof val !== "object" || Array.isArray(val) || val instanceof Map) continue; + inspect(val); + for (const subKey of Object.keys(val).slice(0, 12)) { + const sub = readOwn(val, subKey); + if (sub && typeof sub === "object" && !Array.isArray(sub) && !(sub instanceof Map)) { + inspect(sub); + } + } + } + if (matches.size === 1) { + const [only] = matches; + return only; } + if (matches.size > 1) return null; + return typeof tile.personalityNotes === "string" ? tile.personalityNotes : null; } /** Returns true for a character that can receive new notes. */ diff --git a/ts/character_media.ts b/ts/character_media.ts index c52e5b3..46f4945 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -20,17 +20,15 @@ import { fifeBase, hoverProbe, isVisibleEnabled, - legacyMedia, pickTileUrl, setNativeValue, } from "./dom"; -import { frontendBuild, readBuildLabel, type CharacterPreviewFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; import { runtimeState } from "./state"; +import { discoverCharacterPreview, type BoundCharacterPreview } from "./store_shapes"; import type { CharacterMediaOpRequest, FlowMediaPayload, - NgLView, } from "./types"; /** Image slot in the character editor. */ @@ -39,27 +37,10 @@ type CharacterSlot = "portrait" | "body"; /** Maximum wait for the editor to select and load an upload slot. */ const UPLOAD_SLOT_TIMEOUT_MS = 30_000; -/** Character preview panel used to open the native picker and read slot state. */ -interface CharacterPreview { - /** Opens the picker for the active slot. */ - upload: () => unknown; - /** Reads one slot's media record. */ - media: (slot: CharacterSlot) => FlowMediaPayload | null | undefined; - /** Reads the source URL of the active slot. */ - source: () => unknown; - /** Reads the loading state of the active slot. */ - busy: () => unknown; -} - -/** Native methods used by the earlier preview panel. */ -const LEGACY_PREVIEW: CharacterPreviewFormat = { - lifecycle: "Ca", upload: "JR", marker: "Si", portrait: "ka", body: "ma", source: "psa", busy: "zy", -}; - /** Snapshot of character preview slot state read from component signals and DOM. */ interface PreviewSlotState { /** Resolved preview component instance when mounted. */ - previewComp: CharacterPreview | null; + previewComp: BoundCharacterPreview | null; /** Media record for the selected slot (`portrait` or `body`). */ slotMedia: FlowMediaPayload | null | undefined; /** Trimmed slot media identifier string. */ @@ -84,58 +65,6 @@ async function captureLViewAndClick(fn: () => void): Promise { }); } -/** 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 = frontendBuild(readBuildLabel())?.characterPreview ?? LEGACY_PREVIEW; - const roots = document.querySelectorAll( - "flow-character-preview-panel, flow-character-image-preview", - ); - const seen = new Set(); - for (const root of roots) { - const startLv = resolveLView(root); - if (!Array.isArray(startLv)) continue; - const queue: Array<[NgLView, number]> = [[startLv, 0]]; - while (queue.length > 0) { - const next = queue.shift(); - if (!next) break; - const [lv, depth] = next; - if (!Array.isArray(lv) || seen.has(lv)) continue; - seen.add(lv); - for (const slot of lv) { - if ( - slot && - typeof slot === "object" && - !(slot instanceof Node) && - !Array.isArray(slot) && - !(slot instanceof Map) && - !readOwn(readOwn(slot, format.lifecycle), "Va") && - typeof readOwn(slot, format.upload) === "function" && - typeof readOwn(slot, format.marker) === "function" - ) { - return { - upload: () => callPanel(slot, format.upload), - media: (which) => - legacyMedia(callPanel(slot, format[which]) as FlowMediaPayload | null | undefined), - source: () => callPanel(slot, format.source), - busy: () => callPanel(slot, format.busy), - }; - } - } - 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" @@ -145,15 +74,17 @@ function normSlot(raw: unknown): CharacterSlot { /** Reads current slot media, preview URLs, and busy indicators for `slot`. */ function readPreviewSlotState(slot: CharacterSlot): PreviewSlotState { - const previewComp = getCharacterPreviewInstance(); + const imgEl = document.querySelector( + "flow-character-image-preview img.preview-image[src], flow-character-image-preview img[src], flow-character-preview-panel img.preview-image[src], flow-character-preview-panel img[src]", + ); + const imgSrc = (imgEl?.getAttribute("src") || "").trim(); + const roots = document.querySelectorAll( + "flow-character-preview-panel, flow-character-image-preview", + ); + const previewComp = discoverCharacterPreview(roots, imgSrc, slot); const slotMedia = previewComp?.media(slot); const slotMediaId = String(slotMedia?.id || "").trim(); const compSrc = String(previewComp?.source() || "").trim(); - const imgSrc = ( - document - .querySelector("flow-character-image-preview img.preview-image[src]") - ?.getAttribute("src") || "" - ).trim(); const isAreaBusy = Boolean( document.querySelector( @@ -185,9 +116,22 @@ function findPreviewSlotButton(slot: CharacterSlot): HTMLButtonElement | undefin /** 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"); + if (button) { + return ( + button.classList.contains("chip-button-active") || + button.getAttribute("aria-pressed") === "true" || + button.getAttribute("aria-selected") === "true" + ); + } + if ( + document.querySelector( + `flow-character-image-preview[data-slot="${slot}"], flow-character-preview-panel[data-slot="${slot}"]`, + ) + ) { + return true; + } return slot === "portrait" && !findPreviewSlotButton("body") && - Boolean(document.querySelector("flow-character-image-preview")); + Boolean(document.querySelector("flow-character-image-preview, flow-character-preview-panel")); } /** Selects the requested slot and waits for the preview controls. */ @@ -267,9 +211,6 @@ export async function characterMediaOp( const controls = [...document.querySelectorAll("flow-character-preview-panel [mattooltip], flow-character-preview-panel button")]; await withLViewMapCapture(() => hoverProbe(controls.slice(0, 6))); state = readPreviewSlotState(wantSlot); - if (!state.previewComp && frontendBuild(readBuildLabel())?.characterPreview) { - return { ok: false, error: "character_preview_not_bound" }; - } } while (performance.now() < deadline) { if (!state.isAreaBusy && @@ -283,6 +224,49 @@ export async function characterMediaOp( const prevSrc = imgSrc || compSrc; const prevMediaId = slotMediaId; + /** Reveals hover controls on the preview image frame and searches for a delete or clear button. */ + const clearOccupiedSlotViaUi = async (): Promise => { + const frames = document.querySelectorAll( + "flow-character-image-preview .image-frame, flow-character-image-preview .image-area, flow-character-image-preview, flow-character-preview-panel", + ); + await hoverProbe(Array.from(frames).slice(0, 4), 40); + const revealedUpload = findPreviewUploadButton(); + if (revealedUpload) return revealedUpload; + let deleteBtn: HTMLElement | null = null; + for (const root of document.querySelectorAll( + "flow-character-image-preview, flow-character-preview-panel", + )) { + const hit = Array.from(root.querySelectorAll('button, [role="button"]')).find( + (el): el is HTMLElement => { + if (el.closest("flow-slot-chip-button, flow-character-form, flow-edit-character-footer")) { + return false; + } + if (!isVisibleEnabled(el)) return false; + const label = `${el.getAttribute("aria-label") || ""} ${el.getAttribute("title") || ""} ${elText(el)}`; + return /\b(?:delete(?:\s+image)?|remove(?:\s+image)?|clear|replace)\b/i.test(label); + }, + ); + if (hit) { + deleteBtn = hit; + break; + } + } + if (!deleteBtn) return null; + deleteBtn.click(); + await delay(150); + const dialog = document.querySelector('mat-dialog-container, [role="dialog"], [role="alertdialog"]'); + if (dialog) { + clickButtonByRegex(/^(?:delete|remove|confirm|yes)$/i, dialog); + await delay(150); + } + for (let i = 0; i < 30; i++) { + const up = findPreviewUploadButton(); + if (up) return up; + await delay(100); + } + return null; + }; + let capturedFileInput: HTMLInputElement | null = null; const origInputClick = HTMLInputElement.prototype.click; const origShowPicker = @@ -300,15 +284,20 @@ export async function characterMediaOp( }; } try { - const uploadBtn = findPreviewUploadButton(); - if (uploadBtn) { - const inner = uploadBtn.tagName === "FLOW-BUTTON" ? uploadBtn.querySelector("button") : null; - (inner instanceof HTMLElement ? inner : uploadBtn).click(); - } else if (previewComp && (prevMediaId || prevSrc)) { + let uploadBtn = findPreviewUploadButton(); + if (!uploadBtn && previewComp?.upload && (prevMediaId || prevSrc)) { void previewComp.upload(); } else { - const error = prevSrc && !previewComp ? "character_preview_not_bound" : "upload_button_not_found"; - return { ok: false, error }; + if (!uploadBtn && (prevMediaId || prevSrc)) { + uploadBtn = await clearOccupiedSlotViaUi(); + } + if (uploadBtn) { + const inner = uploadBtn.tagName === "FLOW-BUTTON" ? uploadBtn.querySelector("button") : null; + (inner instanceof HTMLElement ? inner : uploadBtn).click(); + } else if (!capturedFileInput) { + const error = prevSrc && !previewComp ? "character_preview_not_bound" : "upload_button_not_found"; + return { ok: false, error }; + } } await delay(250); } finally { @@ -335,10 +324,13 @@ export async function characterMediaOp( if (action === "check_upload") { const slot = normSlot(req?.slot); if (!isPreviewSlotSelected(slot)) return { ok: false, error: "character_upload_slot_changed" }; - const consentDialog = document.querySelector("flow-upload-consent-dialog"); - if (consentDialog && clickButtonByRegex(/^(?:i agree,\s*do not show again|i agree)$/i, consentDialog)) { - await delay(150); - return { ok: true, done: false, accepted_consent: true }; + for (const consentDialog of document.querySelectorAll( + 'flow-upload-consent-dialog, [data-testid="upload-consent-dialog"], mat-dialog-container, [role="dialog"], [role="alertdialog"]', + )) { + if (clickButtonByRegex(/^(?:i agree,\s*do not show again|i agree)$/i, consentDialog)) { + await delay(150); + return { ok: true, done: false, accepted_consent: true }; + } } const prevSrc = String(req?.prev_src || "").trim(); const prevMediaId = String(req?.prev_media_id || "").trim(); @@ -419,7 +411,7 @@ export async function characterMediaOp( const targetUrl = pickTileUrl(targetTile); const targetFife = fifeBase(targetUrl); - const previewCompBefore = getCharacterPreviewInstance(); + const previewCompBefore = readPreviewSlotState("portrait").previewComp; const portraitOccupied = Boolean(previewCompBefore?.media("portrait")?.id); const bodyOccupied = Boolean(previewCompBefore?.media("body")?.id); let wantBodySlot = false; diff --git a/ts/character_ops.ts b/ts/character_ops.ts index 1e9f426..57fba4b 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -3,11 +3,153 @@ // Open, finish, create, and update profile fields for Google Flow characters. -import { findRouter } from "./angular"; -import { clickButtonByRegex, delay, isVisibleEnabled, setNativeValue } from "./dom"; +import { findRouter, readOwn } from "./angular"; +import { clickButtonByRegex, delay, elText, isVisibleEnabled, setNativeValue } from "./dom"; +import { inferCreateEntityShape, inferSingleTileShape } from "./mutation_shapes"; import { clearStore, runtimeState } from "./state"; +import { isComponentDestroyed } from "./store_shapes"; import type { CharacterOpRequest } from "./types"; +/** Maximum wait for `create_entity` completion or character route creation. */ +const CHARACTER_CREATE_TIMEOUT_MS = 10_000; + +/** Finds the character personality textarea in the character editor form. */ +function findCharacterBioInput(): HTMLTextAreaElement | HTMLInputElement | null { + const direct = document.querySelector( + 'textarea[aria-label="Character personality"], textarea[aria-label*="personality" i], input[aria-label="Character personality"], flow-character-form textarea', + ); + if (direct instanceof HTMLTextAreaElement || direct instanceof HTMLInputElement) { + return direct; + } + for (const el of document.querySelectorAll("textarea")) { + if (el instanceof HTMLTextAreaElement && el.getClientRects().length > 0) { + const hint = `${el.getAttribute("aria-label") || ""} ${el.getAttribute("placeholder") || ""}`; + if (/personality|bio|description|notes|about/i.test(hint)) return el; + } + } + return null; +} + +/** Creates a character through workspace UI controls when direct `create_entity` cannot run. */ +async function createCharacterViaUi( + charName: string, + req: CharacterOpRequest, +): Promise> { + const knownCharIds = new Set(); + for (const link of document.querySelectorAll('a[href*="/character/"]')) { + const id = /\/character\/([^/?#]+)/.exec(link.getAttribute("href") || "")?.[1]; + if (id) knownCharIds.add(id); + } + for (const tile of document.querySelectorAll("flow-grid-tile-container[data-tile-id]")) { + const tid = tile.getAttribute("data-tile-id"); + if (tid) knownCharIds.add(tid); + } + + let clicked = clickButtonByRegex( + /^(?:create character|new character|add character)$/i, + document, + ); + if (!clicked) { + const addMenu = + document.querySelector('button[aria-label="Add media menu"]') || + Array.from(document.querySelectorAll('button, [role="button"]')).find( + (b) => + isVisibleEnabled(b) && + /^(?:add media menu|add|new|\+)$/i.test((b.getAttribute("aria-label") || elText(b)).trim()), + ); + if (isVisibleEnabled(addMenu)) { + addMenu.click(); + await delay(200); + const menuTarget = Array.from( + document.querySelectorAll('[role="menuitem"], .cdk-overlay-pane button, [role="menu"] button'), + ).find( + (el): el is HTMLElement => + isVisibleEnabled(el) && /\bcharacter\b/i.test(`${el.getAttribute("aria-label") || ""} ${elText(el)}`), + ); + if (menuTarget) { + menuTarget.click(); + clicked = true; + } + } + } + if (!clicked) { + return { ok: false, error: "character_create_ui_trigger_not_found" }; + } + + let charId: string | null = null; + const deadline = performance.now() + CHARACTER_CREATE_TIMEOUT_MS; + while (performance.now() < deadline) { + const inRoute = /\/character\/([^/?#]+)/.exec(location.pathname || "")?.[1]; + if (inRoute) { + charId = inRoute; + break; + } + for (const link of document.querySelectorAll('a[href*="/character/"]')) { + const id = /\/character\/([^/?#]+)/.exec(link.getAttribute("href") || "")?.[1]; + if (id && !knownCharIds.has(id)) { + charId = id; + break; + } + } + if (!charId) { + for (const tile of document.querySelectorAll("flow-grid-tile-container[data-tile-id]")) { + const tid = tile.getAttribute("data-tile-id"); + const kind = (tile.getAttribute("data-tile-kind") || tile.getAttribute("data-kind") || "").toLowerCase(); + if (tid && !knownCharIds.has(tid) && kind === "character") { + charId = tid; + break; + } + } + } + if (charId) break; + await delay(100); + } + if (!charId) { + return { ok: false, error: "created_character_id_not_found" }; + } + + const applied = ["ui_create_character"]; + if (location.pathname.includes(`/character/${charId}`)) { + for (let i = 0; i < 25; i++) { + if (document.querySelector('input[aria-label="Character name"], flow-character-form')) break; + await delay(100); + } + const nameInput = document.querySelector('input[aria-label="Character name"]'); + if (nameInput instanceof HTMLInputElement && charName) { + nameInput.focus(); + setNativeValue(nameInput, charName, true); + nameInput.dispatchEvent(new FocusEvent("blur", { bubbles: true })); + applied.push("ui_name"); + await delay(120); + } + if (typeof req?.bio === "string") { + const bioInput = findCharacterBioInput(); + if (bioInput) { + bioInput.focus(); + setNativeValue(bioInput, req.bio, true); + bioInput.dispatchEvent(new FocusEvent("blur", { bubbles: true })); + applied.push("ui_bio"); + await delay(120); + } + } + } + + const needsPageUpdate = Boolean( + req?.voice || + (Array.isArray(req?.asset_ids) && req.asset_ids.length > 0) || + req?.look_prompt || + (typeof req?.bio === "string" && !applied.includes("ui_bio")) || + (charName && !applied.includes("ui_name")), + ); + return { + ok: true, + id: charId, + name: charName, + ...(needsPageUpdate ? { need_update_on_page: true } : {}), + applied, + }; +} + /** Creates, opens, updates, or finishes character entity editing in Google Flow. */ export async function characterOp(req: CharacterOpRequest): Promise { const helper = runtimeState.store; @@ -17,16 +159,17 @@ export async function characterOp(req: CharacterOpRequest): Promise { if (action === "open_editor") { const pid = String(req?.project_id || "").trim(); const cid = String(req?.character_id || "").trim(); - if (!pid || !cid) { - return { ok: false, error: "missing_character_route_ids" }; - } + if (!pid || !cid) return { ok: false, error: "missing_character_route_ids" }; const targetSuffix = `/character/${cid}`; if (!location.pathname.includes(targetSuffix)) { const router = findRouter(); - if (!router) { - return { ok: false, error: "angular_router_not_found" }; + if (router) { + await router.navigate(["/project", pid, "character", cid]); + } else { + const link = document.querySelector(`a[href*="/character/${CSS.escape(cid)}"]`); + if (!link) return { ok: false, error: "angular_router_not_found" }; + link.click(); } - await router.navigate(["/project", pid, "character", cid]); } let ready = false; for (let i = 0; i < 60; i += 1) { @@ -43,17 +186,12 @@ export async function characterOp(req: CharacterOpRequest): Promise { await delay(100); } if (!ready) { - return { - ok: false, - error: "character_editor_timeout", - path: location.pathname, - }; + return { ok: false, error: "character_editor_timeout", path: location.pathname }; } if ( runtimeState.projectId === pid && runtimeState.lService && - !runtimeState.lService.Ca?.Va && - !runtimeState.lService._ap?.Ca?.Va + !isComponentDestroyed(runtimeState.lService) ) { runtimeState.routePath = location.pathname; } @@ -77,9 +215,7 @@ export async function characterOp(req: CharacterOpRequest): Promise { let inWorkspace = false; if (exited) { for (let i = 0; i < 20; i++) { - if ( - document.querySelector("flow-project-page, flow-grid-tile-container") - ) { + if (document.querySelector("flow-project-page, flow-grid-tile-container")) { inWorkspace = true; break; } @@ -91,16 +227,17 @@ export async function characterOp(req: CharacterOpRequest): Promise { } const tileMap = getMap(); - const projectMatch = /(\/(?:fx\/tools\/flow\/)?project\/[^/?#]+)/.exec( - location.pathname || "", - ); + const projectMatch = /(\/(?:fx\/tools\/flow\/)?project\/[^/?#]+)/.exec(location.pathname || ""); const projectBasePath = projectMatch ? projectMatch[1] : null; let charId = req?.character_id ? String(req.character_id).trim() : null; if (action === "create") { - if (!helper?.mutate) { - return { ok: false, error: "store_mutate_missing" }; + const charName = String(req?.name || "Character").trim() || "Character"; + const shape = helper?.mutate ? inferCreateEntityShape() : null; + if (!helper?.mutate || !shape?.ok) { + return await createCharacterViaUi(charName, req); } + const existingIds = new Set(); if (tileMap instanceof Map) { for (const [k, v] of tileMap.entries()) { @@ -110,62 +247,54 @@ export async function characterOp(req: CharacterOpRequest): Promise { } } - const charName = String(req?.name || "Character").trim() || "Character"; - let resolveDe: (v: unknown) => void = () => {}; - let rejectDe: (e: unknown) => void = () => {}; let resolvedTile: unknown = null; let mutateErr: string | null = null; - const dePromise = new Promise((res, rej) => { - resolveDe = res; - rejectDe = rej; - }); - dePromise.then( - (v) => { - resolvedTile = v; + const completion = { + resolve: (v: unknown) => { + resolvedTile ??= v; }, - (e) => { + reject: (e: unknown) => { const errObj = e as { message?: unknown } | null; - mutateErr = String(errObj?.message || e || "create_entity_failed"); + mutateErr ??= String(errObj?.message || e || "create_entity_failed"); }, - ); + }; - const mutatePromise = Promise.resolve( - helper.mutate({ - type: "create_entity", - A3: 1, - AW: 1, - displayName: charName, - tb: undefined, - ub: undefined, - De: { resolve: resolveDe, reject: rejectDe }, - ve: { resolve: resolveDe, reject: rejectDe }, - }), - ).then( - (v) => { - const resObj = v as { II?: unknown; MF?: unknown } | null; - const created = resObj?.MF ?? resObj?.II; - if (created && !resolvedTile) resolvedTile = created; - }, - (e) => { - if (!mutateErr) { - const errObj = e as { message?: unknown } | null; - mutateErr = String(errObj?.message || e || "create_entity_failed"); + const extractResponseEntity = (resp: unknown): unknown => { + if (!resp || typeof resp !== "object") return null; + if (typeof readOwn(resp, "id") === "string") return resp; + for (const key of Object.keys(resp)) { + const nested = readOwn(resp, key); + if (nested && typeof nested === "object" && typeof readOwn(nested, "id") === "string") { + return nested; } - }, - ); + } + return null; + }; + + const deadline = performance.now() + CHARACTER_CREATE_TIMEOUT_MS; + void Promise.resolve() + .then(() => + helper.mutate({ + type: "create_entity", + displayName: charName, + completion, + }), + ) + .then((v) => { + const created = extractResponseEntity(v); + if (created && !resolvedTile) resolvedTile = created; + }, completion.reject); const resolvedId = (): string | null => { if (resolvedTile && typeof resolvedTile === "object") { - const id = (resolvedTile as { id?: unknown }).id; + const id = readOwn(resolvedTile, "id"); if (id) return String(id); } return null; }; - for (let i = 0; i < 80; i++) { - if (mutateErr) { - return { ok: false, error: mutateErr }; - } + while (performance.now() < deadline) { + if (mutateErr) return { ok: false, error: mutateErr }; const directId = resolvedId(); if (directId) { charId = directId; @@ -187,38 +316,20 @@ export async function characterOp(req: CharacterOpRequest): Promise { await delay(100); } - if (mutateErr) { - return { ok: false, error: mutateErr }; - } - if (!charId) { - await Promise.race([mutatePromise, delay(200)]).catch(() => {}); - if (mutateErr) return { ok: false, error: mutateErr }; - const directId = resolvedId(); - if (directId) charId = directId; - } - if (!charId) { - return { ok: false, error: "created_character_id_not_found" }; - } + if (mutateErr) return { ok: false, error: mutateErr }; + if (!charId) return { ok: false, error: "created_character_id_not_found" }; const needsPageUpdate = Boolean( req?.voice || (Array.isArray(req?.asset_ids) && req.asset_ids.length > 0) || - req?.look_prompt, + req?.look_prompt || + typeof req?.bio === "string", ); - if (needsPageUpdate) { - return { - ok: true, - id: charId, - name: charName, - need_update_on_page: true, - applied: ["create_entity"], - }; - } - return { ok: true, id: charId, name: charName, + ...(needsPageUpdate ? { need_update_on_page: true } : {}), applied: ["create_entity"], }; } @@ -249,20 +360,30 @@ 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"]', - ); + const nameInput = document.querySelector('input[aria-label="Character name"]'); if (nameInput instanceof HTMLInputElement) { nameInput.focus(); setNativeValue(nameInput, nameStr, true); + nameInput.dispatchEvent(new FocusEvent("blur", { bubbles: true })); applied.push("ui_name"); await delay(150); } - if (charId && helper?.rename) { + if (charId && helper?.rename && inferSingleTileShape().ok) { await helper.rename(charId, nameStr); applied.push("store_name"); } } + if (typeof req?.bio === "string") { + const bioInput = findCharacterBioInput(); + if (!bioInput) { + return { ok: false, error: "character_bio_input_not_found" }; + } + bioInput.focus(); + setNativeValue(bioInput, req.bio, true); + bioInput.dispatchEvent(new FocusEvent("blur", { bubbles: true })); + applied.push("ui_bio"); + await delay(150); + } return { ok: true, diff --git a/ts/collection_ops.ts b/ts/collection_ops.ts index a34a75a..58fe10b 100644 --- a/ts/collection_ops.ts +++ b/ts/collection_ops.ts @@ -3,7 +3,7 @@ // Read and change collections in the active project without page controls. -import { isTrashedTile, parentCollectionId } from "./dom"; +import { collectionIdOf, isTrashedTile } from "./dom"; import { readBuildLabel } from "./frontend_builds"; import type { CollectionWriteFormat } from "./frontend_builds"; import { collectionWriteCompatibility } from "./frontend_compatibility"; @@ -62,6 +62,11 @@ function movable(tile: FlowTile | undefined): tile is FlowTile { return available(tile) && supportsMove(tile); } +/** Reads the parent collection ID of `tile` by known fields or live collection ID reference. */ +function tileParentId(tile: FlowTile, tiles: Map): string | null { + return collectionIdOf(tile, (cid) => tiles.get(cid)?.type === "COLLECTION"); +} + /** Lists the active collections and counts the asset tiles in each collection. */ function summarize(tiles: Map): SnapshotCollectionItem[] { const collections = new Map(); @@ -73,7 +78,7 @@ function summarize(tiles: Map): SnapshotCollectionItem[] { for (const tile of tiles.values()) { if (isTrashedTile(tile) || tile.type === "COLLECTION" || (tile.type === "SCENE" && tile.isPending)) continue; - const id = parentCollectionId(tile); + const id = tileParentId(tile, tiles); const parent = id === null ? undefined : collections.get(id); if (parent) parent.count++; } @@ -119,7 +124,7 @@ async function create(writer: CollectionWriter, id: string, name: string): Promi // This build sets the server-side name to "Untitled collection" on creation. const created = await mutateAndVerify(writer.store, { type: "create_collection", id }, (tiles) => { const tile = tiles.get(id); - return available(tile) && tile.type === "COLLECTION" && parentCollectionId(tile) === null; + return available(tile) && tile.type === "COLLECTION" && tileParentId(tile, tiles) === null; }); if (!created) return outcomeUnknown(writer.store, "create_collection", [id]); @@ -148,7 +153,7 @@ async function move( } if (!found.length) return { ok: false, error: "no_matching_assets", missing }; - const moving = found.filter((tile) => parentCollectionId(tile) !== target); + const moving = found.filter((tile) => tileParentId(tile, tiles) !== target); const after = moving.length === 0 ? tiles : await mutateAndVerify( store, moveRequest(format, target, moving), @@ -159,7 +164,7 @@ async function move( } return found.every((asset) => { const tile = typeof asset.id === "string" ? fresh.get(asset.id) : undefined; - return available(tile) && tile.type === asset.type && parentCollectionId(tile) === target; + return available(tile) && tile.type === asset.type && tileParentId(tile, fresh) === target; }); }, ); @@ -183,7 +188,7 @@ function moveRequest(format: CollectionWriteFormat, target: string | null, tiles /** Returns each direct member of a collection. */ function collectionMembers(tiles: Map, id: string) { - return [...tiles.values()].filter((tile) => parentCollectionId(tile) === id); + return [...tiles.values()].filter((tile) => tileParentId(tile, tiles) === id); } /** Moves the members and confirms an empty collection before it sends the deletion. */ @@ -197,7 +202,7 @@ async function deleteCollection({ store, format }: CollectionWriter, id: string) if (!available(collection) || collection.type !== "COLLECTION") { return { ok: false, error: "collection_not_found", id }; } - const parent = parentCollectionId(collection); + const parent = tileParentId(collection, tiles); if (parent !== null && (parent === id || !available(tiles.get(parent)) || tiles.get(parent)?.type !== "COLLECTION")) { return { ok: false, error: "collection_parent_unavailable", id }; } @@ -209,7 +214,7 @@ async function deleteCollection({ store, format }: CollectionWriter, id: string) const moved = members.length ? await mutateAndVerify(store, moveRequest(format, parent, members), (fresh) => ids.every((memberId) => { const member = fresh.get(memberId); - return member !== undefined && parentCollectionId(member) === parent; + return member !== undefined && tileParentId(member, fresh) === parent; })) : tiles; if (!moved) return outcomeUnknown(store, "move_collection_members", ids, parent); if (collectionMembers(moved, id).length) { diff --git a/ts/discover_store.ts b/ts/discover_store.ts index d16f07b..c0fc5a3 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -3,15 +3,17 @@ // Discover the Angular Ivy project store service and bind handles in module state. -import { - isNgLViewMap, - readOwn, - resolveLView, - withLViewMapCapture, -} from "./angular"; +import { isNgLViewMap, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe } from "./dom"; import { withMutationAliases } from "./frontend_compatibility"; import { clearStore, runtimeState } from "./state"; +import { + discoverProjectStoreCandidates, + discoverQueryTileServiceInLView, + isComponentDestroyed, + readRowsFromQueryTileService, + safeFnSource, +} from "./store_shapes"; import type { DiscoverStoreResult, FlowStoreService, @@ -31,14 +33,8 @@ function findMethodByMarker( for (const k of Object.getOwnPropertyNames(cur)) { if (k === "constructor") continue; const fn = readOwn(obj, k); - if (typeof fn === "function") { - try { - if (fn.toString().includes(marker)) { - return fn.bind(obj) as (...args: unknown[]) => unknown; - } - } catch { - // Ignore non-inspectable functions. - } + if (typeof fn === "function" && safeFnSource(fn).includes(marker)) { + return fn.bind(obj) as (...args: unknown[]) => unknown; } } cur = Object.getPrototypeOf(cur); @@ -56,10 +52,7 @@ function isTileMap(m: unknown): m is Map { if (!(m instanceof Map)) return false; if (m.size === 0) return true; for (const v of m.values()) { - if (v && typeof v === "object" && ("id" in v || "type" in v)) { - return true; - } - return false; + return Boolean(v && typeof v === "object" && ("id" in v || "type" in v)); } return false; } @@ -68,29 +61,19 @@ function isTileMap(m: unknown): m is Map { function resolveTileMapFrom(svc: FlowStoreService | null): Map | null { if (!svc || typeof svc !== "object") return null; const apKa = svc._ap?.ka; - if (typeof apKa === "function") { - try { - const m = apKa.call(svc._ap); - if (m instanceof Map) return m; - } catch { - // Try next getter. - } - } - if (typeof svc.ka === "function") { - try { - const m = svc.ka(); - if (m instanceof Map) return m; - } catch { - // Try next getter. - } - } + const svcKa = svc.ka; const haKa = svc.ha?.ka; - if (typeof haKa === "function") { + for (const getter of [ + typeof apKa === "function" ? () => apKa.call(svc._ap) : null, + typeof svcKa === "function" ? () => svcKa.call(svc) : null, + typeof haKa === "function" ? () => haKa.call(svc.ha) : null, + ]) { + if (!getter) continue; try { - const m = haKa.call(svc.ha); + const m = getter(); if (m instanceof Map) return m; } catch { - // Fall back to BFS scan. + // Try next getter. } } const queue: object[] = [svc]; @@ -132,7 +115,7 @@ function resolveTileMapFrom(svc: FlowStoreService | null): Map return emptyMapFallback; } -/** Returns the async mutate function of a TanStack mutation result (`oe`, `re` or `mutateAsync` by Flow build), or null. */ +/** Returns the async mutate function of a TanStack mutation result, or null. */ function mutateAsyncOf( obj: unknown, ): ((payload: Record) => Promise) | null { @@ -165,34 +148,25 @@ async function invokeMutation( payload = withMutationAliases(payload); const mq = queueObj as MutationQueueObj | null | undefined; const qKa = typeof mq?.ka === "function" ? mq.ka.bind(mq) : null; - const hasPendingQueueItems = (): boolean => { - if (!qKa) return false; + for (let i = 0; i < 200; i++) { + if (!qKa) break; try { const q = qKa(); - return Array.isArray(q?.items) && q.items.length > 0; + if (!Array.isArray(q?.items) || q.items.length === 0) break; } catch { - return false; + break; } - }; - for (let i = 0; i < 200; i++) { - if (!hasPendingQueueItems()) break; await delay(50); } - const lcAsync = mutateAsyncOf(lcObj); - if (lcAsync) { - const res = await lcAsync(payload); - await delay(0); - return res; - } - const qAsync = mutateAsyncOf(mq); - if (qAsync) { - const res = await qAsync(payload); - await delay(0); - return res; + for (const candidate of [mutateAsyncOf(lcObj), mutateAsyncOf(mq)]) { + if (candidate) { + const res = await candidate(payload); + await delay(0); + return res; + } } - const qMutateAsync = mq?.mutateAsync; - if (typeof qMutateAsync === "function") { - const res = await qMutateAsync.call(mq, payload); + if (typeof mq?.mutateAsync === "function") { + const res = await mq.mutateAsync.call(mq, payload); await delay(0); return res; } @@ -212,11 +186,8 @@ async function invokeMutation( for (let i = 0; i < 1200; i++) { await delay(25); if (capturedError) break; - const snapshot = qKa(); - const items = snapshot?.items; - const stillQueued = - Array.isArray(items) && - items.some((it) => it && it.mutation === payload); + const items = qKa()?.items; + const stillQueued = Array.isArray(items) && items.some((it) => it && it.mutation === payload); if (!stillQueued) { let errState: unknown = null; if (typeof mq?.error === "function") { @@ -234,9 +205,7 @@ async function invokeMutation( } } if (capturedError) { - throw capturedError instanceof Error - ? capturedError - : new Error(String(capturedError)); + throw capturedError instanceof Error ? capturedError : new Error(String(capturedError)); } throw new Error("mutation_timeout"); } finally { @@ -263,9 +232,7 @@ function resolveMutatorFrom( if (!svc || typeof svc !== "object") return null; const lcFallback = (obj: FlowStoreService): MutationQueueObj | null => { if (mutateAsyncOf(obj.lc)) return obj.lc ?? null; - if (typeof obj.ka === "object" && obj.ka && mutateAsyncOf(obj.ka)) { - return obj.ka; - } + if (typeof obj.ka === "object" && obj.ka && mutateAsyncOf(obj.ka)) return obj.ka; return null; }; const haInner = svc.ha?.ha as MutationQueueObj | null | undefined; @@ -282,33 +249,38 @@ function resolveMutatorFrom( return (payload) => invokeMutation(svc.ha, payload, lcFallback(svc)); } const directLc = lcFallback(svc); - if (directLc && mutateAsyncOf(directLc)) { - return (payload) => invokeMutation(svc, payload, directLc); - } - if (typeof svc.mutate === "function") { - return (payload) => invokeMutation(svc, payload, directLc); - } + if (directLc && mutateAsyncOf(directLc)) return (payload) => invokeMutation(svc, payload, directLc); + if (typeof svc.mutate === "function") return (payload) => invokeMutation(svc, payload, directLc); for (const k of Object.keys(svc)) { const child = readOwn(svc, k); - if (child && typeof child === "object") { - const childObj = child as FlowStoreService; - const childLc = childObj.lc || directLc || null; - if (typeof childObj.mutate === "function") { - return (payload) => invokeMutation(childObj, payload, childLc); - } - for (const ck of Object.keys(childObj)) { - const sub = readOwn(childObj, ck) as MutationQueueObj | undefined; - if (sub && typeof sub.mutate === "function") { - return (payload) => invokeMutation(sub, payload, childLc); - } + if (!child || typeof child !== "object") continue; + const childObj = child as FlowStoreService; + const childLc = childObj.lc || directLc || null; + if (typeof childObj.mutate === "function") return (payload) => invokeMutation(childObj, payload, childLc); + for (const ck of Object.keys(childObj)) { + const sub = readOwn(childObj, ck) as MutationQueueObj | undefined; + if (sub && typeof sub.mutate === "function") return (payload) => invokeMutation(sub, payload, childLc); + } + } + const dispatchers: Array<(...args: unknown[]) => unknown> = []; + let cur: object | null = svc; + for (let depth = 0; cur && cur !== Object.prototype && depth < 3; depth++) { + for (const k of Object.getOwnPropertyNames(cur)) { + if (k === "constructor") continue; + const fn = readOwn(svc, k); + const src = safeFnSource(fn); + if ( + typeof fn === "function" && + src.includes("PROJECT_TILES") && + (src.includes("batch_move_to_collection") || src.includes("set_display_name")) + ) { + dispatchers.push(fn.bind(svc) as (...args: unknown[]) => unknown); } } + cur = Object.getPrototypeOf(cur); } - const dispatcher = - findMethodByMarker(svc, "batch_move_to_collection") || - findMethodByMarker(svc, "set_display_name"); - if (dispatcher) { - return (payload) => Promise.resolve(dispatcher(projectId, payload)); + if (dispatchers.length === 1) { + return (payload) => Promise.resolve(dispatchers[0](projectId, withMutationAliases(payload))); } return null; } @@ -316,7 +288,10 @@ function resolveMutatorFrom( /** Returns true when `svc` or its nested wrapper has been destroyed by Angular. */ function isDestroyed(svc: FlowStoreService | null | undefined): boolean { if (!svc || typeof svc !== "object") return true; - return Boolean(svc.Ca?.Va || svc._ap?.Ca?.Va || svc.ha?.Ca?.Va); + if (svc._qt) return isComponentDestroyed(svc._qt.owner); + if (svc._ap) return isComponentDestroyed(svc._ap); + if (svc._uo) return isComponentDestroyed(svc._uo); + return isComponentDestroyed(svc); } /** Returns true while bound store queries are ready and not pending initial load. */ @@ -324,13 +299,10 @@ function isStoreDataReady(svc: FlowStoreService | null): boolean { if (!svc || isDestroyed(svc)) return false; const ap = svc._ap || svc.ha || svc; const rc = readOwn(ap, "RC") as { isPending?: () => boolean } | undefined; - if (typeof rc?.isPending === "function" && rc.isPending()) { - return false; - } - if (svc._uo) { + if (typeof rc?.isPending === "function" && rc.isPending()) return false; + if (svc._uo || svc._qt) { const haKa = svc.ha?.ka; - const m = typeof haKa === "function" ? haKa.call(svc.ha) : null; - if (!(m instanceof Map)) return false; + if (!(typeof haKa === "function" && haKa.call(svc.ha) instanceof Map)) return false; } return true; } @@ -339,23 +311,16 @@ function isStoreDataReady(svc: FlowStoreService | null): boolean { function isLService(v: unknown): boolean { if (!v || typeof v !== "object" || isDestroyed(v as FlowStoreService)) return false; const svc = v as FlowStoreService; - if ( - typeof svc.RK === "function" && - typeof svc.ZA === "function" && - typeof svc.ha?.ka === "function" - ) { + if (typeof svc.RK === "function" && typeof svc.ZA === "function" && typeof svc.ha?.ka === "function") { return true; } - if ( + return ( (hasMethodString(svc, "create_collection") || hasMethodString(svc, "PROJECT_TILES") || hasMethodString(svc.na, "PROJECT_TILES")) && hasMethodString(svc, "set_display_name") && resolveTileMapFrom(svc) instanceof Map - ) { - return true; - } - return false; + ); } /** Checks whether `v` is the `_ap` signal-store variant. */ @@ -364,9 +329,7 @@ function isAPService(v: unknown): v is FlowStoreService { return false; } const svc = v as FlowStoreService; - if (typeof svc.ka !== "function" || typeof svc.ha?.mutate !== "function") { - return false; - } + if (typeof svc.ka !== "function" || typeof svc.ha?.mutate !== "function") return false; try { return svc.ka() instanceof Map; } catch { @@ -378,32 +341,20 @@ function isAPService(v: unknown): v is FlowStoreService { function isUOService(v: unknown): v is FlowStoreService { if (!v || typeof v !== "object" || v instanceof Node) return false; const svc = v as FlowStoreService; - if ( - typeof svc.PG !== "function" || - typeof svc.queryKey !== "function" || - typeof svc.ob?.ha !== "function" - ) { - return false; - } return ( + typeof svc.PG === "function" && + typeof svc.queryKey === "function" && + typeof svc.ob?.ha === "function" && hasMethodString(svc, "create_collection") && hasMethodString(svc, "PROJECT_TILES") ); } /** Resolves cached tile rows from a `_uo` store service. */ -function resolveTileArrayFromUO( - uo: FlowStoreService, - projectId: string | null, -): FlowTile[] | null { - if (!uo || typeof uo !== "object" || typeof uo.ob?.ha !== "function") { - return null; - } +function resolveTileArrayFromUO(uo: FlowStoreService, projectId: string | null): FlowTile[] | null { + if (!uo || typeof uo !== "object" || typeof uo.ob?.ha !== "function") return null; try { - const qk = - typeof uo.queryKey === "function" - ? uo.queryKey(projectId) - : ["PROJECT_TILES", projectId]; + const qk = typeof uo.queryKey === "function" ? uo.queryKey(projectId) : ["PROJECT_TILES", projectId]; const data = uo.ob.ha(qk); if (data && Array.isArray(data.Cb)) return data.Cb; } catch { @@ -412,6 +363,18 @@ function resolveTileArrayFromUO( return null; } +/** Builds the rename payload passed through `withMutationAliases`. */ +function renamePayload(id: string, displayName: string): Record { + return { type: "single_tile", tileId: id, change: { type: "set_display_name", displayName } }; +} + +/** Route path of the most recent failed invasive DOM store probe. */ +let lastInvasiveMissPath = ""; +/** Timestamp (`performance.now()`) of the most recent failed invasive DOM store probe. */ +let lastInvasiveMissAt = -Infinity; +/** Cooldown between invasive hover/scroll/focus store probes on the same route. */ +const INVASIVE_PROBE_COOLDOWN_MS = 5_000; + /** Scans the DOM, Ivy contexts, and transient Map activity to bind the project store. */ export async function discoverStore(): Promise { const match = /\/project\/([^/?#]+)/.exec(location.pathname || ""); @@ -421,10 +384,7 @@ export async function discoverStore(): Promise { if (isAPService(found) && !isLService(found)) { const ap = found; const apKa = ap.ka as () => Map | null | undefined; - runtimeState.lService = { - _ap: ap, - ha: { ka: () => apKa.call(ap), ha: ap.ha }, - }; + runtimeState.lService = { _ap: ap, ha: { ka: () => apKa.call(ap), ha: ap.ha } }; runtimeState.projectId = projectId; runtimeState.routePath = location.pathname; runtimeState.store = { @@ -432,27 +392,36 @@ export async function discoverStore(): Promise { getTileMap: () => apKa.call(ap), isReady: () => isStoreDataReady(runtimeState.lService), mutate: (payload) => invokeMutation(ap.ha, payload, ap.lc), - rename: async (id, displayName) => - await invokeMutation( - ap.ha, - { - type: "single_tile", - Xc: id, - Uc: id, - Ve: { type: "set_display_name", displayName }, - }, - ap.lc, - ), + rename: async (id, displayName) => await invokeMutation(ap.ha, renamePayload(id, displayName), ap.lc), + }; + return; + } + + if (found._qt) { + const qt = found._qt; + const getQtMap = (): Map | null => + readRowsFromQueryTileService(qt.tilesService, qt.queryClient, qt.rows, projectId); + const dispatch = (payload: Record): Promise => { + const fn = qt.dispatcher ? readOwn(qt.tilesService, qt.dispatcher) : undefined; + if (typeof fn !== "function") throw new Error("store_mutate_missing"); + return Promise.resolve(fn.call(qt.tilesService, projectId, withMutationAliases(payload))); + }; + runtimeState.lService = { _qt: qt, ha: { ka: getQtMap } }; + runtimeState.projectId = projectId; + runtimeState.routePath = location.pathname; + runtimeState.store = { + projectId, + getTileMap: getQtMap, + isReady: () => isStoreDataReady(runtimeState.lService), + mutate: dispatch, + rename: async (id, displayName) => await dispatch(renamePayload(id, displayName)), }; return; } if (isUOService(found) && !isLService(found)) { const uo = found; - const uoPg = uo.PG as ( - pid: string | null, - payload: Record, - ) => Promise; + const uoPg = uo.PG as (pid: string | null, payload: Record) => Promise; const getUoMap = (): Map | null => { const arr = resolveTileArrayFromUO(uo, projectId); if (!arr) return null; @@ -462,29 +431,16 @@ export async function discoverStore(): Promise { } return m; }; - runtimeState.lService = { - _uo: uo, - ha: { ka: getUoMap }, - }; + runtimeState.lService = { _uo: uo, ha: { ka: getUoMap } }; runtimeState.projectId = projectId; runtimeState.routePath = location.pathname; runtimeState.store = { projectId, getTileMap: getUoMap, isReady: () => isStoreDataReady(runtimeState.lService), - mutate: (payload) => - uoPg.call(uo, projectId, withMutationAliases(payload)), + mutate: (payload) => uoPg.call(uo, projectId, withMutationAliases(payload)), rename: async (id, displayName) => - await uoPg.call( - uo, - projectId, - withMutationAliases({ - type: "single_tile", - Xc: id, - Uc: id, - Ve: { type: "set_display_name", displayName }, - }), - ), + await uoPg.call(uo, projectId, withMutationAliases(renamePayload(id, displayName))), }; return; } @@ -504,19 +460,8 @@ export async function discoverStore(): Promise { rename: async (id, displayName) => { const svc = runtimeState.lService; const fn = resolveMutatorFrom(svc, projectId); - if (fn) { - return await fn( - withMutationAliases({ - type: "single_tile", - Xc: id, - Uc: id, - Ve: { type: "set_display_name", displayName }, - }), - ); - } - if (svc && typeof svc.RK === "function") { - return await svc.RK(id, displayName); - } + if (fn) return await fn(withMutationAliases(renamePayload(id, displayName))); + if (svc && typeof svc.RK === "function") return await svc.RK(id, displayName); throw new Error("store_rename_missing"); }, }; @@ -528,6 +473,7 @@ export async function discoverStore(): Promise { runtimeState.lService && !isDestroyed(runtimeState.lService) && !runtimeState.lService._uo && + !runtimeState.lService._qt && resolveTileMapFrom(runtimeState.lService) instanceof Map ) { installHandle(runtimeState.lService._ap || runtimeState.lService); @@ -538,16 +484,14 @@ export async function discoverStore(): Promise { const findInLView = (lv: unknown): FlowStoreService | null => { if (!Array.isArray(lv)) return null; - for (let i = 0; i < lv.length; i++) { - if (isLService(lv[i])) return lv[i] as FlowStoreService; + for (const cand of lv) { + if (isLService(cand)) return cand as FlowStoreService; } return null; }; - const findAPInLView = (lv: unknown): FlowStoreService | null => { if (!Array.isArray(lv)) return null; - for (let i = 0; i < lv.length; i++) { - const cand = lv[i]; + for (const cand of lv) { if (isAPService(cand)) return cand; if (cand && typeof cand === "object" && !(cand instanceof Node)) { for (const prop of ["Eu", "oa", "ka"]) { @@ -558,11 +502,9 @@ export async function discoverStore(): Promise { } return null; }; - const findUOInLView = (lv: unknown): FlowStoreService | null => { if (!Array.isArray(lv)) return null; - for (let i = 0; i < lv.length; i++) { - const cand = lv[i]; + for (const cand of lv) { if (isUOService(cand)) return cand; if (cand && typeof cand === "object" && !(cand instanceof Node)) { for (const prop of ["ma", "ya", "Hoa", "oa"]) { @@ -573,13 +515,32 @@ export async function discoverStore(): Promise { } return null; }; + const findQTInLView = (lv: unknown): FlowStoreService | null => { + const hit = discoverQueryTileServiceInLView(lv, projectId); + if (!hit) return null; + return { + _qt: hit, + ha: { ka: () => readRowsFromQueryTileService(hit.tilesService, hit.queryClient, hit.rows, projectId) }, + }; + }; - const findAnyInLView = (lv: unknown): FlowStoreService | null => - findInLView(lv) || findAPInLView(lv) || findUOInLView(lv); + const matchers = [findInLView, findAPInLView, findUOInLView, findQTInLView]; + const findAnyInLView = (lv: unknown): FlowStoreService | null => { + for (const m of matchers) { + const hit = m(lv); + if (hit) return hit; + } + return null; + }; - const scanDomNgContexts = ( - matcher: (lv: unknown) => FlowStoreService | null = findInLView, - ): FlowStoreService | null => { + /** Verifies that structural store discovery is unambiguous across known Angular view maps. */ + const isAmbiguousAcrossMaps = (maps: Iterable): boolean => { + if (!projectId) return false; + const outcome = discoverProjectStoreCandidates([...maps], projectId); + return outcome.ambiguousInner || outcome.candidates.length > 1; + }; + + const scanDomNgContexts = (matcher: (lv: unknown) => FlowStoreService | null): FlowStoreService | null => { const matchWithParents = (el: Element): FlowStoreService | null => { let p: NgLView | null = resolveLView(el); for (let d = 0; d < 6 && Array.isArray(p); d++) { @@ -594,22 +555,18 @@ export async function discoverStore(): Promise { ); for (const el of roots) { let cur: Element | null = el; - let steps = 0; - while (cur && steps < 12) { + for (let steps = 0; cur && steps < 12; steps++) { const hit = matchWithParents(cur); if (hit) return hit; cur = cur.parentElement; - steps++; } } const allEls = document.querySelectorAll("*"); const limit = Math.min(allEls.length, 600); for (let i = 0; i < limit; i++) { const lv = resolveLView(allEls[i]); - if (lv) { - const hit = matcher(lv); - if (hit) return hit; - } + const hit = lv ? matcher(lv) : null; + if (hit) return hit; } return null; }; @@ -623,30 +580,32 @@ export async function discoverStore(): Promise { ), ); const visible = all.filter((el) => el.getClientRects().length > 0); - const targets = (visible.length > 0 ? visible : all).slice(0, 12); - await hoverProbe(targets, 30); + await hoverProbe((visible.length > 0 ? visible : all).slice(0, 12), 30); }); }; - let found: FlowStoreService | null = - scanDomNgContexts(findInLView) || - scanDomNgContexts(findAPInLView) || - scanDomNgContexts(findUOInLView); + let found: FlowStoreService | null = null; + for (const matcher of matchers) { + found = scanDomNgContexts(matcher); + if (found) break; + } if (found) { await probeLViewMapHover(); + if (runtimeState.ngLViewMap && isAmbiguousAcrossMaps([runtimeState.ngLViewMap])) { + clearStore(); + return { bound: false, newlyDiscovered: false }; + } installHandle(found); return { bound: true, newlyDiscovered: true }; } const allSeenMaps = new Set>(); - const scanMaps = (maps: Set>): FlowStoreService | null => { for (const m of maps) { - if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(m)) { - runtimeState.ngLViewMap = m; - } + if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(m)) runtimeState.ngLViewMap = m; } - for (const matcher of [findInLView, findAPInLView, findUOInLView]) { + if (isAmbiguousAcrossMaps(maps)) return null; + for (const matcher of matchers) { for (const m of maps) { try { for (const v of m.values()) { @@ -661,20 +620,14 @@ export async function discoverStore(): Promise { return null; }; - const captureWithMapHook = async ( - runAsync: () => Promise, - ): Promise => { + const captureWithMapHook = async (runAsync: () => Promise): Promise => { const origSet = Map.prototype.set; const origGet = Map.prototype.get; const seenMaps = new Set>(); const seenLViews: NgLView[] = []; let directFound: FlowStoreService | null = null; try { - Map.prototype.set = function ( - this: Map, - k: unknown, - v: unknown, - ): Map { + Map.prototype.set = function (this: Map, k: unknown, v: unknown): Map { seenMaps.add(this); allSeenMaps.add(this); if (typeof k === "number" && Array.isArray(v) && v[19] === k) { @@ -686,19 +639,11 @@ export async function discoverStore(): Promise { } return origSet.call(this, k, v); }; - Map.prototype.get = function ( - this: Map, - k: unknown, - ): unknown { + Map.prototype.get = function (this: Map, k: unknown): unknown { seenMaps.add(this); allSeenMaps.add(this); const v: unknown = origGet.call(this, k); - if ( - !(runtimeState.ngLViewMap instanceof Map) && - typeof k === "number" && - Array.isArray(v) && - v[19] === k - ) { + if (!(runtimeState.ngLViewMap instanceof Map) && typeof k === "number" && Array.isArray(v) && v[19] === k) { runtimeState.ngLViewMap = this as unknown as Map; } return v; @@ -708,8 +653,9 @@ export async function discoverStore(): Promise { Map.prototype.set = origSet; Map.prototype.get = origGet; } + if (isAmbiguousAcrossMaps(allSeenMaps)) return null; if (directFound) return directFound; - for (const matcher of [findInLView, findAPInLView, findUOInLView]) { + for (const matcher of matchers) { for (const lv of seenLViews) { const hit = matcher(lv); if (hit) return hit; @@ -718,6 +664,19 @@ export async function discoverStore(): Promise { return scanMaps(seenMaps); }; + if (!found && runtimeState.ngLViewMap instanceof Map) { + found = scanMaps(new Set([runtimeState.ngLViewMap])); + } + const routeKey = `${location.pathname}?${location.search}`; + if ( + !found && + document.readyState === "complete" && + lastInvasiveMissPath === routeKey && + performance.now() - lastInvasiveMissAt < INVASIVE_PROBE_COOLDOWN_MS + ) { + return { bound: false, newlyDiscovered: false, cooldownSkipped: true }; + } + const probeSelectors = [ "flow-project-page", "flow-project-shell", "flow-character-edit-page", "flow-character-edit-header", "flow-character-form", "flow-character-preview-panel", @@ -736,9 +695,7 @@ export async function discoverStore(): Promise { } if (!found) { - const scroller = document.querySelector( - ".page-container, cdk-virtual-scroll-viewport", - ); + const scroller = document.querySelector(".page-container, cdk-virtual-scroll-viewport"); if (scroller) { const prev = scroller.scrollTop; found = await captureWithMapHook(async () => { @@ -757,7 +714,6 @@ export async function discoverStore(): Promise { } } } - if (!found) found = scanMaps(allSeenMaps); if (!found) { @@ -780,9 +736,7 @@ export async function discoverStore(): Promise { ); if (charInputs.length > 0) { found = await captureWithMapHook(async () => { - for (const inp of charInputs) { - inp.dispatchEvent(new FocusEvent("blur", { bubbles: false })); - } + for (const inp of charInputs) inp.dispatchEvent(new FocusEvent("blur", { bubbles: false })); await delay(60); }); if (!found) found = scanMaps(allSeenMaps); @@ -791,15 +745,11 @@ export async function discoverStore(): Promise { if (!found) { const findPanelToggle = (): HTMLElement | null => { - const btn = Array.from( - document.querySelectorAll('button, [role="button"]'), - ).find( + const btn = Array.from(document.querySelectorAll('button, [role="button"]')).find( (b) => b instanceof HTMLElement && b.getClientRects().length > 0 && - /\b(?:collapse|expand)\b/i.test( - (b.innerText || b.getAttribute("aria-label") || "").trim(), - ), + /\b(?:collapse|expand)\b/i.test((b.innerText || b.getAttribute("aria-label") || "").trim()), ); return btn instanceof HTMLElement ? btn : null; }; @@ -821,10 +771,17 @@ export async function discoverStore(): Promise { } } - if (found) { + if (found && !isAmbiguousAcrossMaps(allSeenMaps)) { + lastInvasiveMissPath = ""; await probeLViewMapHover(); + if (runtimeState.ngLViewMap && isAmbiguousAcrossMaps([runtimeState.ngLViewMap])) { + clearStore(); + return { bound: false, newlyDiscovered: false }; + } installHandle(found); return { bound: true, newlyDiscovered: true }; } + lastInvasiveMissPath = routeKey; + lastInvasiveMissAt = performance.now(); return { bound: false, newlyDiscovered: false }; } diff --git a/ts/dom.ts b/ts/dom.ts index 3f5a812..b305ccc 100644 --- a/ts/dom.ts +++ b/ts/dom.ts @@ -31,6 +31,22 @@ function hasDimensions(d: { width?: number; height?: number } | undefined): bool /** Media status values of the Flow front end. */ const MEDIA_STATUSES = new Set(["success", "pending", "scheduled", "failed", "canceled"]); +/** Optional reader returning an inferred trashed boolean property name on FlowTile. */ +let trashedFieldReader: (() => string | null) | null = null; + +/** Registers a reader for an inferred trashed field name so `isTrashedTile` checks it. */ +export function registerTrashedFieldReader(reader: () => string | null): void { + trashedFieldReader = reader; +} + +/** Returns the first own string field on `m` that holds an HTTP, blob, or data URL. */ +function findMediaUrlField(m: object): string | undefined { + for (const [, v] of ownEntries(m)) { + if (typeof v === "string" && /^(?:https?:\/\/|blob:|data:)/i.test(v)) return v; + } + return undefined; +} + /** Returns the own enumerable values of `o` with their keys. */ function ownEntries(o: object): Array<[string, unknown]> { return Object.entries(o as Record); @@ -71,6 +87,8 @@ export function legacyMedia(m: T) ? raw.Cf : undefined; const created = [m.hc, m.kc, raw.lc].find((v) => v instanceof Date) as Date | undefined; + const fallbackUrl = + m.Wb ?? m.fifeUrl ?? m.imageUrl ?? m.videoUrl ?? m.mediaUrl ?? m.url ?? m.Bd ?? findMediaUrlField(m); return { ...m, Zc: m.Zc ?? m.od ?? findStatus(m), @@ -78,17 +96,26 @@ export function legacyMedia(m: T) nf: m.nf ?? m.Bf, Lf: m.Lf ?? duration, hc: m.hc ?? created, + ...(fallbackUrl && !m.url && !m.Wb && !m.fifeUrl && !m.videoUrl && !m.Bd ? { url: fallbackUrl } : {}), }; } -/** Returns the field of tile `t` that holds its media payload: an object with a string `id` and a string `workflowId`. The key name changes with each front-end build. */ +/** Returns the field of tile `t` that holds its media payload: an object with a string `id` and workflow or media metadata. */ function findMediaContainer(t: object): FlowMediaPayload | undefined { + const secondary: FlowMediaPayload[] = []; for (const [, v] of ownEntries(t)) { if (!v || typeof v !== "object" || Array.isArray(v) || v instanceof Map || v instanceof Date) continue; const c = v as { id?: unknown; workflowId?: unknown }; if (typeof c.id === "string" && typeof c.workflowId === "string") return v as FlowMediaPayload; + if ( + typeof c.id === "string" && + c.id.length > 0 && + (findStatus(v) !== undefined || findMediaUrlField(v) !== undefined) + ) { + secondary.push(v as FlowMediaPayload); + } } - return undefined; + return secondary.length === 1 ? secondary[0] : undefined; } /** Returns `t` with `Fb` set to its media payload under the old field names and `hc` set to its date. It finds the media payload by shape, because the key name changes with each front-end build. */ @@ -134,8 +161,17 @@ export function collectionIdOf( /** Returns true when the project store marks the tile as trashed. */ export function isTrashedTile(t: FlowTile): boolean { - return t.trashed === true || t.isTrashed === true || t.Cb === true || - t.yb === true || t.Ab === true; + if ( + t.trashed === true || + t.isTrashed === true || + t.Cb === true || + t.yb === true || + t.Ab === true + ) { + return true; + } + const inferred = trashedFieldReader?.(); + return Boolean(inferred && (t as Record)[inferred] === true); } /** Returns the look map of character tile `t`, or null. It accepts the old `oi` field, or any other `Map` field whose entries hold a `primaryMediaId` or a `history`, because the key name changes with each front-end build. */ diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 0307d4a..2eef50d 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -575,6 +575,17 @@ export interface VoiceConfirmationFormat { pickerSelection: string; } +/** Character preview panel format of build 20261120.00. */ +export const NOVEMBER_20_CHARACTER_PREVIEW: CharacterPreviewFormat = { + lifecycle: "Ba", + upload: "NV", + marker: "hh", + portrait: "ka", + body: "ma", + source: "Gza", + busy: "mB", +}; + /** Request formats by exact build label. Include only verified operations. */ const VERIFIED_BUILDS: ReadonlyMap = new Map([ ["boq_labs-ai-sandbox-frontend_20261117.10_p0", { @@ -609,9 +620,7 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ editor: "qu", entityQuery: "ma", savedVoice: "Xjb", selectedVoice: "A3", previewSaved: "MK", pickerSelection: "Qn", }, - characterPreview: { - lifecycle: "Ba", upload: "NV", marker: "hh", portrait: "ka", body: "ma", source: "Gza", busy: "mB", - }, + characterPreview: NOVEMBER_20_CHARACTER_PREVIEW, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -643,5 +652,5 @@ export function frontendBuild(label: string | null): FrontendBuild | undefined { /** Returns the layouts to check when the runtime binds the active project store. */ export function projectStoreFormats(): readonly ProjectStoreFormat[] { const format = frontendBuild(readBuildLabel())?.projectStore; - return format ? [format] : [NOVEMBER_17_STORE, NOVEMBER_18_STORE]; + return format ? [format] : [NOVEMBER_20_STORE, NOVEMBER_18_STORE, NOVEMBER_17_STORE]; } diff --git a/ts/frontend_compatibility.ts b/ts/frontend_compatibility.ts index c74127e..9c58170 100644 --- a/ts/frontend_compatibility.ts +++ b/ts/frontend_compatibility.ts @@ -16,6 +16,13 @@ import type { } from "./frontend_builds"; import { projectWriteChecks } from "./project_store"; import { legacyTile, pickTileUrl } from "./dom"; +import { + buildValidatedMutation, + inferAssetTrashShape, + inferCharacterBioShape, + inferCollectionWriteShape, + type ShapeValidation, +} from "./mutation_shapes"; import { runtimeState } from "./state"; import type { FlowTile, StoreProbeCheck, StoreProbeResult } from "./types"; @@ -36,24 +43,22 @@ interface UnsupportedFrontend { /** Result of checking a build and runtime for an operation. */ type FrontendCompatibility = { ok: true; format: Format } | UnsupportedFrontend; -/** Adds the native fields used by the general project store. */ +/** Builds a validated mutation payload or throws before any unverified or ambiguous write. */ export function withMutationAliases(payload: Record): Record { - const format = frontendBuild(readBuildLabel())?.projectStore.mutations; - if (payload.type === "single_tile" && payload.Ve && typeof payload.Ve === "object") { - if (!format) return { ...payload, We: payload.We ?? payload.Ve, df: payload.df ?? payload.Ve }; - const change = payload.Ve as Record; - const native = change.type === "set_video_trim_seconds" ? { - ...change, [format.trimStart]: change.Cg, [format.trimEnd]: change.Rf, - } : change; - return { ...payload, [format.tileId]: payload.Xc ?? payload.Uc, [format.tileChange]: native }; - } - if (format && payload.type === "create_scene") { - return { ...payload, [format.sceneWorkflows]: payload.rg, [format.sceneCollection]: payload.Fc }; - } - if (format && payload.type === "add_workflows_to_scene") { - return { ...payload, [format.sceneId]: payload.Lc, [format.sceneWorkflows]: payload.rg }; - } - return payload; + return buildValidatedMutation(payload); +} + +/** Validates a store write operation using both live store checks and inferred mutation shapes. */ +function checkStoreShape( + operation: Operation, + shape: ShapeValidation, + storeChecks: StoreProbeCheck[], +): FrontendCompatibility { + const build = readBuildLabel(); + const failed = storeChecks.filter(({ ok }) => !ok); + if (shape.ok && failed.length === 0) return { ok: true, format: shape.format }; + if (!shape.ok) failed.unshift(shape.check); + return { ok: false, error: "unsupported_front_end", build, operation, failed_checks: failed }; } /** Returns the verified format when the build and runtime checks pass. */ @@ -133,17 +138,29 @@ export function projectUploadCompatibility( /** Returns the collection format for the active project when its checks pass. */ export function collectionWriteCompatibility(): FrontendCompatibility { - return checkOperation("collection_write", readBuildLabel(), projectWriteChecks("collection")); + return checkStoreShape( + "collection_write", + inferCollectionWriteShape(), + projectWriteChecks("collection"), + ); } /** Returns the personality update format when the project store can submit and confirm it. */ export function characterBioCompatibility(): FrontendCompatibility { - return checkOperation("character_bio", readBuildLabel(), projectWriteChecks("project")); + return checkStoreShape( + "character_bio", + inferCharacterBioShape(), + projectWriteChecks("project"), + ); } /** Returns the asset trash format when its checks pass. */ export function assetTrashCompatibility(): FrontendCompatibility { - return checkOperation("asset_trash_store", readBuildLabel(), projectWriteChecks("project")); + return checkStoreShape( + "asset_trash_store", + inferAssetTrashShape(), + projectWriteChecks("project"), + ); } /** Counts readable image and video tiles in the first 200 tiles. */ @@ -217,8 +234,8 @@ export function probeStore(): StoreProbeResult { agent_attachments: operationStatus(agentAttachmentCompatibility()), agent_settings: operationStatus(agentSettingsCompatibility()), project_upload: operationStatus(projectUploadCompatibility()), - collection_write: operationStatus(checkOperation("collection_write", build, projectWriteChecks("collection"))), - character_bio: operationStatus(checkOperation("character_bio", build, projectWriteChecks("project"))), + collection_write: operationStatus(collectionWriteCompatibility()), + character_bio: operationStatus(characterBioCompatibility()), asset_trash_store: operationStatus(assetTrashCompatibility()), }, }; diff --git a/ts/index.ts b/ts/index.ts index 41f0ea3..f3aca5d 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -12,6 +12,7 @@ import { agentOp, agentPrototype, agentStatus, + agentUiBind, bindAgent, } from "./agent_chat"; import { bindAngularViews } from "./angular"; @@ -63,6 +64,7 @@ if (!window.__flowMcp) { agentOp, agentPrototype, agentStatus, + agentUiBind, bindAgent, bindAngularViews, collectionOps, diff --git a/ts/locate.ts b/ts/locate.ts index bd790b6..664240e 100644 --- a/ts/locate.ts +++ b/ts/locate.ts @@ -5,16 +5,16 @@ import type { LocatePointRequest, ViewportPoint } from "./types"; -/** Returns true when `el` is rendered. */ +/** Returns true when `el` is rendered in the viewport. */ function isRendered(el: Element): boolean { - return (el as HTMLElement).offsetParent !== null; + return el.getClientRects().length > 0; } /** Returns the visible control that matches `req`, or null. */ function findControl(req: LocatePointRequest): Element | null { if (req.by === "aria-label") { return ( - Array.from(document.querySelectorAll("button")).find( + Array.from(document.querySelectorAll('button, [role="button"], [role="menuitem"]')).find( (b) => b.getAttribute("aria-label") === req.name && isRendered(b), ) ?? null ); @@ -32,9 +32,20 @@ function findControl(req: LocatePointRequest): Element | null { }) ?? null ); } + const dialogs = Array.from( + document.querySelectorAll( + 'mat-dialog-container, [role="alertdialog"], [role="dialog"]', + ), + ).filter(isRendered); + for (const dialog of dialogs) { + const inDialog = Array.from( + dialog.querySelectorAll('button, [role="button"], [role="menuitem"]'), + ).find((e) => isRendered(e) && textOf(e) === want); + if (inDialog) return inDialog; + } return ( Array.from( - document.querySelectorAll('[role="menuitem"], button'), + document.querySelectorAll('[role="menuitem"], button, [role="button"]'), ).find((e) => isRendered(e) && textOf(e) === want) ?? null ); } diff --git a/ts/mutation_parser.ts b/ts/mutation_parser.ts new file mode 100644 index 0000000..3fdfa4b --- /dev/null +++ b/ts/mutation_parser.ts @@ -0,0 +1,375 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Extract live JavaScript function sources, switch cases, and object literals for mutation inference. + +import { readOwn } from "./angular"; +import { readBuildLabel } from "./frontend_builds"; +import { runtimeState } from "./state"; +import { safeFnSource } from "./store_shapes"; + +/** Valid JavaScript identifier pattern excluding reserved payload keys. */ +const IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/; + +/** Cached function source corpus keyed by active dispatcher identity and build label. */ +let cachedCorpusKey = ""; +/** Cached function source strings for the active runtime. */ +let cachedSources: string[] = []; + +/** Bound store dispatcher reader registered by `project_store.ts`. */ +export type BoundDispatcherInfo = { + /** Bound project store service object. */ + service: object | null; + /** Bound tile query service object. */ + tilesService: object | null; + /** Dispatcher method on the tile query service. */ + dispatcher: unknown; +}; + +/** Optional callback registered by `project_store.ts` to inspect the bound store dispatcher. */ +let boundDispatcherReader: (() => BoundDispatcherInfo) | null = null; + +/** Registers a reader for the bound project store dispatcher so shape probes inspect it first. */ +export function registerBoundDispatcherReader(reader: () => BoundDispatcherInfo): void { + boundDispatcherReader = reader; +} + +/** Collects method sources from an object and its prototype chain. */ +function collectObjectMethodSources(target: unknown, out: Set): void { + if (!target || typeof target !== "object") return; + let cur: object | null = target; + for (let depth = 0; cur && cur !== Object.prototype && depth < 4; depth++) { + for (const key of Object.getOwnPropertyNames(cur)) { + if (key === "constructor") continue; + const fn = readOwn(target, key); + if (typeof fn === "function") { + const src = safeFnSource(fn); + if (src.length > 20) out.add(src); + } + } + cur = Object.getPrototypeOf(cur); + } +} + +/** Collects live runtime JS sources from the bound dispatcher, store handles, and Flow namespace. */ +export function runtimeMutationSources(): string[] { + const bound = boundDispatcherReader?.() ?? { + service: null, + tilesService: null, + dispatcher: undefined, + }; + const label = readBuildLabel() ?? "unknown"; + const dispSrc = safeFnSource(bound.dispatcher); + const qtSvc = runtimeState.lService?._qt?.tilesService; + const qtSrc = safeFnSource( + qtSvc && runtimeState.lService?._qt?.dispatcher + ? readOwn(qtSvc, runtimeState.lService._qt.dispatcher) + : undefined, + ); + const ns = readOwn(window, "default_AiSandboxAngularFrontend"); + const nsKeys = ns && typeof ns === "object" ? Object.keys(ns) : []; + const key = `${label}:${dispSrc.length}:${qtSrc.length}:${Boolean(runtimeState.lService)}:${nsKeys.length}`; + if (key === cachedCorpusKey && cachedSources.length > 0) { + return cachedSources; + } + + const sources = new Set(); + if (dispSrc) sources.add(dispSrc); + if (qtSrc) sources.add(qtSrc); + collectObjectMethodSources(bound.tilesService, sources); + collectObjectMethodSources(bound.service, sources); + if (runtimeState.lService) { + collectObjectMethodSources(runtimeState.lService, sources); + collectObjectMethodSources(runtimeState.lService._ap, sources); + collectObjectMethodSources(runtimeState.lService._uo, sources); + collectObjectMethodSources(runtimeState.lService._qt?.tilesService, sources); + collectObjectMethodSources(runtimeState.lService._qt?.owner, sources); + collectObjectMethodSources(runtimeState.lService.ha, sources); + collectObjectMethodSources(runtimeState.lService.na, sources); + } + if (ns && typeof ns === "object") { + for (let i = 0; i < nsKeys.length && i < 2500; i++) { + const exp = readOwn(ns, nsKeys[i]); + if (typeof exp === "function") { + const src = safeFnSource(exp); + if (src.length > 20) sources.add(src); + const proto = readOwn(exp, "prototype"); + if (proto && typeof proto === "object") { + collectObjectMethodSources(proto, sources); + } + } else if (exp && typeof exp === "object") { + collectObjectMethodSources(exp, sources); + } + } + } + cachedCorpusKey = key; + cachedSources = [...sources]; + return cachedSources; +} + +/** Walks backward from `caseIndex` to find the variable switched on by the enclosing `switch (.type)`. */ +function findEnclosingSwitchVar(src: string, caseIndex: number): string { + let depth = 0; + for (let i = caseIndex - 1; i >= 0; i--) { + const ch = src[i]; + if (ch === "}") { + depth++; + } else if (ch === "{") { + if (depth > 0) { + depth--; + continue; + } + const header = src.slice(Math.max(0, i - 160), i); + const sw = /switch\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)(?:\?\.|\.)type\s*\)\s*$/.exec(header); + if (sw) return sw[1]; + } + } + return ""; +} + +/** Extracts the body of one `case` clause up to the next sibling `case`/`default` or closing `}` of the `switch`. */ +function extractCaseClauseBody(src: string, start: number): string { + const limit = Math.min(src.length, start + 2400); + let depth = 0; + let quote = ""; + for (let i = start; i < limit; i++) { + const ch = src[i]; + if (quote) { + if (ch === "\\") i++; + else if (ch === quote) quote = ""; + continue; + } + if (ch === '"' || ch === "'" || ch === "`") { + quote = ch; + } else if (ch === "{") { + depth++; + } else if (ch === "}") { + if (depth === 0) return src.slice(start, i); + depth--; + } else if (depth === 0 && (ch === "c" || ch === "d")) { + const prev = i > 0 ? src[i - 1] : " "; + if (!/[A-Za-z0-9_$]/.test(prev)) { + const rest = src.slice(i, Math.min(limit, i + 80)); + if (/^(?:case\s*["']|default\s*:)/.test(rest)) { + return src.slice(start, i); + } + } + } + } + return src.slice(start, limit); +} + +/** Extracts the `{ ... }` branch body immediately following an `if (.type === "...")` test. */ +function extractIfBranchBody(src: string, afterCond: number): string { + const openSearchLimit = Math.min(src.length, afterCond + 120); + let open = -1; + for (let i = afterCond; i < openSearchLimit; i++) { + if (src[i] === "{") { + open = i; + break; + } + if (src[i] === ";") return src.slice(afterCond, i + 1); + } + if (open < 0) return src.slice(afterCond, Math.min(src.length, afterCond + 400)); + const limit = Math.min(src.length, open + 2000); + let depth = 0; + let quote = ""; + for (let i = open; i < limit; i++) { + const ch = src[i]; + if (quote) { + if (ch === "\\") i++; + else if (ch === quote) quote = ""; + continue; + } + if (ch === '"' || ch === "'" || ch === "`") quote = ch; + else if (ch === "{") depth++; + else if (ch === "}") { + depth--; + if (depth === 0) return src.slice(open + 1, i); + } + } + return src.slice(open + 1, limit); +} + +/** Extracts switch-case or branch snippets following `case "":` or `.type === ""`. */ +export function findCaseBlocks( + sources: readonly string[], + actionType: string, +): Array<{ block: string; actionVar: string }> { + const escaped = actionType.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const results: Array<{ block: string; actionVar: string }> = []; + const caseRe = new RegExp(`case\\s*["']${escaped}["']\\s*:`, "g"); + const eqRe = new RegExp(`([A-Za-z_$][A-Za-z0-9_$]*)\\.type\\s*===?\\s*["']${escaped}["']`, "g"); + + for (const src of sources) { + if (!src.includes(actionType)) continue; + let m: RegExpExecArray | null; + caseRe.lastIndex = 0; + while ((m = caseRe.exec(src)) !== null) { + const actionVar = findEnclosingSwitchVar(src, m.index); + if (actionVar) { + results.push({ block: extractCaseClauseBody(src, m.index + m[0].length), actionVar }); + } + } + eqRe.lastIndex = 0; + while ((m = eqRe.exec(src)) !== null) { + results.push({ block: extractIfBranchBody(src, m.index + m[0].length), actionVar: m[1] }); + } + } + return results; +} + +/** Splits the top-level `key: value` or shorthand `key` entries of a JS object literal body. */ +export function splitObjectLiteralPairs(body: string): Array<{ key: string; value: string }> { + const parts: string[] = []; + let depth = 0; + let start = 0; + let quote = ""; + for (let i = 0; i < body.length; i++) { + const ch = body[i]; + if (quote) { + if (ch === "\\") i++; + else if (ch === quote) quote = ""; + continue; + } + if (ch === '"' || ch === "'" || ch === "`") { + quote = ch; + } else if (ch === "{" || ch === "[" || ch === "(") { + depth++; + } else if (ch === "}" || ch === "]" || ch === ")") { + depth--; + } else if (ch === "," && depth === 0) { + parts.push(body.slice(start, i)); + start = i + 1; + } + } + parts.push(body.slice(start)); + + const out: Array<{ key: string; value: string }> = []; + for (const raw of parts) { + const trimmed = raw.trim(); + if (!trimmed || trimmed.startsWith("...")) continue; + let colon = -1; + let d = 0; + let q = ""; + for (let i = 0; i < trimmed.length; i++) { + const ch = trimmed[i]; + if (q) { + if (ch === "\\") i++; + else if (ch === q) q = ""; + continue; + } + if (ch === '"' || ch === "'" || ch === "`") q = ch; + else if (ch === "{" || ch === "[" || ch === "(") d++; + else if (ch === "}" || ch === "]" || ch === ")") d--; + else if (ch === ":" && d === 0) { + colon = i; + break; + } + } + if (colon < 0) { + if (IDENT_RE.test(trimmed)) out.push({ key: trimmed, value: trimmed }); + continue; + } + const key = trimmed.slice(0, colon).trim().replace(/^["']|["']$/g, ""); + const value = trimmed.slice(colon + 1).trim(); + if (IDENT_RE.test(key)) out.push({ key, value }); + } + return out; +} + +/** Finds object literals `{ ... type: "" ... }` and returns their top-level key-value pairs. */ +export function findActionLiterals( + sources: readonly string[], + actionType: string, +): Array> { + const results: Array> = []; + for (const src of sources) { + let idx = 0; + while ((idx = src.indexOf(actionType, idx)) !== -1) { + const typePrefix = src.slice(Math.max(0, idx - 20), idx + actionType.length + 2); + idx += actionType.length; + if (!/type\s*:\s*["']/.test(typePrefix)) continue; + let open = -1; + let depth = 0; + for (let p = idx - actionType.length - 1; p >= Math.max(0, idx - 320); p--) { + const ch = src[p]; + if (ch === "}" || ch === "]" || ch === ")") depth++; + else if (ch === "{" || ch === "[" || ch === "(") { + if (depth === 0 && ch === "{") { + open = p; + break; + } + depth--; + } + } + if (open < 0) continue; + let close = -1; + depth = 0; + for (let p = open; p < Math.min(src.length, open + 500); p++) { + const ch = src[p]; + if (ch === "{" || ch === "[" || ch === "(") depth++; + else if (ch === "}" || ch === "]" || ch === ")") { + depth--; + if (depth === 0 && ch === "}") { + close = p; + break; + } + } + } + if (close < 0) continue; + const body = src.slice(open + 1, close); + const pairs = splitObjectLiteralPairs(body); + if (pairs.some((p) => p.key === "type" && p.value.replace(/["'\s]/g, "") === actionType)) { + results.push(pairs); + } + } + } + return results; +} + +/** Returns all distinct properties accessed as `.` or `?.` in `block`. */ +export function propsReadOn(block: string, varName: string): string[] { + const escaped = varName.replace(/\$/g, "\\$"); + const re = new RegExp(`\\b${escaped}(?:\\?\\.|\\.)([A-Za-z_$][A-Za-z0-9_$]*)\\b`, "g"); + const found = new Set(); + let m: RegExpExecArray | null; + while ((m = re.exec(block)) !== null) { + if (m[1] !== "type") found.add(m[1]); + } + const destructRe = new RegExp(`\\{([^{}]+)\\}\\s*=\\s*${escaped}\\b`, "g"); + while ((m = destructRe.exec(block)) !== null) { + for (const pair of splitObjectLiteralPairs(m[1])) { + if (pair.key !== "type") found.add(pair.key); + } + } + return [...found]; +} + +/** Returns true when `.` is used as an array or iterable in `block`. */ +export function isIteratedProp(block: string, varName: string, prop: string): boolean { + const v = varName.replace(/\$/g, "\\$"); + const p = prop.replace(/\$/g, "\\$"); + const expr = `(?:\\b${v}(?:\\?\\.|\\.)${p}|\\(\\s*${v}(?:\\?\\.|\\.)${p}\\s*(?:\\|\\||\\?\\?)\\s*\\[\\s*\\]\\s*\\))`; + const direct = new RegExp( + `${expr}(?:\\?\\.|\\.)(?:map|forEach|filter|some|every|flatMap|reduce|slice|length)\\b|of\\s+${expr}\\b|Array\\.(?:from|isArray)\\s*\\(\\s*${v}(?:\\?\\.|\\.)${p}\\b`, + ); + if (direct.test(block)) return true; + const aliasMatch = new RegExp( + `\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*=\\s*${v}(?:\\?\\.|\\.)${p}\\b`, + ).exec(block); + if (aliasMatch) { + const alias = aliasMatch[1].replace(/\$/g, "\\$"); + return new RegExp( + `\\b${alias}(?:\\?\\.|\\.)(?:map|forEach|filter|some|every|flatMap|reduce|slice|length)\\b|of\\s+${alias}\\b|Array\\.(?:from|isArray)\\s*\\(\\s*${alias}\\b`, + ).test(block); + } + return false; +} + +/** Returns true when `.` is used as a `{ resolve, reject }` completion handle in `block`. */ +export function isCompletionProp(block: string, varName: string, prop: string): boolean { + const v = varName.replace(/\$/g, "\\$"); + const p = prop.replace(/\$/g, "\\$"); + return new RegExp(`\\b${v}(?:\\?\\.|\\.)${p}(?:\\?\\.|\\.)(?:resolve|reject)\\b`).test(block); +} diff --git a/ts/mutation_shapes.ts b/ts/mutation_shapes.ts new file mode 100644 index 0000000..748054c --- /dev/null +++ b/ts/mutation_shapes.ts @@ -0,0 +1,686 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Infer and validate Flow mutation field keys from live runtime method signatures and handlers. + +import { registerTrashedFieldReader } from "./dom"; +import { + frontendBuild, + readBuildLabel, + type AssetTrashFormat, + type CharacterBioFormat, + type CollectionWriteFormat, +} from "./frontend_builds"; +import { + findActionLiterals, + findCaseBlocks, + isCompletionProp, + isIteratedProp, + propsReadOn, + registerBoundDispatcherReader, + runtimeMutationSources, + splitObjectLiteralPairs, +} from "./mutation_parser"; +import type { StoreProbeCheck } from "./types"; + +export { registerBoundDispatcherReader }; + +/** Outcome of validating a runtime mutation shape before dispatch. */ +export type ShapeValidation = + | { ok: true; format: Format } + | { + ok: false; + reason: "unverified_mutation_shape" | "ambiguous_mutation_shape"; + check: StoreProbeCheck; + }; + +/** Inferred shape for a `single_tile` wrapper mutation. */ +export interface SingleTileShape { + /** Tile ID field name on `single_tile`. */ + tileId: string; + /** Inner change payload field name on `single_tile`. */ + tileChange: string; +} + +/** Inferred shape for `set_video_trim_seconds`. */ +export interface VideoTrimShape extends SingleTileShape { + /** Trim start timestamp field name. */ + trimStart: string; + /** Trim end timestamp field name. */ + trimEnd: string; +} + +/** Inferred shape for `create_scene`. */ +export interface CreateSceneShape { + /** Workflow ID array field name. */ + sceneWorkflows: string; + /** Optional parent collection ID field name. */ + sceneCollection?: string; + /** Optional completion callback (`{ resolve, reject }`) field name. */ + completion?: string; + /** Optional created scene field name in the response payload. */ + sceneCreated?: string; +} + +/** Inferred shape for `add_workflows_to_scene`. */ +export interface AddClipsShape { + /** Target scene ID field name. */ + sceneId: string; + /** Workflow ID array field name. */ + sceneWorkflows: string; + /** Optional completion callback (`{ resolve, reject }`) field name. */ + completion?: string; +} + +/** Inferred shape for `create_entity` character creation. */ +export interface CreateEntityShape { + /** Numeric entity type field name (`1` for character). */ + entityType: string; + /** Optional completion callback (`{ resolve, reject }`) field name. */ + completion?: string; +} + +/** Validates a candidate set of serialized shapes and ensures exactly one unique candidate exists. */ +function finalizeCandidates( + name: string, + items: readonly T[], + keyOf: (item: T) => string, +): ShapeValidation { + const byKey = new Map(); + for (const item of items) byKey.set(keyOf(item), item); + if (byKey.size === 1) { + const [only] = byKey.values(); + return { ok: true, format: only }; + } + if (byKey.size > 1) { + const detail = `ambiguous candidates (${byKey.size}): ${[...byKey.keys()].join(" | ")}`; + return { ok: false, reason: "ambiguous_mutation_shape", check: { name, ok: false, detail } }; + } + return { + ok: false, + reason: "unverified_mutation_shape", + check: { name, ok: false, detail: "no matching runtime mutation shape" }, + }; +} + +/** Infers and validates the `single_tile` wrapper shape (`tileId`, `tileChange`). */ +export function inferSingleTileShape(): ShapeValidation { + const build = frontendBuild(readBuildLabel()); + const verifiedMut = build?.projectStore.mutations; + if (verifiedMut) { + return { ok: true, format: { tileId: verifiedMut.tileId, tileChange: verifiedMut.tileChange } }; + } + const verifiedCol = build?.operations.collection_write; + if (verifiedCol) { + return { ok: true, format: { tileId: verifiedCol.tileId, tileChange: verifiedCol.tileChange } }; + } + + const sources = runtimeMutationSources(); + const candidates: SingleTileShape[] = []; + + for (const { block, actionVar } of findCaseBlocks(sources, "single_tile")) { + const props = propsReadOn(block, actionVar); + if (props.length !== 2) continue; + const changeProps = props.filter((p) => { + const v = actionVar.replace(/\$/g, "\\$"); + const esc = p.replace(/\$/g, "\\$"); + if (new RegExp(`\\b${v}(?:\\?\\.|\\.)${esc}(?:\\?\\.|\\.)type\\b`).test(block)) return true; + const alias = new RegExp(`\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*=\\s*${v}(?:\\?\\.|\\.)${esc}\\b`).exec(block); + return Boolean( + alias && new RegExp(`\\b${alias[1].replace(/\$/g, "\\$")}(?:\\?\\.|\\.)type\\b`).test(block), + ); + }); + if (changeProps.length === 1) { + const tileChange = changeProps[0]; + const tileId = props.find((p) => p !== tileChange); + if (tileId && tileId !== tileChange) candidates.push({ tileId, tileChange }); + } + } + + for (const pairs of findActionLiterals(sources, "single_tile")) { + const others = pairs.filter((p) => p.key !== "type"); + if (others.length !== 2) continue; + const withType = others.filter((p) => /\btype\s*:/.test(p.value)); + if (withType.length === 1) { + const tileChange = withType[0].key; + const tileId = others.find((p) => p.key !== tileChange)?.key; + if (tileId && tileId !== tileChange) candidates.push({ tileId, tileChange }); + } + } + + return finalizeCandidates("single_tile_shape", candidates, (c) => `${c.tileId}:${c.tileChange}`); +} + +/** Infers and validates `CharacterBioFormat` (`tileId`, `tileChange`, `notes`). */ +export function inferCharacterBioShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.operations.character_bio; + if (verified) return { ok: true, format: verified }; + + const single = inferSingleTileShape(); + if (!single.ok) return single; + + const sources = runtimeMutationSources(); + const noteKeys: string[] = []; + + for (const { block, actionVar } of findCaseBlocks(sources, "set_character_personality_notes")) { + const props = propsReadOn(block, actionVar); + if (props.length === 1) noteKeys.push(props[0]); + } + for (const pairs of findActionLiterals(sources, "set_character_personality_notes")) { + const others = pairs.filter((p) => p.key !== "type"); + if (others.length === 1) noteKeys.push(others[0].key); + } + + const notesCheck = finalizeCandidates("character_bio_shape", noteKeys, (k) => k); + if (!notesCheck.ok) return notesCheck; + return { ok: true, format: { ...single.format, notes: notesCheck.format } }; +} + +/** Infers and validates `VideoTrimShape` (`tileId`, `tileChange`, `trimStart`, `trimEnd`). */ +export function inferVideoTrimShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.projectStore.mutations; + if (verified) { + const { tileId, tileChange, trimStart, trimEnd } = verified; + return { ok: true, format: { tileId, tileChange, trimStart, trimEnd } }; + } + + const single = inferSingleTileShape(); + if (!single.ok) return single; + + const sources = runtimeMutationSources(); + const pairsList: Array<{ trimStart: string; trimEnd: string }> = []; + + for (const pairs of findActionLiterals(sources, "set_video_trim_seconds")) { + const bounds = pairs.filter((p) => p.key !== "type" && p.key !== "mediaId"); + if (bounds.length === 2 && bounds[0].key !== bounds[1].key) { + pairsList.push({ trimStart: bounds[0].key, trimEnd: bounds[1].key }); + } + } + if (pairsList.length === 0) { + for (const { block, actionVar } of findCaseBlocks(sources, "set_video_trim_seconds")) { + const props = propsReadOn(block, actionVar).filter((p) => p !== "mediaId"); + if (props.length === 2 && props[0] !== props[1]) { + const i0 = block.indexOf(`.${props[0]}`); + const i1 = block.indexOf(`.${props[1]}`); + if (i0 >= 0 && i1 >= 0 && i0 !== i1) { + pairsList.push( + i0 < i1 + ? { trimStart: props[0], trimEnd: props[1] } + : { trimStart: props[1], trimEnd: props[0] }, + ); + } + } + } + } + + const trimCheck = finalizeCandidates("video_trim_shape", pairsList, (p) => `${p.trimStart}:${p.trimEnd}`); + if (!trimCheck.ok) return trimCheck; + return { ok: true, format: { ...single.format, ...trimCheck.format } }; +} + +/** Infers and validates `CollectionWriteFormat` (`tileId`, `tileChange`, `moveTarget`, `moveTiles`, `deleteCollections?`). */ +export function inferCollectionWriteShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.operations.collection_write; + if (verified) return { ok: true, format: verified }; + + const single = inferSingleTileShape(); + if (!single.ok) return single; + + const sources = runtimeMutationSources(); + const moveCandidates: Array<{ moveTarget: string; moveTiles: string }> = []; + + for (const { block, actionVar } of findCaseBlocks(sources, "batch_move_to_collection")) { + const props = propsReadOn(block, actionVar); + if (props.length !== 2) continue; + const iterated = props.filter((p) => isIteratedProp(block, actionVar, p)); + if (iterated.length === 1) { + const moveTiles = iterated[0]; + const moveTarget = props.find((p) => p !== moveTiles); + if (moveTarget && moveTarget !== moveTiles) { + moveCandidates.push({ moveTarget, moveTiles }); + } + } + } + if (moveCandidates.length === 0) { + for (const pairs of findActionLiterals(sources, "batch_move_to_collection")) { + const others = pairs.filter((p) => p.key !== "type"); + if (others.length !== 2) continue; + const arrayVal = others.filter((p) => /^\[|\.map\(|\.filter\(|tiles/i.test(p.value)); + if (arrayVal.length === 1) { + const moveTiles = arrayVal[0].key; + const moveTarget = others.find((p) => p.key !== moveTiles)?.key; + if (moveTarget && moveTarget !== moveTiles) { + moveCandidates.push({ moveTarget, moveTiles }); + } + } + } + } + + const moveCheck = finalizeCandidates( + "collection_move_shape", + moveCandidates, + (m) => `${m.moveTarget}:${m.moveTiles}`, + ); + if (!moveCheck.ok) return moveCheck; + + const delKeys = new Set(); + for (const { block, actionVar } of findCaseBlocks(sources, "batch_delete_tiles")) { + for (const p of propsReadOn(block, actionVar)) { + if (isIteratedProp(block, actionVar, p) && /COLLECTION|collection/i.test(block)) { + delKeys.add(p); + } + } + } + const deleteCollections = delKeys.size === 1 ? [...delKeys][0] : undefined; + + return { + ok: true, + format: { + ...single.format, + ...moveCheck.format, + ...(deleteCollections ? { deleteCollections } : {}), + }, + }; +} + +/** Infers and validates `AssetTrashFormat` (`entries`, `tile`, `trashed`, `date`, `destination`, `sceneWorkflows`). */ +export function inferAssetTrashShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.operations.asset_trash_store; + if (verified) return { ok: true, format: verified }; + + const sources = runtimeMutationSources(); + const candidates: Array> = []; + + for (const pairs of findActionLiterals(sources, "batch_set_tiles_trashed")) { + const others = pairs.filter((p) => p.key !== "type"); + if (others.length !== 2) continue; + const datePair = others.find((p) => /new\s+Date|Date\.now/i.test(p.value)); + const entriesPair = others.find((p) => p !== datePair); + if (!datePair || !entriesPair) continue; + const innerBrace = /\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/.exec(entriesPair.value); + if (!innerBrace) continue; + const entryPairs = splitObjectLiteralPairs(innerBrace[1]); + if (entryPairs.length !== 3) continue; + const destPair = entryPairs.find((p) => /\bmode\s*:/.test(p.value)); + const boolPair = entryPairs.find((p) => p !== destPair && /^(?:!0|!1|true|false)\b/.test(p.value)); + const tilePair = entryPairs.find((p) => p !== destPair && p !== boolPair); + if (destPair && boolPair && tilePair) { + candidates.push({ + date: datePair.key, + entries: entriesPair.key, + tile: tilePair.key, + trashed: boolPair.key, + destination: destPair.key, + }); + } + } + + for (const { block, actionVar } of findCaseBlocks(sources, "batch_set_tiles_trashed")) { + const props = propsReadOn(block, actionVar); + if (props.length !== 2) continue; + const iter = props.filter((p) => isIteratedProp(block, actionVar, p)); + if (iter.length !== 1) continue; + const entries = iter[0]; + const date = props.find((p) => p !== entries); + if (!date) continue; + const av = actionVar.replace(/\$/g, "\\$"); + const ev = entries.replace(/\$/g, "\\$"); + const itemVarMatch = new RegExp( + `(?:\\bfor\\s*\\(\\s*(?:const|let|var)\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\s+of\\s+${av}(?:\\?\\.|\\.)${ev})|(?:${av}(?:\\?\\.|\\.)${ev}\\.(?:map|forEach)\\(\\s*(?:\\(\\s*)?([A-Za-z_$][A-Za-z0-9_$]*))`, + ).exec(block); + const itemVar = itemVarMatch?.[1] || itemVarMatch?.[2]; + if (!itemVar) continue; + const itemProps = propsReadOn(block, itemVar); + if (itemProps.length !== 3) continue; + const iv = itemVar.replace(/\$/g, "\\$"); + const dests = itemProps.filter((p) => + new RegExp(`\\b${iv}(?:\\?\\.|\\.)${p.replace(/\$/g, "\\$")}(?:\\?\\.|\\.)mode\\b`).test(block), + ); + const tiles = itemProps.filter((p) => + new RegExp(`\\b${iv}(?:\\?\\.|\\.)${p.replace(/\$/g, "\\$")}(?:\\?\\.|\\.)(?:id|type|workflowId)\\b`).test(block), + ); + if (dests.length === 1 && tiles.length === 1 && dests[0] !== tiles[0]) { + const trashed = itemProps.find((p) => p !== dests[0] && p !== tiles[0]); + if (trashed) { + candidates.push({ date, entries, tile: tiles[0], trashed, destination: dests[0] }); + } + } + } + + const baseCheck = finalizeCandidates( + "asset_trash_shape", + candidates, + (c) => `${c.date}:${c.entries}:${c.tile}:${c.trashed}:${c.destination}`, + ); + if (!baseCheck.ok) return baseCheck; + + const wfKeys = new Set(); + for (const { block, actionVar } of findCaseBlocks(sources, "batch_delete_tiles")) { + for (const p of propsReadOn(block, actionVar)) { + if (isIteratedProp(block, actionVar, p) && /workflow|scene|clip/i.test(block)) { + wfKeys.add(p); + } + } + } + if (wfKeys.size > 1) { + const detail = `ambiguous sceneWorkflows keys: ${[...wfKeys].join(", ")}`; + return { + ok: false, + reason: "ambiguous_mutation_shape", + check: { name: "scene_clip_delete_shape", ok: false, detail }, + }; + } + return { + ok: true, + format: { ...baseCheck.format, sceneWorkflows: wfKeys.size === 1 ? [...wfKeys][0] : "" }, + }; +} + +/** Infers and validates `CreateSceneShape` (`create_scene`). */ +export function inferCreateSceneShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.projectStore.mutations; + if (verified) { + return { + ok: true, + format: { + sceneWorkflows: verified.sceneWorkflows, + sceneCollection: verified.sceneCollection, + sceneCreated: verified.sceneCreated, + completion: "De", + }, + }; + } + + const sources = runtimeMutationSources(); + const candidates: CreateSceneShape[] = []; + + for (const { block, actionVar } of findCaseBlocks(sources, "create_scene")) { + const props = propsReadOn(block, actionVar).filter((p) => p !== "aspectRatio"); + const iter = props.filter((p) => isIteratedProp(block, actionVar, p)); + if (iter.length !== 1) continue; + const sceneWorkflows = iter[0]; + const completions = props.filter((p) => isCompletionProp(block, actionVar, p)); + if (completions.length > 1) continue; + const completion = completions[0]; + const rest = props.filter((p) => p !== sceneWorkflows && p !== completion); + const sceneCollection = rest.length === 1 ? rest[0] : undefined; + const retMatch = /return\s*\{\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*:/.exec(block); + candidates.push({ + sceneWorkflows, + ...(sceneCollection ? { sceneCollection } : {}), + ...(completion ? { completion } : {}), + ...(retMatch ? { sceneCreated: retMatch[1] } : {}), + }); + } + if (candidates.length === 0) { + for (const pairs of findActionLiterals(sources, "create_scene")) { + const others = pairs.filter((p) => p.key !== "type" && p.key !== "aspectRatio"); + const wfPairs = others.filter((p) => /^\[|\.map\(|workflow/i.test(p.value)); + const compPairs = others.filter((p) => /\bresolve\b/.test(p.value)); + if (wfPairs.length === 1 && compPairs.length <= 1) { + candidates.push({ + sceneWorkflows: wfPairs[0].key, + ...(compPairs[0] ? { completion: compPairs[0].key } : {}), + }); + } + } + } + + return finalizeCandidates( + "create_scene_shape", + candidates, + (c) => `${c.sceneWorkflows}:${c.sceneCollection ?? ""}:${c.completion ?? ""}`, + ); +} + +/** Infers and validates `AddClipsShape` (`add_workflows_to_scene`). */ +export function inferAddClipsShape(): ShapeValidation { + const verified = frontendBuild(readBuildLabel())?.projectStore.mutations; + if (verified) { + return { + ok: true, + format: { + sceneId: verified.sceneId, + sceneWorkflows: verified.sceneWorkflows, + completion: "De", + }, + }; + } + + const sources = runtimeMutationSources(); + const candidates: AddClipsShape[] = []; + + for (const { block, actionVar } of findCaseBlocks(sources, "add_workflows_to_scene")) { + const props = propsReadOn(block, actionVar).filter((p) => p !== "position"); + const iter = props.filter((p) => isIteratedProp(block, actionVar, p)); + if (iter.length !== 1) continue; + const sceneWorkflows = iter[0]; + const completions = props.filter((p) => isCompletionProp(block, actionVar, p)); + if (completions.length > 1) continue; + const completion = completions[0]; + const scalars = props.filter((p) => p !== sceneWorkflows && p !== completion); + if (scalars.length === 1) { + candidates.push({ + sceneId: scalars[0], + sceneWorkflows, + ...(completion ? { completion } : {}), + }); + } else if (scalars.length > 1) { + const av = actionVar.replace(/\$/g, "\\$"); + const getMatches = scalars.filter((s) => + new RegExp(`\\.get\\(\\s*${av}(?:\\?\\.|\\.)${s.replace(/\$/g, "\\$")}\\s*\\)`).test(block), + ); + if (getMatches.length === 1) { + candidates.push({ + sceneId: getMatches[0], + sceneWorkflows, + ...(completion ? { completion } : {}), + }); + } + } + } + if (candidates.length === 0) { + for (const pairs of findActionLiterals(sources, "add_workflows_to_scene")) { + const others = pairs.filter((p) => p.key !== "type" && p.key !== "position"); + const compPairs = others.filter((p) => /\bresolve\b/.test(p.value)); + const wfPairs = others.filter((p) => p !== compPairs[0] && (/^\[|\.map\(|workflow/i.test(p.value))); + const idPairs = others.filter((p) => p !== compPairs[0] && p !== wfPairs[0]); + if (wfPairs.length === 1 && idPairs.length === 1 && compPairs.length <= 1) { + candidates.push({ + sceneId: idPairs[0].key, + sceneWorkflows: wfPairs[0].key, + ...(compPairs[0] ? { completion: compPairs[0].key } : {}), + }); + } + } + } + + return finalizeCandidates( + "add_workflows_to_scene_shape", + candidates, + (c) => `${c.sceneId}:${c.sceneWorkflows}:${c.completion ?? ""}`, + ); +} + +/** Infers and validates `CreateEntityShape` (`create_entity`). */ +export function inferCreateEntityShape(): ShapeValidation { + const sources = runtimeMutationSources(); + const candidates: CreateEntityShape[] = []; + + for (const pairs of findActionLiterals(sources, "create_entity")) { + const others = pairs.filter((p) => p.key !== "type" && p.key !== "displayName"); + const compPairs = others.filter((p) => /\bresolve\b/.test(p.value)); + const numPairs = others.filter( + (p) => p !== compPairs[0] && /^(?:1|!0|[A-Za-z_$]+\.[A-Z_]+)$/.test(p.value), + ); + if (numPairs.length === 1 && compPairs.length <= 1) { + candidates.push({ + entityType: numPairs[0].key, + ...(compPairs[0] ? { completion: compPairs[0].key } : {}), + }); + } + } + for (const { block, actionVar } of findCaseBlocks(sources, "create_entity")) { + const props = propsReadOn(block, actionVar).filter((p) => p !== "displayName"); + const completions = props.filter((p) => isCompletionProp(block, actionVar, p)); + const rest = props.filter((p) => !completions.includes(p)); + if (rest.length === 1 && completions.length <= 1) { + candidates.push({ + entityType: rest[0], + ...(completions[0] ? { completion: completions[0] } : {}), + }); + } + } + + return finalizeCandidates( + "create_entity_shape", + candidates, + (c) => `${c.entityType}:${c.completion ?? ""}`, + ); +} + +/** Builds a validated mutation payload or throws a structured diagnostic error before any write. */ +export function buildValidatedMutation(payload: Record): Record { + const action = String(payload.type ?? ""); + if (action === "single_tile") { + const rawChange = payload.change ?? payload.Ve ?? payload.We ?? payload.df ?? payload.mf; + if (!rawChange || typeof rawChange !== "object") { + throw new Error("unverified_mutation_shape:single_tile:missing_change"); + } + const change = rawChange as Record; + const tileIdVal = payload.tileId ?? payload.Xc ?? payload.Uc ?? payload.Vc; + if (typeof tileIdVal !== "string" || !tileIdVal) { + throw new Error("unverified_mutation_shape:single_tile:missing_tile_id"); + } + if (change.type === "set_video_trim_seconds") { + const trim = inferVideoTrimShape(); + if (!trim.ok) { + throw new Error(`${trim.reason}:${trim.check.name}:${trim.check.detail}`); + } + const startVal = "startSeconds" in change ? change.startSeconds : change.Cg; + const endVal = "endSeconds" in change ? change.endSeconds : change.Rf; + return { + type: "single_tile", + [trim.format.tileId]: tileIdVal, + [trim.format.tileChange]: { + type: "set_video_trim_seconds", + mediaId: change.mediaId, + [trim.format.trimStart]: startVal ?? null, + [trim.format.trimEnd]: endVal ?? null, + }, + }; + } + if (change.type === "set_character_personality_notes") { + const bio = inferCharacterBioShape(); + if (!bio.ok) { + throw new Error(`${bio.reason}:${bio.check.name}:${bio.check.detail}`); + } + const textVal = typeof change.notes === "string" ? change.notes : String(change.Mv ?? ""); + return { + type: "single_tile", + [bio.format.tileId]: tileIdVal, + [bio.format.tileChange]: { + type: "set_character_personality_notes", + [bio.format.notes]: textVal, + }, + }; + } + const single = inferSingleTileShape(); + if (!single.ok) { + throw new Error(`${single.reason}:${single.check.name}:${single.check.detail}`); + } + return { + type: "single_tile", + [single.format.tileId]: tileIdVal, + [single.format.tileChange]: change, + }; + } + + if (action === "create_scene") { + const scene = inferCreateSceneShape(); + if (!scene.ok) { + throw new Error(`${scene.reason}:${scene.check.name}:${scene.check.detail}`); + } + const workflows = payload.workflows ?? payload.rg ?? []; + const completion = payload.completion ?? payload.De ?? payload.ve; + const out: Record = { + type: "create_scene", + [scene.format.sceneWorkflows]: workflows, + aspectRatio: payload.aspectRatio ?? 1, + }; + if (scene.format.sceneCollection) { + out[scene.format.sceneCollection] = payload.collectionId ?? payload.Fc; + } + if (completion && scene.format.completion) { + out[scene.format.completion] = completion; + } + return out; + } + + if (action === "add_workflows_to_scene") { + const add = inferAddClipsShape(); + if (!add.ok) { + throw new Error(`${add.reason}:${add.check.name}:${add.check.detail}`); + } + const sceneId = payload.sceneId ?? payload.Lc ?? payload.Ic; + const workflows = payload.workflows ?? payload.rg ?? []; + const completion = payload.completion ?? payload.De ?? payload.ve; + const out: Record = { + type: "add_workflows_to_scene", + [add.format.sceneId]: sceneId, + [add.format.sceneWorkflows]: workflows, + position: payload.position, + }; + if (completion && add.format.completion) { + out[add.format.completion] = completion; + } + return out; + } + + if (action === "create_entity") { + const entity = inferCreateEntityShape(); + if (!entity.ok) { + throw new Error(`${entity.reason}:${entity.check.name}:${entity.check.detail}`); + } + const completion = payload.completion ?? payload.De ?? payload.ve; + const out: Record = { + type: "create_entity", + [entity.format.entityType]: 1, + displayName: payload.displayName, + }; + if (completion && entity.format.completion) { + out[entity.format.completion] = completion; + } + return out; + } + + if (action === "batch_move_to_collection") { + const col = inferCollectionWriteShape(); + if (!col.ok) { + throw new Error(`${col.reason}:${col.check.name}:${col.check.detail}`); + } + if (col.format.moveTarget in payload && col.format.moveTiles in payload) { + return payload; + } + return { + type: "batch_move_to_collection", + [col.format.moveTarget]: payload.target ?? null, + [col.format.moveTiles]: payload.tiles ?? [], + }; + } + + if (action === "batch_set_tiles_trashed") { + const trash = inferAssetTrashShape(); + if (!trash.ok) { + throw new Error(`${trash.reason}:${trash.check.name}:${trash.check.detail}`); + } + return payload; + } + + return payload; +} + +registerTrashedFieldReader(() => { + const shape = inferAssetTrashShape(); + return shape.ok ? shape.format.trashed : null; +}); diff --git a/ts/open_upload_trigger.ts b/ts/open_upload_trigger.ts index 306bca6..beef69b 100644 --- a/ts/open_upload_trigger.ts +++ b/ts/open_upload_trigger.ts @@ -1,29 +1,90 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Click the image/frame upload trigger or accept the upload consent dialog. +// Click the image/frame/library upload trigger or accept the upload consent dialog. import { elText, isVisibleEnabled } from "./dom"; -/** Clicks the frame upload trigger button or accepts the upload consent modal. */ +/** Clicks an upload trigger button, captures a hidden file input, or accepts upload consent. */ export function uploadUiAction(action: string): boolean { if (action === "accept_consent") { - const dialog = document.querySelector("flow-upload-consent-dialog"); - if (!dialog) return false; - const btn = Array.from( - dialog.querySelectorAll('button, [role="button"]'), - ).find((el): el is HTMLElement => { - if (!isVisibleEnabled(el)) return false; - const txt = elText(el); - return /^(?:i agree,\s*do not show again|i agree)$/i.test(txt); - }); - if (btn) { - btn.click(); - return true; + const dialogs = document.querySelectorAll( + 'flow-upload-consent-dialog, [data-testid="upload-consent-dialog"], mat-dialog-container, [role="dialog"], [role="alertdialog"]', + ); + for (const dialog of dialogs) { + const btn = Array.from(dialog.querySelectorAll('button, [role="button"]')).find( + (el): el is HTMLElement => { + if (!isVisibleEnabled(el)) return false; + const txt = elText(el); + return /^(?:i agree,\s*do not show again|i agree)$/i.test(txt) || + (dialog.matches('flow-upload-consent-dialog, [data-testid="upload-consent-dialog"]') && + /^(?:accept|continue)$/i.test(txt)); + }, + ); + if (btn) { + btn.click(); + return true; + } } return false; } + if (action === "capture_project_file_input") { + for (const prev of document.querySelectorAll('[data-flow-mcp-upload="project"]')) { + prev.removeAttribute("data-flow-mcp-upload"); + } + const existing = document.querySelector( + 'flow-project-page input[type="file"], flow-project-shell input[type="file"], input[type="file"][data-upload-target="project"]', + ); + if (existing) { + existing.setAttribute("data-flow-mcp-upload", "project"); + return true; + } + let captured: HTMLInputElement | null = null; + const origClick = HTMLInputElement.prototype.click; + const origShow = + typeof HTMLInputElement.prototype.showPicker === "function" + ? HTMLInputElement.prototype.showPicker + : null; + HTMLInputElement.prototype.click = function (this: HTMLInputElement): void { + if (this.type === "file") { + captured = this; + return; + } + origClick.call(this); + }; + if (origShow) { + HTMLInputElement.prototype.showPicker = function (this: HTMLInputElement): void { + if (this.type === "file") { + captured = this; + return; + } + origShow.call(this); + }; + } + try { + const menuItem = Array.from( + document.querySelectorAll('[role="menuitem"], button, [role="button"]'), + ).find((el) => { + if (!isVisibleEnabled(el)) return false; + const label = `${el.getAttribute("aria-label") || ""} ${elText(el)}`.trim(); + return /^(?:upload|upload media|upload files?)$/i.test(label) || /\bupload\b$/i.test(label); + }); + menuItem?.click(); + } finally { + HTMLInputElement.prototype.click = origClick; + if (origShow) HTMLInputElement.prototype.showPicker = origShow; + } + if (!captured) return false; + const inputEl: HTMLInputElement = captured; + if (!document.contains(inputEl)) { + inputEl.style.display = "none"; + document.body.appendChild(inputEl); + } + inputEl.setAttribute("data-flow-mcp-upload", "project"); + return true; + } + const els = Array.from(document.querySelectorAll('button, [role="button"]')); const trigger = els.find((el): el is HTMLElement => { if (!isVisibleEnabled(el)) return false; diff --git a/ts/page_view.ts b/ts/page_view.ts index 7137778..5f2ba82 100644 --- a/ts/page_view.ts +++ b/ts/page_view.ts @@ -39,11 +39,31 @@ export async function openView(collection: string): Promise(`a[href*="/collection/${CSS.escape(want)}"]`); + if (link) { + link.click(); + } else { + history.pushState({}, "", `${prefix}/project/${encodeURIComponent(view.projectId)}/collection/${encodeURIComponent(want)}?hl=en`); + window.dispatchEvent(new PopStateEvent("popstate")); + } + } else { + const back = document.querySelector( + 'button[aria-label="Back to project"], button[aria-label="Go back"], a.collection-back-link', + ); + if (back && back.getClientRects().length > 0) { + back.click(); + } else { + history.pushState({}, "", `${prefix}/project/${encodeURIComponent(view.projectId)}?hl=en`); + window.dispatchEvent(new PopStateEvent("popstate")); + } + } for (let i = 0; i < 50; i++) { await delay(100); const now = currentView(); @@ -62,16 +82,55 @@ function isRendered(el: Element): boolean { return el.getClientRects().length > 0; } -/** Returns the text input of the asset rename control. */ -function renameControl(): HTMLInputElement | null { +/** Returns the text input of the requested asset or collection rename control. */ +function renameControl(control = "", current = ""): HTMLInputElement | null { + if (control === "item") { + return ( + Array.from( + document.querySelectorAll('input[aria-label="Rename item"]'), + ).find(isRendered) ?? null + ); + } + if (control === "title") { + const inputs = Array.from( + document.querySelectorAll('input[aria-label="Editable text"]'), + ).filter(isRendered); + const active = inputs.find( + (e) => e === document.activeElement && e.classList.contains("editing"), + ); + if (active) return active; + const named = inputs.filter((e) => e.value === current); + return named.length === 1 ? named[0] : null; + } const host = Array.from(document.querySelectorAll('[aria-label="Rename tile"]')).find(isRendered); - const input = host?.querySelector("input"); - return input instanceof HTMLInputElement ? input : null; + const hostInput = host?.querySelector("input"); + if (hostInput instanceof HTMLInputElement && isRendered(hostInput)) return hostInput; + const direct = Array.from( + document.querySelectorAll( + 'input[aria-label="Rename tile"], input[aria-label="Rename item"], input[aria-label="Collection name"], [role="dialog"] input, flow-grid-tile-container input', + ), + ).find(isRendered); + if (direct) return direct; + if (document.activeElement instanceof HTMLInputElement && isRendered(document.activeElement)) { + const insideTileOrHeader = document.activeElement.closest( + 'flow-grid-tile-container, [role="dialog"], .collection-header', + ); + if (insideTileOrHeader) return document.activeElement; + } + return null; +} + +/** Returns the viewport center of the requested rename control. */ +export function textPoint(control = "", current = ""): Record { + const el = renameControl(control, current); + if (!el) return { ok: false, error: "text_control_not_found" }; + const r = el.getBoundingClientRect(); + return { ok: true, point: { x: r.x + r.width / 2, y: r.y + r.height / 2 } }; } /** Selects the text of the focused rename control. */ -export function selectText(): Record { - const el = renameControl(); +export function selectText(control = "", current = ""): Record { + const el = renameControl(control, current); if (!el) return { ok: false, error: "text_control_not_found" }; const focused = document.activeElement === el; if (focused) el.select(); @@ -79,8 +138,8 @@ export function selectText(): Record { } /** Returns the text in the rename control. */ -export function readText(): Record { - const el = renameControl(); +export function readText(control = "", current = ""): Record { + const el = renameControl(control, current); if (!el) return { ok: false, error: "text_control_not_found" }; return { ok: true, value: el.value }; } diff --git a/ts/project_store.ts b/ts/project_store.ts index 215ec6f..cb48800 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -7,7 +7,9 @@ import { isNgLViewMap, readOwn } from "./angular"; import { delay } from "./dom"; import { projectStoreFormats } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; +import { registerBoundDispatcherReader } from "./mutation_shapes"; import { runtimeState } from "./state"; +import { discoverProjectStoreCandidates } from "./store_shapes"; import type { FlowTile, NgLView, StoreProbeCheck } from "./types"; /** A Flow query for the tiles of one project. */ @@ -69,7 +71,14 @@ function isProjectKey(key: unknown, projectId: string): boolean { /** Indexes a complete result by tile ID. */ function tileMap(data: unknown, field: string): Map | null { - const rows = readOwn(data, field); + const rows = + field === "__self__" + ? data + : field === "__map__" + ? data instanceof Map + ? [...data.values()] + : null + : readOwn(data, field); if (!Array.isArray(rows)) return null; const tiles = new Map(); for (const tile of rows) { @@ -112,40 +121,52 @@ export function bindProjectStore(maps: unknown[], projectId: string): ReturnType const storeClass = readOwn(frontEnd, format.storeClass); return typeof storeClass === "function" ? [{ format, storeClass }] : []; }); - if (!layouts.length) { - return { ok: false, error: "collection_store_not_bound" }; - } const seen = new Set(); const candidates: Array<{ store: ProjectStore; views: Map }> = []; - const consider = (value: unknown, views: Map): void => { - if (!value || typeof value !== "object" || seen.has(value)) return; - seen.add(value); - for (const { storeClass, format } of layouts) { - if (!(value instanceof storeClass)) continue; - const candidate = { projectId, service: value, format }; - if (readProjectStore(candidate)) { - candidates.push({ store: candidate, views }); - break; + if (layouts.length > 0) { + const consider = (value: unknown, views: Map): void => { + if (!value || typeof value !== "object" || seen.has(value)) return; + seen.add(value); + for (const { storeClass, format } of layouts) { + if (!(value instanceof storeClass)) continue; + const candidate = { projectId, service: value, format }; + if (readProjectStore(candidate)) { + candidates.push({ store: candidate, views }); + break; + } } - } - }; + }; - for (const map of maps) { - if (!isNgLViewMap(map)) continue; - for (const view of map.values()) { - if (!Array.isArray(view)) continue; - for (const slot of view) { - consider(slot, map); - // The project shell holds the store in its component instance. - if (!slot || typeof slot !== "object") continue; - for (const key of ["ha", "Eu", "oa", "ka", "fh"]) { - consider(Object.getOwnPropertyDescriptor(slot, key)?.value, map); + for (const map of maps) { + if (!isNgLViewMap(map)) continue; + for (const view of map.values()) { + if (!Array.isArray(view)) continue; + for (const slot of view) { + consider(slot, map); + if (!slot || typeof slot !== "object") continue; + for (const key of Object.keys(slot).slice(0, 30)) { + consider(Object.getOwnPropertyDescriptor(slot, key)?.value, map); + } } } } } + if (candidates.length === 0) { + const discovered = discoverProjectStoreCandidates(maps, projectId); + if (discovered.ambiguousInner || discovered.candidates.length > 1) { + boundStore = null; + return { ok: false, error: "ambiguous_collection_store" }; + } + for (const item of discovered.candidates) { + const candidate = { projectId: item.projectId, service: item.service, format: item.format }; + if (readProjectStore(candidate)) { + candidates.push({ store: candidate, views: item.views }); + } + } + } + const selected = candidates.length === 1 ? candidates[0] : undefined; boundStore = selected?.store ?? null; if (selected) runtimeState.ngLViewMap = selected.views; @@ -170,9 +191,20 @@ export function projectWriteChecks(scope: "collection" | "project"): StoreProbeC /** Returns the dispatcher of the tile service. */ function storeDispatcher({ service, format }: ProjectStore): unknown { - return readOwn(readOwn(service, format.tilesService), format.dispatcher); + return format.dispatcher ? readOwn(readOwn(service, format.tilesService), format.dispatcher) : undefined; } +registerBoundDispatcherReader(() => { + const store = boundStore && isCurrent(boundStore) ? boundStore : null; + const tilesService = + store ? ((readOwn(store.service, store.format.tilesService) as object | null) ?? null) : null; + return { + service: store?.service ?? null, + tilesService, + dispatcher: store ? storeDispatcher(store) : undefined, + }; +}); + /** Sends one mutation to the server with the bound project ID. */ async function submitProjectMutation( store: ProjectStore, diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 9247fa5..ab85f51 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -3,18 +3,21 @@ // Read all project tiles, scene clips, and collections from the bound store map. +import { readOwn, resolveLView } from "./angular"; import { characterPersonalityNotes } from "./character_bio"; import { sceneContents } from "./scene_tiles"; import { characterLooksOf, collectionIdOf, + elText, fifeEnv as getFifeEnv, isTrashedTile, legacyMedia, legacyTile, } from "./dom"; import { clearStore, runtimeState } from "./state"; +import { isComponentDestroyed } from "./store_shapes"; import type { FlowMediaPayload, FlowTile, @@ -45,28 +48,214 @@ function normalizeVoiceVal(v: unknown): string | null { return String(v); } +/** Reads rendered tiles and collections directly from the workspace DOM when no JS store is bound. */ +function readDomWorkspaceSnapshot(projectId: string | null): StoreSnapshotResult { + if (!projectId) return { ok: false, error: "store_not_bound" }; + const workspace = document.querySelector( + "flow-project-page, flow-project-shell, flow-grid-tile-container, flow-character-edit-page", + ); + if (!workspace) return { ok: false, error: "store_not_bound" }; + + const cols = new Map(); + const counts = new Map(); + const assets: SnapshotAssetItem[] = []; + const seenIds = new Set(); + const activeColId = /\/collection\/([^/?#]+)/.exec(location.pathname || "")?.[1] ?? null; + if (activeColId) { + const colHeader = document.querySelector( + '[data-collection-title], .collection-title, input[aria-label="Collection name"], input[aria-label="Editable text"]', + ); + const colName = colHeader + ? ((colHeader as HTMLInputElement).value || elText(colHeader)).trim() + : activeColId; + cols.set(activeColId, colName); + counts.set(activeColId, 0); + } + + const readLViewTile = (container: Element): { id: string; name: string; type: string } | null => { + const nodes = [container, ...Array.from(container.querySelectorAll("*")).slice(0, 8)]; + for (const node of nodes) { + const lv = resolveLView(node); + if (!Array.isArray(lv)) continue; + for (const slot of lv) { + if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot)) continue; + const id = readOwn(slot, "id"); + const type = readOwn(slot, "type"); + if (typeof id === "string" && id && typeof type === "string" && type) { + const disp = readOwn(slot, "displayName") ?? readOwn(slot, "name") ?? ""; + return { id, name: typeof disp === "string" ? disp : "", type: type.toUpperCase() }; + } + } + } + return null; + }; + + for (const container of document.querySelectorAll("flow-grid-tile-container")) { + const lvTile = readLViewTile(container); + const hostId = + container.getAttribute("data-tile-id") || + container.getAttribute("data-id") || + container.querySelector("[data-tile-id]")?.getAttribute("data-tile-id") || + ""; + const colLink = container.querySelector('a[href*="/collection/"]'); + const charLink = container.querySelector('a[href*="/character/"]'); + const sceneLink = container.querySelector('a[href*="/scene/"]'); + const editLink = container.querySelector('a[href*="/edit/"]'); + const mediaEl = container.querySelector("[data-media-id]"); + const routeColId = colLink ? /\/collection\/([^/?#]+)/.exec(colLink.getAttribute("href") || "")?.[1] : null; + const routeCharId = charLink ? /\/character\/([^/?#]+)/.exec(charLink.getAttribute("href") || "")?.[1] : null; + const routeSceneId = sceneLink ? /\/scene\/([^/?#]+)/.exec(sceneLink.getAttribute("href") || "")?.[1] : null; + const routeEditId = editLink ? /\/edit\/([^/?#]+)/.exec(editLink.getAttribute("href") || "")?.[1] : null; + const rawKind = ( + container.getAttribute("data-tile-kind") || + container.getAttribute("data-kind") || + "" + ).toLowerCase(); + const isFolder = + rawKind === "collection" || + lvTile?.type === "COLLECTION" || + container.classList.contains("collection-tile") || + Boolean(routeColId) || + Boolean(container.querySelector('flow-collection-tile, [data-tile-type="COLLECTION"], .collection-folder')); + + const id = + hostId || + (isFolder ? container.getAttribute("data-collection-id") || "" : "") || + routeColId || + routeCharId || + routeSceneId || + routeEditId || + mediaEl?.getAttribute("data-media-id") || + lvTile?.id || + ""; + if (!id || seenIds.has(id)) continue; + seenIds.add(id); + + const titleNode = container.querySelector( + ".asset-title, .tile-title, [data-tile-title], .collection-name, h3, h4", + ); + const name = ( + (titleNode ? elText(titleNode) : "") || + container.getAttribute("data-tile-name") || + container.getAttribute("aria-label") || + lvTile?.name || + "" + ).trim(); + + if (isFolder) { + cols.set(id, name); + const countAttr = Number.parseInt(container.getAttribute("data-collection-count") || "", 10); + if (!counts.has(id)) counts.set(id, Number.isFinite(countAttr) ? countAttr : 0); + continue; + } + + const videoEl = container.querySelector("video[src]"); + const imgEl = container.querySelector("img[src]"); + const lvKind = + lvTile?.type === "CHARACTER" || lvTile?.type === "ENTITY" + ? "character" + : lvTile?.type === "SCENE" + ? "scene" + : lvTile?.type === "VIDEO" + ? "video" + : lvTile?.type === "IMAGE" + ? "image" + : ""; + const kind = + rawKind === "video" || rawKind === "image" || rawKind === "character" || rawKind === "scene" + ? rawKind + : lvKind || + (routeCharId || container.classList.contains("character-tile") + ? "character" + : routeSceneId + ? "scene" + : videoEl + ? "video" + : "image"); + const url = videoEl?.getAttribute("src") || imgEl?.getAttribute("src") || null; + const parentCol = + container.getAttribute("data-collection-id") || activeColId || null; + if (parentCol) counts.set(parentCol, (counts.get(parentCol) ?? 0) + 1); + const bioAttr = + container.getAttribute("data-personality-notes") || + container.getAttribute("data-bio") || + null; + + assets.push({ + id, + name, + kind, + prompt: container.getAttribute("data-prompt") || null, + url, + collection_id: parentCol, + collection_name: parentCol ? (cols.get(parentCol) ?? null) : null, + primary_media_id: mediaEl?.getAttribute("data-media-id") || null, + personality_notes: bioAttr, + voice: container.getAttribute("data-voice") || null, + trim_start_seconds: null, + trim_end_seconds: null, + media_status: "success", + media_error: null, + width: null, + height: null, + duration: null, + created_at: null, + }); + } + + for (const asset of assets) { + if (asset.collection_id && !asset.collection_name) { + asset.collection_name = cols.get(asset.collection_id) ?? null; + } + } + const collections: SnapshotCollectionItem[] = [...cols.entries()].map(([cid, cname]) => ({ + id: cid, + name: cname, + count: counts.get(cid) ?? 0, + })); + + const titleEl = document.querySelector( + 'input[aria-label="Editable text"], .editable-text-input, [data-testid="project-title"]', + ); + const rawTitle = titleEl + ? ((titleEl as HTMLInputElement).value || titleEl.textContent || "").trim() + : ""; + const docTitle = (document.title || "") + .replace(/\s*[-–|]\s*(?:Google\s*)?Flow\s*$/i, "") + .trim(); + + return { + ok: true, + projectId, + projectTitle: rawTitle || docTitle || null, + credits: null, + assets, + collections, + }; +} + /** Reads project tiles, scenes, characters, and collections from bound runtime state. */ -export function readStoreSnapshot(): StoreSnapshotResult { +export function readStoreSnapshot(allowDomFallback = false): StoreSnapshotResult { const match = /\/project\/([^/?#]+)/.exec(location.pathname || ""); const projectId = match ? match[1] : null; const helper = runtimeState.store; const l = runtimeState.lService; - if ( - (helper || l) && - (runtimeState.routePath !== location.pathname || - l?.Ca?.Va || - l?._ap?.Ca?.Va || - l?.ha?.Ca?.Va) - ) { + const storeDestroyed = Boolean( + l && + (isComponentDestroyed(l) || + (l._ap ? isComponentDestroyed(l._ap) : false) || + (l._qt ? isComponentDestroyed(l._qt.owner) : false)), + ); + if ((helper || l) && (runtimeState.routePath !== location.pathname || storeDestroyed)) { clearStore(); - return { ok: false, error: "route_changed" }; + if (!allowDomFallback) return { ok: false, error: "route_changed" }; } if (typeof helper?.isReady === "function" && !helper.isReady()) { - return { ok: false, error: "store_loading" }; + return allowDomFallback ? readDomWorkspaceSnapshot(projectId) : { ok: false, error: "store_loading" }; } const tileMap = helper?.getTileMap?.(); if (!(tileMap instanceof Map)) { - return { ok: false, error: "store_not_bound" }; + return allowDomFallback ? readDomWorkspaceSnapshot(projectId) : { ok: false, error: "store_not_bound" }; } if ( projectId && diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index 2b31842..6aaf538 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -5,9 +5,31 @@ import { createScene } from "./angular"; import { delay } from "./dom"; +import { inferAddClipsShape, inferSingleTileShape } from "./mutation_shapes"; +import { sceneContents } from "./scene_tiles"; import { runtimeState } from "./state"; import type { FlowTile, SceneOpRequest } from "./types"; +/** Maximum wait for `add_workflows_to_scene` callback or store clip confirmation. */ +const SCENE_ADD_CLIPS_TIMEOUT_MS = 15_000; +/** Maximum wait for optional post-create scene rename. */ +const SCENE_RENAME_TIMEOUT_MS = 10_000; + +/** Runs an async promise under a bounded timeout and clears its timer on settle. */ +async function withBoundedTimeout(work: Promise, timeoutMs: number, code: string): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + work, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(code)), timeoutMs); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { const helper = runtimeState.store; @@ -22,16 +44,21 @@ export async function sceneOp(req: SceneOpRequest): Promise { ids.map((id) => String(getMap()?.get(id)?.workflowId || id)); if (action === "create") { - const assetIds = Array.isArray(req?.asset_ids) - ? req.asset_ids.map(String) - : []; + const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map(String) : []; const created = await createScene(helper, getMap, resolveWfIds(assetIds)); if (!created?.ok || !created.id) { return created || { ok: false, error: "created_scene_id_not_found" }; } if (req?.name && helper?.rename) { - await helper.rename(created.id, String(req.name)); - await delay(400); + const singleCheck = inferSingleTileShape(); + if (singleCheck.ok) { + await withBoundedTimeout( + helper.rename(created.id, String(req.name)), + SCENE_RENAME_TIMEOUT_MS, + "scene_rename_timeout", + ); + await delay(300); + } } return { ok: true, @@ -42,33 +69,61 @@ export async function sceneOp(req: SceneOpRequest): Promise { if (action === "add_clips") { const sceneId = String(req?.scene_id || "").trim(); - const assetIds = Array.isArray(req?.asset_ids) - ? req.asset_ids.map(String) - : []; + const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map(String) : []; if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } - let resolveDe: (v: unknown) => void = () => {}; - let rejectDe: (e: unknown) => void = () => {}; - const dePromise = new Promise((res, rej) => { - resolveDe = res; - rejectDe = rej; - }); - await helper.mutate({ - type: "add_workflows_to_scene", - Lc: sceneId, - Ic: sceneId, - rg: resolveWfIds(assetIds), - YWa: resolveWfIds(assetIds), - position: typeof req.position === "number" ? req.position : undefined, - Mh: undefined, - Eh: undefined, - De: { resolve: resolveDe, reject: rejectDe }, - ve: { resolve: resolveDe, reject: rejectDe }, - }); - await dePromise; - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; + const shape = inferAddClipsShape(); + if (!shape.ok) { + return { ok: false, error: `${shape.reason}:${shape.check.name}:${shape.check.detail}` }; + } + + const wfIds = resolveWfIds(assetIds); + const initialTile = getMap()?.get(sceneId); + const beforeCount = initialTile ? sceneContents(initialTile).clips.length : 0; + + let callbackDone = false; + let mutateSettled = false; + let failure: string | undefined; + const completion = { + resolve: () => { + callbackDone = true; + }, + reject: (error: unknown) => { + failure ??= error instanceof Error ? error.message : String(error ?? "add_clips_failed"); + }, + }; + + const deadline = performance.now() + SCENE_ADD_CLIPS_TIMEOUT_MS; + void Promise.resolve() + .then(() => + helper.mutate({ + type: "add_workflows_to_scene", + sceneId, + workflows: wfIds, + position: typeof req.position === "number" ? req.position : undefined, + completion, + }), + ) + .then(() => { + mutateSettled = true; + }, completion.reject); + + while (performance.now() < deadline) { + if (failure) return { ok: false, error: failure }; + const currentScene = getMap()?.get(sceneId); + const nowClips = currentScene ? sceneContents(currentScene).clips.length : 0; + if ( + callbackDone || + nowClips >= beforeCount + wfIds.length || + (!shape.format.completion && mutateSettled && nowClips > beforeCount) + ) { + await delay(200); + return { ok: true, scene_id: sceneId, added: assetIds.length }; + } + await delay(150); + } + return { ok: false, error: "scene_add_clips_timeout" }; } return { ok: false, error: `unknown_scene_action:${action}` }; diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..d4acca0 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -7,16 +7,132 @@ import { readOwn } from "./angular"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +/** Returns true when `value` is a non-empty or valid array of scene clip descriptors. */ +function isSceneClipArray(value: unknown): value is SceneClipItem[] { + if (!Array.isArray(value)) return false; + return value.every( + (item) => + Boolean(item && typeof item === "object" && !Array.isArray(item)) && + (typeof (item as SceneClipItem).workflowId === "string" || + typeof (item as SceneClipItem).workflowId === "number"), + ); +} + +/** Returns true when `value` is a media payload array inside a scene workflow history map. */ +function isHistoryMediaList(value: unknown): value is FlowMediaPayload[] { + return ( + Array.isArray(value) && + value.every( + (m) => + Boolean(m && typeof m === "object" && !Array.isArray(m)) && + ("id" in m || "Wb" in m || "fifeUrl" in m || "videoUrl" in m || "Bd" in m || "url" in m), + ) + ); +} + +/** Collects own values on `tile` and one-level nested plain containers for structural scene probing. */ +function sceneCandidateValues(tile: FlowTile): unknown[] { + const out: unknown[] = []; + for (const val of Object.values(tile as Record)) { + out.push(val); + if ( + val && + typeof val === "object" && + !Array.isArray(val) && + !(val instanceof Map) && + !(val instanceof Date) + ) { + for (const sub of Object.values(val as Record)) out.push(sub); + } + } + return out; +} + +/** Infers the clip list of a scene tile from verified, known, or live object fields. */ +function findSceneClips(tile: FlowTile, verifiedKey?: string): SceneClipItem[] { + if (verifiedKey) { + const direct = readOwn(tile, verifiedKey); + if (Array.isArray(direct)) return direct as SceneClipItem[]; + } + const candidates = sceneCandidateValues(tile); + const nonEmpty = candidates.filter( + (val): val is SceneClipItem[] => isSceneClipArray(val) && val.length > 0, + ); + if (nonEmpty.length === 1) return nonEmpty[0]; + for (const key of ["Uc", "Tc", "Oc"]) { + const known = readOwn(tile, key); + if (isSceneClipArray(known)) return known; + } + const emptyArrays = candidates.filter( + (v): v is SceneClipItem[] => Array.isArray(v) && v.length === 0, + ); + return emptyArrays.length === 1 ? emptyArrays[0] : []; +} + +/** Infers the workflow history map of a scene tile from verified, known, or live object fields. */ +function findSceneHistory( + tile: FlowTile, + clips: readonly SceneClipItem[], + verifiedKey?: string, +): Map { + const toMap = (candidate: unknown): Map | null => { + if (candidate instanceof Map) { + const entries = [...candidate.entries()]; + if ( + entries.every( + ([k, v]) => (typeof k === "string" || typeof k === "number") && isHistoryMediaList(v), + ) + ) { + return new Map(entries.map(([k, v]) => [String(k), v])); + } + return null; + } + if ( + candidate && + typeof candidate === "object" && + !Array.isArray(candidate) && + !(candidate instanceof Date) + ) { + const entries = Object.entries(candidate as Record); + if (entries.length > 0 && entries.every(([, v]) => isHistoryMediaList(v))) { + return new Map(entries.map(([k, v]) => [k, v as FlowMediaPayload[]])); + } + } + return null; + }; + + if (verifiedKey) { + const direct = toMap(readOwn(tile, verifiedKey)); + if (direct) return direct; + } + const wfSet = new Set(clips.map((c) => String(c.workflowId ?? "")).filter(Boolean)); + const nonEmptyMaps: Map[] = []; + const emptyMaps: Map[] = []; + for (const val of sceneCandidateValues(tile)) { + const parsed = toMap(val); + if (!parsed) continue; + if (parsed.size > 0) nonEmptyMaps.push(parsed); + else emptyMaps.push(parsed); + } + if (nonEmptyMaps.length === 1) return nonEmptyMaps[0]; + if (nonEmptyMaps.length > 1 && wfSet.size > 0) { + const matching = nonEmptyMaps.filter((m) => [...wfSet].some((id) => m.has(id))); + if (matching.length === 1) return matching[0]; + } + for (const key of ["Cg", "tg", "Yf"]) { + const known = toMap(readOwn(tile, key)); + if (known) return known; + } + return emptyMaps.length === 1 ? emptyMaps[0] : new Map(); +} + /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { + if (!tile || typeof tile !== "object") { + return { clips: [] as SceneClipItem[], history: new Map() }; + } const format = frontendBuild(readBuildLabel())?.projectStore.scene; - const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; - const history = (format && readOwn(tile, format.history)) ?? tile.Yf; - const entries: Iterable<[string, FlowMediaPayload[]]> = history instanceof Map - ? history.entries() - : history && typeof history === "object" ? Object.entries(history) : []; - return { - clips: Array.isArray(clips) ? clips as SceneClipItem[] : [], - history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), - }; + const clips = findSceneClips(tile, format?.clips); + const history = findSceneHistory(tile, clips, format?.history); + return { clips, history }; } diff --git a/ts/store_shapes.ts b/ts/store_shapes.ts new file mode 100644 index 0000000..3fd0454 --- /dev/null +++ b/ts/store_shapes.ts @@ -0,0 +1,715 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Discover live Angular stores, tile caches, and character preview panels by runtime structure. + +import { isNgLViewMap, readOwn, resolveLView } from "./angular"; +import { legacyMedia } from "./dom"; +import { + frontendBuild, + NOVEMBER_20_CHARACTER_PREVIEW, + readBuildLabel, + type CharacterPreviewFormat, + type ProjectStoreFormat, +} from "./frontend_builds"; +import type { FlowMediaPayload, FlowTile, NgLView } from "./types"; + +/** Lifecycle field pair and active status on an Angular service or component. */ +export interface LifecycleShape { + /** Property name of the lifecycle controller on the owner object. */ + lifecycle: string; + /** Property name of the boolean destroyed flag on the lifecycle controller. */ + destroyed: string; + /** True when the lifecycle controller is active and not destroyed. */ + active: boolean; +} + +/** Candidate project store binding discovered in Angular views. */ +export interface DiscoveredStoreCandidate { + /** Project ID matched on the store signal. */ + projectId: string; + /** Store service object. */ + service: object; + /** Inferred or verified field names on the store and tile query. */ + format: ProjectStoreFormat; + /** Angular view registry map that holds the store. */ + views: Map; +} + +/** Structural discovery result across all Angular view maps. */ +export interface StoreDiscoveryOutcome { + /** Validated unique candidates. */ + candidates: DiscoveredStoreCandidate[]; + /** True when structural probing found ambiguous inner fields on an active store. */ + ambiguousInner: boolean; +} + +/** Character slot name in the character editor preview panel. */ +export type PreviewSlotName = "portrait" | "body"; + +/** Bound character preview panel operations. */ +export interface BoundCharacterPreview { + /** Opens the native file chooser for the active slot when uniquely identified. */ + upload: (() => unknown) | null; + /** Reads the media payload of the requested slot. */ + media: (slot: PreviewSlotName) => FlowMediaPayload | null | undefined; + /** Reads the active preview image URL. */ + source: () => unknown; + /** Reads whether the preview panel is busy. */ + busy: () => unknown; +} + +/** Known lifecycle field pairs from earlier Flow builds. */ +const KNOWN_LIFECYCLE_PAIRS: ReadonlyArray = [ + ["Ba", "Va"], + ["Ca", "Va"], + ["Ca", "Wa"], + ["Ba", "Wa"], +]; + +/** Legacy character preview field names used before build 20261120.00. */ +const LEGACY_CHARACTER_PREVIEW: CharacterPreviewFormat = { + lifecycle: "Ca", + upload: "JR", + marker: "Si", + portrait: "ka", + body: "ma", + source: "psa", + busy: "zy", +}; + +/** Mutation literal markers that identify the project tile dispatcher method. */ +const DISPATCHER_MARKERS = [ + "create_collection", + "set_display_name", + "single_tile", + "batch_move_to_collection", + "batch_set_tiles_trashed", + "create_scene", + "add_workflows_to_scene", +]; + +/** Returns true when `value` is a plain or class instance object suitable for structural inspection. */ +function isInspectableObject(value: unknown): value is object { + return Boolean( + value && + typeof value === "object" && + !(value instanceof Node) && + !Array.isArray(value) && + !(value instanceof Map) && + !(value instanceof Set) && + !(value instanceof Date) && + !(value instanceof RegExp), + ); +} + +/** Reads `Function.prototype.toString` safely without throwing on bound or host functions. */ +export function safeFnSource(fn: unknown): string { + if (typeof fn !== "function") return ""; + try { + return Function.prototype.toString.call(fn); + } catch { + return ""; + } +} + +/** Finds the lifecycle controller and boolean destroyed flag on an Angular object. */ +export function findLifecycleFields(owner: unknown): LifecycleShape | null { + if (!isInspectableObject(owner)) return null; + for (const [lifecycle, destroyed] of KNOWN_LIFECYCLE_PAIRS) { + const ctrl = readOwn(owner, lifecycle); + if (!isInspectableObject(ctrl)) continue; + const flag = readOwn(ctrl, destroyed); + if (typeof flag === "boolean") { + return { lifecycle, destroyed, active: !flag }; + } + } + const matches: LifecycleShape[] = []; + for (const key of Object.keys(owner).slice(0, 40)) { + const ctrl = readOwn(owner, key); + if (!isInspectableObject(ctrl)) continue; + const onDestroy = readOwn(ctrl, "onDestroy"); + if (typeof onDestroy !== "function") continue; + const boolKeys = Object.keys(ctrl).filter( + (k) => typeof readOwn(ctrl, k) === "boolean", + ); + if (boolKeys.some((k) => readOwn(ctrl, k) === true)) { + return { lifecycle: key, destroyed: boolKeys[0] ?? "destroyed", active: false }; + } + if (boolKeys.length === 1) { + matches.push({ lifecycle: key, destroyed: boolKeys[0], active: true }); + continue; + } + const src = safeFnSource(onDestroy); + const referenced = boolKeys.filter((k) => + new RegExp(`\\.${k.replace(/\$/g, "\\$")}\\b`).test(src), + ); + if (referenced.length === 1) { + matches.push({ lifecycle: key, destroyed: referenced[0], active: true }); + } + } + return matches.length === 1 ? matches[0] : null; +} + +/** Returns true when an Angular service or component lifecycle reports a destroyed instance. */ +export function isComponentDestroyed(owner: unknown): boolean { + if (!isInspectableObject(owner)) return true; + for (const [lifecycle, destroyed] of KNOWN_LIFECYCLE_PAIRS) { + if (readOwn(readOwn(owner, lifecycle), destroyed) === true) return true; + for (const nestedKey of ["_ap", "ha"]) { + if (readOwn(readOwn(readOwn(owner, nestedKey), lifecycle), destroyed) === true) { + return true; + } + } + } + const shape = findLifecycleFields(owner); + return shape !== null && !shape.active; +} + +/** Returns true when `key` matches `["PROJECT_TILES", projectId]` or starts with `"PROJECT_TILES"`. */ +function matchesProjectTilesKey(key: unknown, projectId: string | null): boolean { + if (!Array.isArray(key) || key[0] !== "PROJECT_TILES") return false; + return projectId === null ? key.length >= 1 : key.length === 2 && key[1] === projectId; +} + +/** Returns true when `rows` is an array of valid Flow tile objects with unique IDs. */ +export function isValidTileRowArray(rows: unknown): rows is FlowTile[] { + if (!Array.isArray(rows)) return false; + const seenIds = new Set(); + for (const item of rows) { + if ( + !item || + typeof item !== "object" || + typeof (item as { id?: unknown }).id !== "string" || + !(item as { id: string }).id || + typeof (item as { type?: unknown }).type !== "string" + ) { + return false; + } + const id = (item as { id: string }).id; + if (seenIds.has(id)) return false; + seenIds.add(id); + } + return true; +} + +/** Inspects a query data payload to find the unique own property holding tile rows. */ +function findUniqueRowsField( + data: unknown, +): { field: string } | { ambiguous: boolean } { + if (isValidTileRowArray(data)) return { field: "__self__" }; + if (data instanceof Map && isValidTileRowArray([...data.values()])) { + return { field: "__map__" }; + } + if (!isInspectableObject(data)) return { ambiguous: false }; + const nonEmpty: string[] = []; + const empty: string[] = []; + for (const key of Object.keys(data)) { + const val = readOwn(data, key); + if (!isValidTileRowArray(val)) continue; + if (val.length > 0) nonEmpty.push(key); + else empty.push(key); + } + if (nonEmpty.length === 1) return { field: nonEmpty[0] }; + if (nonEmpty.length > 1) return { ambiguous: true }; + if (empty.length === 1) return { field: empty[0] }; + return { ambiguous: empty.length > 1 }; +} + +/** Finds dispatcher methods on a tile service object by source markers and arity. */ +function findDispatcherMethods(tilesService: object): string[] { + const names = new Set(); + let cur: object | null = tilesService; + for (let depth = 0; cur && cur !== Object.prototype && depth < 4; depth++) { + for (const key of Object.getOwnPropertyNames(cur)) { + if (key === "constructor" || key === "queryKey") continue; + const fn = readOwn(tilesService, key); + if (typeof fn !== "function") continue; + const src = safeFnSource(fn); + if ( + src.includes("PROJECT_TILES") && + DISPATCHER_MARKERS.some((marker) => src.includes(marker)) + ) { + names.add(key); + } + } + cur = Object.getPrototypeOf(cur); + } + return [...names]; +} + +/** Probes one object for the tile query service layout (`queryClient`, `rows`, `dispatcher`). */ +export function inspectTilesServiceShape( + tiles: unknown, + projectId: string | null, +): { + queryClient: string; + rows: string; + dispatcher: string; + ambiguousDispatcher: boolean; +} | { ambiguous: true } | null { + if (!isInspectableObject(tiles)) return null; + const queryKeyFn = readOwn(tiles, "queryKey"); + if (typeof queryKeyFn !== "function") return null; + let key: unknown; + try { + key = queryKeyFn.call(tiles, projectId); + } catch { + return null; + } + if (!matchesProjectTilesKey(key, projectId)) return null; + + const clientMatches: Array<{ queryClient: string; rows: string }> = []; + let sawAmbiguousRows = false; + for (const prop of Object.keys(tiles).slice(0, 40)) { + const client = readOwn(tiles, prop); + const cache = readOwn(client, "queryCache"); + const find = readOwn(cache, "find"); + if (typeof find !== "function") continue; + let query: { queryKey?: unknown; state?: { status?: string; data?: unknown }; fetch?: unknown } | undefined; + try { + query = find.call(cache, { queryKey: key, exact: true }) as typeof query; + } catch { + continue; + } + if ( + !query || + !matchesProjectTilesKey(query.queryKey, projectId) || + !query.state || + query.state.status === "pending" + ) { + continue; + } + const rowsRes = findUniqueRowsField(query.state.data); + if ("field" in rowsRes) { + clientMatches.push({ queryClient: prop, rows: rowsRes.field }); + } else if (rowsRes.ambiguous) { + sawAmbiguousRows = true; + } + } + if (sawAmbiguousRows || clientMatches.length > 1) return { ambiguous: true }; + if (clientMatches.length === 0) return null; + + const dispatchers = findDispatcherMethods(tiles); + return { + queryClient: clientMatches[0].queryClient, + rows: clientMatches[0].rows, + dispatcher: dispatchers.length === 1 ? dispatchers[0] : "", + ambiguousDispatcher: dispatchers.length > 1, + }; +} + +/** Probes one Angular object to determine whether it is a live project shell store for `projectId`. */ +function probeStoreObject( + service: object, + projectId: string, +): { format: ProjectStoreFormat } | { ambiguous: true } | null { + const life = findLifecycleFields(service); + if (!life || !life.active) return null; + + const projectGetters: string[] = []; + const tileServices: Array<{ + tilesService: string; + queryClient: string; + rows: string; + dispatcher: string; + }> = []; + + for (const key of Object.keys(service).slice(0, 50)) { + if (key === life.lifecycle) continue; + const val = Object.getOwnPropertyDescriptor(service, key)?.value; + if (typeof val === "function" && val.length === 0) { + try { + if (val.call(service) === projectId) projectGetters.push(key); + } catch { + // Ignore throwing signal or getter. + } + continue; + } + const tilesShape = inspectTilesServiceShape(val, projectId); + if (!tilesShape) continue; + if ("ambiguous" in tilesShape || tilesShape.ambiguousDispatcher) { + return { ambiguous: true }; + } + tileServices.push({ + tilesService: key, + queryClient: tilesShape.queryClient, + rows: tilesShape.rows, + dispatcher: tilesShape.dispatcher, + }); + } + + if (tileServices.length === 0 || projectGetters.length === 0) return null; + if (tileServices.length > 1 || projectGetters.length > 1) { + return { ambiguous: true }; + } + + const tiles = tileServices[0]; + const ctorName = + typeof (service as { constructor?: { name?: unknown } }).constructor?.name === "string" + ? ((service as { constructor: { name: string } }).constructor.name || "DiscoveredStore") + : "DiscoveredStore"; + return { + format: { + storeClass: ctorName, + lifecycle: life.lifecycle, + destroyed: life.destroyed, + projectId: projectGetters[0], + tilesService: tiles.tilesService, + queryClient: tiles.queryClient, + dispatcher: tiles.dispatcher, + rows: tiles.rows, + }, + }; +} + +/** Discovers live project store candidates by runtime structure across Angular view maps. */ +export function discoverProjectStoreCandidates( + maps: unknown[], + projectId: string, +): StoreDiscoveryOutcome { + const seen = new Set(); + const candidates: DiscoveredStoreCandidate[] = []; + let ambiguousInner = false; + + const consider = (value: unknown, views: Map): void => { + if (!isInspectableObject(value) || seen.has(value)) return; + seen.add(value); + const probed = probeStoreObject(value, projectId); + if (!probed) return; + if ("ambiguous" in probed) { + ambiguousInner = true; + return; + } + candidates.push({ + projectId, + service: value, + format: probed.format, + views, + }); + }; + + for (const map of maps) { + if (!isNgLViewMap(map)) continue; + for (const view of map.values()) { + if (!Array.isArray(view)) continue; + for (const slot of view) { + consider(slot, map); + if (!isInspectableObject(slot)) continue; + for (const key of Object.keys(slot).slice(0, 40)) { + consider(Object.getOwnPropertyDescriptor(slot, key)?.value, map); + } + } + } + } + return { candidates, ambiguousInner }; +} + +/** Discovers a query-cache tile store handle inside a single Angular LView for `discoverStore`. */ +export function discoverQueryTileServiceInLView( + lv: unknown, + projectId: string | null, +): { + owner: object; + tilesService: object; + queryClient: string; + rows: string; + dispatcher: string; +} | null { + if (!Array.isArray(lv) || !projectId) return null; + const checkCandidate = (cand: unknown) => { + if (!isInspectableObject(cand) || isComponentDestroyed(cand)) return null; + const direct = inspectTilesServiceShape(cand, projectId); + if (direct && !("ambiguous" in direct) && !direct.ambiguousDispatcher) { + return { + owner: cand, + tilesService: cand, + queryClient: direct.queryClient, + rows: direct.rows, + dispatcher: direct.dispatcher, + }; + } + const storeProbe = probeStoreObject(cand, projectId); + if (storeProbe && !("ambiguous" in storeProbe)) { + const tiles = readOwn(cand, storeProbe.format.tilesService); + if (isInspectableObject(tiles)) { + return { + owner: cand, + tilesService: tiles, + queryClient: storeProbe.format.queryClient, + rows: storeProbe.format.rows, + dispatcher: storeProbe.format.dispatcher, + }; + } + } + return null; + }; + + for (const slot of lv) { + const hit = checkCandidate(slot); + if (hit) return hit; + if (!isInspectableObject(slot)) continue; + for (const key of Object.keys(slot).slice(0, 30)) { + const nested = checkCandidate(Object.getOwnPropertyDescriptor(slot, key)?.value); + if (nested) return nested; + } + } + return null; +} + +/** Reads tile rows from a structurally discovered query-cache tile service. */ +export function readRowsFromQueryTileService( + tilesService: object, + queryClientKey: string, + rowsKey: string, + projectId: string | null, +): Map | null { + const queryKeyFn = readOwn(tilesService, "queryKey"); + const cache = readOwn(readOwn(tilesService, queryClientKey), "queryCache"); + const find = readOwn(cache, "find"); + if (typeof queryKeyFn !== "function" || typeof find !== "function") return null; + try { + const key: unknown = queryKeyFn.call(tilesService, projectId); + const query = find.call(cache, { queryKey: key, exact: true }) as { + state?: { status?: string; data?: unknown }; + } | undefined; + if (!query?.state || query.state.status === "pending") return null; + const rawData = query.state.data; + const rows = + rowsKey === "__self__" + ? rawData + : rowsKey === "__map__" + ? rawData instanceof Map + ? [...rawData.values()] + : null + : readOwn(rawData, rowsKey); + if (!Array.isArray(rows)) return null; + const map = new Map(); + for (const row of rows) { + if (row && typeof row === "object" && (row as { id?: unknown }).id != null) { + map.set(String((row as { id: unknown }).id), row as FlowTile); + } + } + return map; + } catch { + return null; + } +} + +/** Calls a zero-argument method or signal on `panel` safely. */ +function callZeroArg(panel: object, name: string): unknown { + if (!name) return undefined; + const fn = readOwn(panel, name); + if (typeof fn !== "function") return undefined; + try { + return fn.call(panel); + } catch { + return undefined; + } +} + +/** Binds a character preview panel using a static `CharacterPreviewFormat` if all members exist. */ +function tryStaticPreviewFormat( + slot: object, + format: CharacterPreviewFormat, +): BoundCharacterPreview | null { + if (isComponentDestroyed(slot)) return null; + if ( + typeof readOwn(slot, format.upload) !== "function" || + typeof readOwn(slot, format.marker) !== "function" || + typeof readOwn(slot, format.portrait) !== "function" || + typeof readOwn(slot, format.body) !== "function" + ) { + return null; + } + return { + upload: () => callZeroArg(slot, format.upload), + media: (which) => + legacyMedia(callZeroArg(slot, format[which]) as FlowMediaPayload | null | undefined), + source: () => callZeroArg(slot, format.source), + busy: () => callZeroArg(slot, format.busy), + }; +} + +/** Returns true when `value` looks like a character slot media record or an empty slot value. */ +function isMediaOrEmpty(value: unknown): boolean { + if (value === null || value === undefined) return true; + return Boolean( + isInspectableObject(value) && + typeof (value as { id?: unknown }).id === "string" && + (value as { id: string }).id.length > 0, + ); +} + +/** Structurally inspects a character preview component to bind its signals and upload method. */ +function probeCharacterPreviewComponent( + comp: object, + renderedImgSrc: string, + activeSlot: PreviewSlotName, +): BoundCharacterPreview | "ambiguous" | null { + if (!isInspectableObject(comp) || isComponentDestroyed(comp)) return null; + const proto = Object.getPrototypeOf(comp) as object | null; + if (!proto || proto === Object.prototype) return null; + + const uploadMethods: string[] = []; + let protoCombinedSrc = ""; + for (const name of Object.getOwnPropertyNames(proto)) { + if (name === "constructor") continue; + const fn = readOwn(comp, name); + if (typeof fn !== "function") continue; + const src = safeFnSource(fn); + protoCombinedSrc += `\n${src}`; + if ( + fn.length === 0 && + (/createElement\s*\(\s*["']input["']\)/i.test(src) || + /\.type\s*=\s*["']file["']/i.test(src) || + (/\.click\s*\(\s*\)/.test(src) && /accept|file|upload|consent/i.test(src))) + ) { + uploadMethods.push(name); + } + } + + const zeroArgOwn = Object.keys(comp).filter((k) => { + const fn = Object.getOwnPropertyDescriptor(comp, k)?.value; + return typeof fn === "function" && fn.length === 0; + }); + if (zeroArgOwn.length < 2 && uploadMethods.length === 0) return null; + + const signalValues = new Map(); + for (const key of zeroArgOwn) { + signalValues.set(key, callZeroArg(comp, key)); + } + + // Infer portrait and body signals from `ka`/`ma`, prototype slot branches, or media payloads. + let portraitKey = ""; + let bodyKey = ""; + if ( + signalValues.has("ka") && + signalValues.has("ma") && + isMediaOrEmpty(signalValues.get("ka")) && + isMediaOrEmpty(signalValues.get("ma")) + ) { + portraitKey = "ka"; + bodyKey = "ma"; + } else { + const branchMatch = + /portrait[^?;:]*\?\s*this\.([A-Za-z0-9_$]+)\(\)\s*:\s*this\.([A-Za-z0-9_$]+)\(\)/i.exec( + protoCombinedSrc, + ) || + /body[^?;:]*\?\s*this\.([A-Za-z0-9_$]+)\(\)\s*:\s*this\.([A-Za-z0-9_$]+)\(\)/i.exec( + protoCombinedSrc, + ); + if (branchMatch) { + const isBodyFirst = /^body/i.test(branchMatch[0]); + const first = branchMatch[1]; + const second = branchMatch[2]; + if ( + signalValues.has(first) && + signalValues.has(second) && + isMediaOrEmpty(signalValues.get(first)) && + isMediaOrEmpty(signalValues.get(second)) + ) { + portraitKey = isBodyFirst ? second : first; + bodyKey = isBodyFirst ? first : second; + } + } + if (!portraitKey || !bodyKey) { + const mediaSignals = zeroArgOwn.filter((k) => { + const v = signalValues.get(k); + return isInspectableObject(v) && typeof (v as { id?: unknown }).id === "string"; + }); + if (mediaSignals.length === 1) { + if (activeSlot === "portrait") portraitKey = mediaSignals[0]; + else bodyKey = mediaSignals[0]; + } + } + } + + // Infer source URL signal and busy boolean signal. + const stringSignals = zeroArgOwn.filter((k) => { + const v = signalValues.get(k); + return ( + typeof v === "string" && + (renderedImgSrc ? v === renderedImgSrc : /^(?:https?:|blob:|data:|$)/.test(v)) + ); + }); + const sourceKey = + (renderedImgSrc + ? stringSignals.find((k) => signalValues.get(k) === renderedImgSrc) + : stringSignals.find((k) => /^https?:|^blob:|^data:/.test(String(signalValues.get(k))))) ?? ""; + + const boolSignals = zeroArgOwn.filter((k) => typeof signalValues.get(k) === "boolean"); + const busyKey = boolSignals.length === 1 ? boolSignals[0] : ""; + + if (uploadMethods.length === 0 && !portraitKey && !bodyKey && !sourceKey) { + return null; + } + if (uploadMethods.length > 1) return "ambiguous"; + + const uploadFn = uploadMethods.length === 1 ? () => callZeroArg(comp, uploadMethods[0]) : null; + return { + upload: uploadFn, + media: (which) => { + const key = which === "portrait" ? portraitKey : bodyKey; + return legacyMedia( + (key ? callZeroArg(comp, key) : undefined) as FlowMediaPayload | null | undefined, + ); + }, + source: () => (sourceKey ? callZeroArg(comp, sourceKey) : ""), + busy: () => (busyKey ? callZeroArg(comp, busyKey) : false), + }; +} + +/** Discovers the character preview panel in Angular LViews by verified or runtime structure. */ +export function discoverCharacterPreview( + roots: Iterable, + renderedImgSrc: string, + activeSlot: PreviewSlotName, +): BoundCharacterPreview | null { + const verified = frontendBuild(readBuildLabel())?.characterPreview; + const staticFormats = verified + ? [verified] + : [NOVEMBER_20_CHARACTER_PREVIEW, LEGACY_CHARACTER_PREVIEW]; + + const seenLViews = new Set(); + const seenObjects = new Set(); + const structuralMatches: BoundCharacterPreview[] = []; + let sawAmbiguous = false; + + 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) || seenLViews.has(lv)) continue; + seenLViews.add(lv); + for (const slot of lv) { + if (!isInspectableObject(slot) || seenObjects.has(slot)) continue; + seenObjects.add(slot); + for (const fmt of staticFormats) { + const bound = tryStaticPreviewFormat(slot, fmt); + if (bound) return bound; + } + const probed = probeCharacterPreviewComponent(slot, renderedImgSrc, activeSlot); + if (probed === "ambiguous") { + sawAmbiguous = true; + } else if (probed) { + structuralMatches.push(probed); + } + } + if (depth < 4) { + if (Array.isArray(lv[3])) queue.push([lv[3], depth + 1]); + if (Array.isArray(lv[15])) queue.push([lv[15], depth + 1]); + } + } + } + + if (sawAmbiguous) return null; + if (structuralMatches.length === 1) return structuralMatches[0]; + const withUpload = structuralMatches.filter((m) => m.upload !== null); + if (withUpload.length === 1) return withUpload[0]; + return null; +} diff --git a/ts/tile_dom.ts b/ts/tile_dom.ts index 4a7c450..5c4e64e 100644 --- a/ts/tile_dom.ts +++ b/ts/tile_dom.ts @@ -1,49 +1,185 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// Locate project tiles in the page, read their state from the bound store, and dispatch page view and text control actions. +// Locate media, character, scene, and collection tiles in the virtual grid and run DOM view actions. -import { collectionIdOf, delay, dismissOverlay, isTrashedTile, legacyTile } from "./dom"; -import { openView, readText, readView, selectText } from "./page_view"; +import { readOwn, resolveLView } from "./angular"; +import { + characterLooksOf, + clickButtonByRegex, + collectionIdOf, + delay, + dismissOverlay, + elText, + fifeBase, + isTrashedTile, + isVisibleEnabled, + legacyTile, + pickTileUrl, + setNativeValue, +} from "./dom"; +import { openView, readText, readView, selectText, textPoint } from "./page_view"; +import { readStoreSnapshot } from "./read_store_snapshot"; +import { sceneContents } from "./scene_tiles"; 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`. */ +/** Returns all media IDs associated with a media, character, or scene store tile. */ function mediaIdsOf(raw: FlowTile | null | undefined): string[] { const t = legacyTile(raw); if (!t) return []; - const ids = [t.primaryMediaId, t.Fb?.id, t.Fb?.mediaId, t.mediaId]; + const ids: unknown[] = [t.primaryMediaId, t.Fb?.id, t.Fb?.mediaId, t.fb?.mediaId, t.mediaId]; + const ttype = String(t.type || "").toUpperCase(); + if (ttype === "CHARACTER") { + const looks = characterLooksOf(t); + if (looks) { + for (const entry of looks.values()) { + if (!entry) continue; + ids.push(entry.primaryMediaId, entry.media?.id, readOwn(entry, "id")); + if (Array.isArray(entry.history)) { + for (const h of entry.history) ids.push(h?.primaryMediaId, h?.media?.id, readOwn(h, "id")); + } + } + } + } else if (ttype === "SCENE") { + const { clips, history } = sceneContents(t); + for (const clip of clips) ids.push(clip?.primaryMediaId); + for (const items of history.values()) { + for (const m of items) ids.push(m?.id); + } + } return Array.from( - new Set( - ids - .filter((v) => v !== undefined && v !== null && v !== "") - .map(String), - ), + new Set(ids.filter((v) => v !== undefined && v !== null && v !== "").map(String)), ); } -/** Returns true when a store tile other than `id` shows one of `mediaIds`. */ -function mediaIsShared( - tileMap: Map, - id: string, - mediaIds: string[], -): boolean { - for (const [otherId, other] of tileMap.entries()) { - if (otherId === id) continue; - if (mediaIdsOf(other).some((m) => mediaIds.includes(m))) return true; - } - return false; +/** Returns normalized FIFE base URLs associated with a store tile, its looks, or its clips. */ +function fifeBasesOf(raw: FlowTile | null | undefined): string[] { + const t = legacyTile(raw); + if (!t) return []; + const urls: unknown[] = [pickTileUrl(t), t.ue]; + const ttype = String(t.type || "").toUpperCase(); + if (ttype === "CHARACTER") { + const looks = characterLooksOf(t); + if (looks) { + for (const entry of looks.values()) { + urls.push(entry?.Wb, entry?.fifeUrl, entry?.imageUrl, entry?.url, entry?.media?.Wb, entry?.media?.fifeUrl); + } + } + } else if (ttype === "SCENE") { + const { clips, history } = sceneContents(t); + for (const clip of clips) urls.push(clip?.Wb, clip?.fifeUrl, clip?.videoUrl, clip?.Bd); + for (const items of history.values()) { + for (const m of items) urls.push(m?.Wb, m?.fifeUrl, m?.videoUrl, m?.Bd, m?.url); + } + } + return Array.from(new Set(urls.map(fifeBase).filter(Boolean))); +} + +/** Extracts tile IDs bound inside the Angular `LView` of `container` or its immediate children. */ +function lviewTileIdsOf(container: Element): string[] { + const ids = new Set(); + const recordObj = (obj: unknown): void => { + if (!obj || typeof obj !== "object" || obj instanceof Node || Array.isArray(obj)) return; + const rawId = readOwn(obj, "id"); + const rawType = readOwn(obj, "type"); + const wfId = readOwn(obj, "workflowId"); + const entityId = readOwn(obj, "entityId"); + if (typeof rawId === "string" && rawId && (typeof rawType === "string" || wfId || entityId || "displayName" in obj)) { + ids.add(rawId); + } + if (typeof wfId === "string" && wfId) ids.add(wfId); + if (typeof entityId === "string" && entityId) ids.add(entityId); + }; + + const inspectLv = (startLv: NgLView | null): void => { + if (!Array.isArray(startLv)) return; + const queue: Array<[NgLView, number]> = [[startLv, 0]]; + const seen = new Set(); + while (queue.length > 0) { + const next = queue.shift(); + if (!next) break; + const [lv, depth] = next; + if (!Array.isArray(lv) || seen.has(lv)) continue; + seen.add(lv); + for (const slot of lv) { + if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + recordObj(slot); + for (const prop of ["tile", "item", "asset", "collection", "data"]) { + const field = readOwn(slot, prop); + const val = + typeof field === "function" && field.length === 0 + ? safeCall(field as () => unknown, slot) + : field; + recordObj(val); + } + } + if (depth < 2) { + for (const slot of lv) { + if (Array.isArray(slot) && slot.length >= 20) queue.push([slot as NgLView, depth + 1]); + } + } + } + }; + + inspectLv(resolveLView(container)); + for (const child of Array.from(container.children).slice(0, 4)) { + inspectLv(resolveLView(child)); + } + return [...ids]; } -/** Returns the rendered grid tiles that show one of `mediaIds`. */ -function findContainers(mediaIds: string[]): HTMLElement[] { - const found = new Set(); - for (const el of Array.from(document.querySelectorAll("[data-media-id]"))) { - if (!mediaIds.includes(el.getAttribute("data-media-id") || "")) continue; - const container = el.closest("flow-grid-tile-container"); - if (container) found.add(container); +/** Calls a zero-argument getter safely. */ +function safeCall(fn: () => unknown, ctx: unknown): unknown { + try { + return fn.call(ctx); + } catch { + return undefined; } - return Array.from(found); +} + +/** Extracts explicit tile, route, workflow, or entity IDs rendered on `container` in the DOM. */ +function domDirectIdsOf(container: Element): string[] { + const out = new Set(); + for (const attr of ["data-tile-id", "data-id", "data-workflow-id", "data-entity-id"]) { + const v = container.getAttribute(attr); + if (v) out.add(v); + for (const sub of container.querySelectorAll(`[${attr}]`)) { + const sv = sub.getAttribute(attr); + if (sv) out.add(sv); + } + } + for (const link of container.querySelectorAll("a[href]")) { + const href = link.getAttribute("href") || ""; + const m = /\/(?:collection|character|scene|edit)\/([^/?#]+)/.exec(href); + if (m?.[1]) out.add(decodeURIComponent(m[1])); + } + return [...out]; +} + +/** Reads the rendered title or folder label inside a tile container. */ +function containerTitleOf(container: Element): string { + const titleEl = container.querySelector( + ".asset-title, .tile-title, [data-tile-title], .collection-name, flow-collection-tile h3, h3, h4", + ); + if (titleEl) { + const t = elText(titleEl).trim(); + if (t) return t; + } + const attrTitle = ( + container.getAttribute("data-tile-name") || + container.getAttribute("aria-label") || + "" + ).trim(); + if (attrTitle) return attrTitle; + const rawLines = (elText(container) || "") + .split(/\r?\n/) + .map((s) => s.trim()) + .filter(Boolean); + if (rawLines.length >= 3 && /^\d+$/.test(rawLines[rawLines.length - 1])) { + return rawLines[0]; + } + return ""; } /** Returns the viewport center of `el`. */ @@ -59,7 +195,7 @@ function scrollsVertically(el: HTMLElement): boolean { return overflow === "auto" || overflow === "scroll"; } -/** Returns the element that scrolls the tile grid: the nearest scrolling ancestor of a rendered tile, or the largest scrolling element of the page. */ +/** Returns the element that scrolls the tile grid. */ function findScroller(): HTMLElement | null { const tile = document.querySelector("flow-grid-tile-container"); for (let el = tile?.parentElement ?? null; el; el = el.parentElement) { @@ -77,30 +213,40 @@ function findScroller(): HTMLElement | null { return best; } -/** Scrolls the grid from the top until `find` returns the tiles to use, and returns the points of the single tile and of its "More options" button. */ -async function locateContainer(find: () => HTMLElement[]): Promise> { - let container: HTMLElement | undefined = find()[0]; +/** Scrolls the grid until `find` locates the target tile, rejecting ambiguous matches. */ +async function locateContainer( + find: () => { containers: HTMLElement[]; ambiguousReason?: string }, +): Promise> { + let step = find(); + if (step.ambiguousReason) return { ok: false, error: step.ambiguousReason }; + let container: HTMLElement | undefined = step.containers[0]; const scroller = findScroller(); if (!container && scroller) { scroller.scrollTop = 0; await delay(250); - container = find()[0]; + step = find(); + if (step.ambiguousReason) return { ok: false, error: step.ambiguousReason }; + container = step.containers[0]; for (let i = 0; i < 80 && !container; i++) { const before = scroller.scrollTop; scroller.scrollTop = before + Math.max(200, scroller.clientHeight * 0.8); await delay(200); - container = find()[0]; + step = find(); + if (step.ambiguousReason) return { ok: false, error: step.ambiguousReason }; + container = step.containers[0]; if (scroller.scrollTop === before) break; } } if (!container) return { ok: false, error: "tile_not_rendered" }; container.scrollIntoView({ block: "center" }); await delay(300); - // The virtual grid can replace the element after a scroll. const rendered = find(); - if (rendered.length > 1) return { ok: false, error: "tile_ambiguous" }; - container = rendered[0] ?? container; - const menu = container.querySelector('button[aria-label="More options"]'); + if (rendered.ambiguousReason) return { ok: false, error: rendered.ambiguousReason }; + if (rendered.containers.length > 1) return { ok: false, error: "tile_ambiguous" }; + container = rendered.containers[0] ?? container; + const menu = + container.querySelector('button[aria-label="More options"]') || + container.querySelector('button[aria-label*="More" i], button[aria-haspopup="menu"]'); return { ok: true, tile: centerOf(container), @@ -108,45 +254,304 @@ 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)) { - return { ok: false, error: "tile_media_ambiguous" }; - } - return locateContainer(() => findContainers(mediaIds)); + const rawTile = tileMap instanceof Map ? tileMap.get(id) : undefined; + const tile = legacyTile(rawTile); + + const targetIds = new Set([id]); + if (tile) { + if (tile.id) targetIds.add(String(tile.id)); + if (tile.workflowId) targetIds.add(String(tile.workflowId)); + if (tile.entityId) targetIds.add(String(tile.entityId)); + } + + const mediaIds = tile ? mediaIdsOf(tile) : []; + const fifeBases = tile ? fifeBasesOf(tile) : []; + const domSnap = !(tileMap instanceof Map) ? readStoreSnapshot(true) : null; + const domName = domSnap?.ok + ? (domSnap.assets?.find((a) => a.id === id)?.name ?? + domSnap.collections?.find((c) => c.id === id)?.name ?? + "") + : ""; + const wantName = tile ? String(tile.displayName ?? "").trim() : (domName || id).trim(); + const wantType = tile ? String(tile.type ?? "").toUpperCase() : ""; + + let mediaShared = false; + let fifeShared = false; + let nameShared = false; + if (tileMap instanceof Map && tile) { + const isColId = (v: string): boolean => + String(tileMap.get(v)?.type || "").toUpperCase() === "COLLECTION"; + const myCol = wantType === "COLLECTION" ? null : collectionIdOf(tile, isColId); + for (const [otherId, otherRaw] of tileMap.entries()) { + if (otherId === id || isTrashedTile(otherRaw)) continue; + if (mediaIds.length > 0 && mediaIdsOf(otherRaw).some((m) => mediaIds.includes(m))) { + mediaShared = true; + } + if (fifeBases.length > 0 && fifeBasesOf(otherRaw).some((f) => fifeBases.includes(f))) { + fifeShared = true; + } + const other = legacyTile(otherRaw); + const otherCol = + String(other?.type || "").toUpperCase() === "COLLECTION" + ? null + : collectionIdOf(other, isColId); + if (wantName && otherCol === myCol && String(other?.displayName ?? "").trim() === wantName) { + nameShared = true; + } + } + } + + return locateContainer(() => { + const allContainers = Array.from( + document.querySelectorAll("flow-grid-tile-container"), + ).filter((c) => c.getClientRects().length > 0); + + // 1. Exact tile identity via Angular LView binding or explicit DOM tile/route attributes. + const exactMatches = allContainers.filter((c) => { + const lvIds = lviewTileIdsOf(c); + if (lvIds.some((lid) => targetIds.has(lid))) return true; + const domIds = domDirectIdsOf(c); + return domIds.some((did) => targetIds.has(did)); + }); + if (exactMatches.length > 1) return { containers: [], ambiguousReason: "tile_ambiguous" }; + if (exactMatches.length === 1) return { containers: exactMatches }; + + // 2. Media ID attribute match (including character look and scene clip media IDs). + const candidateMediaIds = mediaIds.length > 0 ? mediaIds : !(tileMap instanceof Map) ? [id] : []; + if (candidateMediaIds.length > 0) { + const mediaContainers = allContainers.filter((c) => + Array.from(c.querySelectorAll("[data-media-id]")).some((el) => + candidateMediaIds.includes(el.getAttribute("data-media-id") || ""), + ), + ); + if (mediaContainers.length > 0) { + if (mediaShared) return { containers: [], ambiguousReason: "tile_media_ambiguous" }; + if (mediaContainers.length > 1) return { containers: [], ambiguousReason: "tile_ambiguous" }; + return { containers: mediaContainers }; + } + } + + // 3. Unique FIFE media URL match on rendered `` or `