diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..04b7cee 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -122,6 +122,8 @@ List, create, open, rename, or delete Google Flow projects. | `id` | `string` | No | Target project ID for `"open"`, `"rename"`, or `"delete"`. | | `title` | `string` | No | New title for `"create"` or `"rename"`, or case-insensitive title match for `"open"` or `"delete"`. | +For `"delete"`, if the confirmation deadline expires after `flow-mcp` clicks Delete project, the tool returns `outcome_unknown`. Call `"list"` to check whether the project still exists before you retry. + --- ## 2. Characters & voice tools diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index 559b074..c92aea6 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -122,6 +122,8 @@ Google Flow プロジェクトを一覧表示、作成、開く、名前変更 | `id` | `string` | いいえ | `"open"`、`"rename"`、または `"delete"` 用の対象プロジェクト ID。 | | `title` | `string` | いいえ | `"create"` または `"rename"` 用の新しいタイトル、あるいは `"open"` / `"delete"` 用の大文字小文字を区別しないタイトル一致。 | +`"delete"` で `flow-mcp` が削除の確認ボタンをクリックした後に確認の期限を過ぎた場合、ツールは `outcome_unknown` を返します。再試行する前に `"list"` を呼び出してプロジェクトが残っているか確認してください。 + --- ## 2. キャラクター・ボイスツール diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..4dc5212 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -122,6 +122,8 @@ flow-mcp [OPTIONS] | `id` | `string` | 否 | 用于 `"open"`、`"rename"` 或 `"delete"` 的目标项目 ID。 | | `title` | `string` | 否 | 用于 `"create"` 或 `"rename"` 的新标题,或用于 `"open"` 与 `"delete"` 的忽略大小写标题匹配词。 | +对于 `"delete"`,如果 `flow-mcp` 点击删除确认按钮后超出确认时限,工具会返回 `outcome_unknown`。请先调用 `"list"` 检查项目是否仍存在,再决定是否重试。 + --- ## 2. 角色与音色工具 diff --git a/src/assets.rs b/src/assets.rs index c3c8975..0d3a04e 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -17,7 +17,7 @@ use crate::collections::{FlowCollection, find_collection}; use crate::db::FlowDb; use crate::download::eval_resolve_media_url; use crate::engine::ChromeEngine; -use crate::project::{ensure_flow_store, read_snapshot}; +use crate::project::{clean_project_title, ensure_flow_store, read_snapshot}; use crate::project_store::ProjectStoreSession; use crate::tile_menu::{rename_through_menu, tile_state, trash_through_menu}; @@ -246,16 +246,11 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result Result> { +) -> Result { let snap = read_project_assets(engine).await?; + let project_id = snap.project_id; + let project_title = snap.project_title; let all = snap.assets; let q_lower = request @@ -396,7 +393,19 @@ pub(crate) async fn list_assets( filtered.truncate(lim); } } - Ok(filtered) + Ok(ProjectAssetsSnapshot { + project_id, + project_title, + assets: filtered, + }) +} + +/// Lists assets in the active Flow project matching optional query, kind, collection, and limit filters. +pub(crate) async fn list_assets( + engine: &ChromeEngine, + request: &AssetsParams, +) -> Result> { + Ok(list_assets_snapshot(engine, request).await?.assets) } /// Checks whether the asset snapshot shows the requested name. diff --git a/src/characters.rs b/src/characters.rs index 12c6de2..154ecc5 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -20,7 +20,9 @@ use crate::project::{ ensure_flow_store, ensure_project_workspace_root, project_id_from_url, project_subroute_url, project_workspace_url, }; -use crate::project_route::character_id_from_url; +use crate::project_route::{ + character_id_from_url, is_character_route_url, is_project_subroute_url, +}; use crate::project_store::ProjectStoreSession; use crate::queue::{ProgressCallback, SceneParams}; use crate::voices::{ @@ -108,63 +110,51 @@ pub(crate) async fn open_character_editor( project_id: &str, char_id: &str, ) -> Result<()> { - let res = engine - .call_flow_async( - "characterOp", - json!([{ - "action": "open_editor", - "project_id": project_id, - "character_id": char_id, - }]), - ) - .await; - if res - .as_ref() - .ok() - .and_then(|v| v.get("ok")) - .and_then(|v| v.as_bool()) - == Some(true) + let req = + json!([{ "action": "open_editor", "project_id": project_id, "character_id": char_id }]); + if let Ok(res) = engine.call_flow_async("characterOp", req).await + && res.get("ok").and_then(Value::as_bool) == Some(true) { tokio::time::sleep(Duration::from_millis(300)).await; let _ = ensure_flow_store(engine).await; return Ok(()); } // Use direct URL navigation if the SPA router does not open the editor. - let char_url = - project_subroute_url(reference_url, project_id, &format!("character/{}", char_id)); + let char_url = project_subroute_url(reference_url, project_id, &format!("character/{char_id}")); engine.navigate(&char_url).await?; tokio::time::sleep(Duration::from_millis(1800)).await; let _ = ensure_flow_store(engine).await; Ok(()) } -/// Exits the character editor back to `/project/` and clears stale Angular store handles. +/// Exits the character editor back to `/project/` or `/project//collection/` and clears stale Angular store handles. pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Option<&str>) { let before_finish = engine.current_url().await.unwrap_or_default(); - let in_character = before_finish.contains("/character/"); + let in_character = is_character_route_url(&before_finish); let finish_res = engine .call_flow_async("characterOp", json!([{ "action": "finish" }])) .await; let in_workspace = finish_res - .as_ref() .ok() - .and_then(|v| v.get("in_workspace")) - .and_then(|v| v.as_bool()) + .and_then(|v| v.get("in_workspace").and_then(Value::as_bool)) .unwrap_or(false); + let _ = ensure_project_workspace_root(engine).await; let cur = engine.current_url().await.unwrap_or_default(); - if (in_character && !in_workspace) || cur.contains("/character/") { - if !cur.contains("/character/") { - tokio::time::sleep(Duration::from_millis(400)).await; - } - if let Some(pid) = project_id + let has_workspace = engine + .call_flow_async("projectNav", json!(["has_workspace"])) + .await + .ok() + .and_then(|v| v.as_bool()) + .unwrap_or(false); + if (is_project_subroute_url(&cur, true) || (in_character && !in_workspace && !has_workspace)) + && let Some(pid) = project_id .map(str::to_string) .or_else(|| project_id_from_url(&cur)) .or_else(|| project_id_from_url(&before_finish)) - { - // Reload `/project/` because exiting a direct `/character/` load leaves an empty shell. - let _ = engine.navigate(&project_workspace_url(&cur, &pid)).await; - tokio::time::sleep(Duration::from_millis(1500)).await; - } + { + // Reload `/project/` because exiting a direct `/character/` load leaves an empty shell. + let _ = engine.navigate(&project_workspace_url(&cur, &pid)).await; + tokio::time::sleep(Duration::from_millis(1500)).await; } let _ = ensure_flow_store(engine).await; } @@ -202,27 +192,18 @@ pub(crate) async fn list_voices( let cid = if let Some(existing_cid) = target_cid { existing_cid } else { - let created = engine - .call_flow_async( - "characterOp", - json!([{ - "action": "create", - "name": "__tmp_voice_probe__", - }]), - ) - .await?; - if created.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to create temporary character for voice lookup: {}", - created - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + let req = json!([{ "action": "create", "name": "__tmp_voice_probe__" }]); + let created = engine.call_flow_async("characterOp", req).await?; + if created.get("ok").and_then(Value::as_bool) != Some(true) { + let err = created + .get("error") + .and_then(Value::as_str) + .unwrap_or("unknown"); + anyhow::bail!("Failed to create temporary character for voice lookup: {err}"); } let tmp_cid = created .get("id") - .and_then(|v| v.as_str()) + .and_then(Value::as_str) .map(str::to_string) .ok_or_else(|| { anyhow::anyhow!("Temporary character creation returned no character ID") diff --git a/src/project.rs b/src/project.rs index e11643e..ddb83d8 100644 --- a/src/project.rs +++ b/src/project.rs @@ -15,15 +15,19 @@ use tokio::time::{Duration, Instant}; use crate::auth::{check_page_auth, check_page_signed_in, is_flow_host_url, redirect_sso_if_about}; use crate::config::{FLOW_URL, has_persisted_session}; -use crate::engine::{ChromeEngine, ENGINE_NAME}; +use crate::engine::{ChromeEngine, ENGINE_NAME, checked_runtime_result}; pub(crate) use crate::project_route::{ - project_id_from_url, project_subroute_url, project_workspace_url, + clean_project_title, collection_id_from_url, is_project_subroute_url, project_id_from_url, + project_subroute_url, project_workspace_url, }; use crate::project_store::{bind_current_store, prepare_project_store_status}; /// Angular error code for a required input that has no value yet. const ANGULAR_REQUIRED_INPUT_ERROR: &str = "NG0950"; +/// Time limit for home-page project grid pagination and confirmation. +const PROJECTS_OP_BUDGET: Duration = Duration::from_secs(45); + /// Parameters for `flow_status`. #[derive(Debug, Clone, Deserialize, JsonSchema)] pub(crate) struct StatusParams { @@ -86,48 +90,35 @@ pub(crate) struct FlowStatus { pub(crate) error: Option, } -/// Navigates back to `/project/` when Chrome is on a non-grid project subroute. -pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Result<()> { - let is_subroute = |url: &str| { - let path = url.split(['?', '#']).next().unwrap_or_default(); - let Some((_, project)) = path.split_once("/project/") else { - return false; - }; - let mut segs = project.trim_end_matches('/').split('/'); - if segs.next().is_none_or(str::is_empty) { - return false; - } - match (segs.next(), segs.next(), segs.next()) { - ( - Some( - "character" | "scene" | "edit" | "chat" | "tool" | "tools" | "create-tool" - | "trash", - ), - _, - _, - ) => true, - (Some("collection"), Some(cid), Some("character")) => !cid.is_empty(), - _ => false, - } - }; +/// Exits child routes under `/project/`, keeping `/collection/` when `allow_collection` is `true`. +async fn ensure_project_route(engine: &ChromeEngine, allow_collection: bool) -> Result<()> { let current = engine.current_url().await?; - if !is_subroute(¤t) { + if !is_project_subroute_url(¤t, allow_collection) { return Ok(()); } let project_id = project_id_from_url(¤t) .ok_or_else(|| anyhow::anyhow!("Cannot identify the active Flow project"))?; let workspace = project_workspace_url(¤t, &project_id); + let target_url = match collection_id_from_url(¤t).filter(|_| allow_collection) { + Some(cid) => project_subroute_url(¤t, &project_id, &format!("collection/{cid}")), + None => workspace.clone(), + }; let returned = |url: &str| { is_flow_host_url(url) - && !is_subroute(url) + && !is_project_subroute_url(url, allow_collection) && project_id_from_url(url).as_deref() == Some(project_id.as_str()) && project_workspace_url(url, &project_id) == workspace }; - let _ = eval_project_nav(engine, "exit_subroute").await; + let nav_action = if allow_collection { + "exit_subroute" + } else { + "exit_to_root" + }; + let _ = eval_project_nav(engine, nav_action).await; if returned(&engine.current_url().await.unwrap_or_default()) { return Ok(()); } - engine.navigate(&workspace).await?; + engine.navigate(&target_url).await?; for _ in 0..10 { if returned(&engine.current_url().await.unwrap_or_default()) { return Ok(()); @@ -137,6 +128,11 @@ pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Resu anyhow::bail!("Cannot return to the active Flow project workspace") } +/// Navigates back to `/project/` or `/project//collection/` from non-grid subroutes. +pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Result<()> { + ensure_project_route(engine, true).await +} + /// Opens a Flow page and verifies access with the active Chrome profile. async fn ensure_signed_in_flow_page(engine: &ChromeEngine) -> Result { engine.ensure_page().await?; @@ -241,11 +237,7 @@ pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowSt .and_then(Value::as_bool) .unwrap_or(false); - let mut project = auth_check - .get("title") - .and_then(|v| v.as_str()) - .map(|s| s.trim().to_string()) - .filter(|s| !s.is_empty()); + let mut project = None; let mut credits = None; let mut assets_count = None; let mut collections_count = None; @@ -255,25 +247,32 @@ pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowSt } if in_project { - let snap = engine + let mut snap = engine .call_flow_js("readStoreSnapshot", json!([])) .await .unwrap_or(Value::Null); - if snap.get("ok").and_then(|v| v.as_bool()) == Some(true) { - if let Some(t) = snap.get("projectTitle").and_then(|v| v.as_str()) - && !t.is_empty() - { - project = Some(t.to_string()); + if !probe { + for _ in 0..8 { + if snap.get("error").and_then(Value::as_str) != Some("store_loading") { + break; + } + tokio::time::sleep(Duration::from_millis(200)).await; + snap = engine + .call_flow_js("readStoreSnapshot", json!([])) + .await + .unwrap_or(Value::Null); } - credits = snap.get("credits").and_then(|v| v.as_i64()); - assets_count = snap - .get("assets") - .and_then(|v| v.as_array()) - .map(|a| a.len()); + } + if snap.get("ok").and_then(Value::as_bool) == Some(true) { + project = clean_project_title(snap.get("projectTitle").and_then(Value::as_str), true); + credits = snap.get("credits").and_then(Value::as_i64); + assets_count = snap.get("assets").and_then(Value::as_array).map(Vec::len); collections_count = snap .get("collections") - .and_then(|v| v.as_array()) - .map(|c| c.len()); + .and_then(Value::as_array) + .map(Vec::len); + } else { + project = clean_project_title(auth_check.get("title").and_then(Value::as_str), false); } } @@ -604,20 +603,33 @@ async fn run_projects_op(engine: &ChromeEngine, req: Value) -> Result { engine.call_flow_async("projectsOp", json!([req])).await } -/// Navigates to the signed-in Google Flow home page. -async fn open_signed_in_home_page(engine: &ChromeEngine) -> Result<()> { +/// Returns the remaining milliseconds before `deadline`, or `None` when expired. +fn remaining_budget_ms(deadline: Instant) -> Option { + let rem = deadline.checked_duration_since(Instant::now())?; + let ms = u64::try_from(rem.as_millis()).unwrap_or(u64::MAX); + (ms > 0).then_some(ms) +} + +/// Navigates to the signed-in Google Flow home page and returns the remaining grid budget in milliseconds. +async fn open_signed_in_home_page(engine: &ChromeEngine) -> Result { + let deadline = Instant::now() + PROJECTS_OP_BUDGET; engine.ensure_page().await?; engine.navigate(FLOW_URL).await?; tokio::time::sleep(Duration::from_millis(900)).await; let _ = ensure_signed_in_flow_page(engine).await?; tokio::time::sleep(Duration::from_millis(500)).await; - Ok(()) + remaining_budget_ms(deadline) + .ok_or_else(|| anyhow::anyhow!("Timed out opening the Google Flow home page")) } /// Lists all existing Flow projects from the Flow home page. async fn list_projects(engine: &ChromeEngine) -> Result { - open_signed_in_home_page(engine).await?; - let res = run_projects_op(engine, json!({ "action": "list" })).await?; + let timeout_ms = open_signed_in_home_page(engine).await?; + let res = run_projects_op( + engine, + json!({ "action": "list", "timeout_ms": timeout_ms }), + ) + .await?; if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { anyhow::bail!( "Failed to list Flow projects: {}", @@ -640,26 +652,56 @@ async fn open_project( if target_id.is_none() { let want = title - .map(|s| s.trim().to_ascii_lowercase()) + .map(|s| s.trim().to_lowercase()) .filter(|s| !s.is_empty()) .ok_or_else(|| anyhow::anyhow!("Provide `id` or `title` to open a project"))?; - let listed = list_projects(engine).await?; + let timeout_ms = open_signed_in_home_page(engine).await?; + let listed = run_projects_op( + engine, + json!({ "action": "list", "title": want, "timeout_ms": timeout_ms }), + ) + .await?; + if listed.get("ok").and_then(Value::as_bool) != Some(true) { + anyhow::bail!( + "Failed to list Flow projects: {}", + listed + .get("error") + .and_then(Value::as_str) + .unwrap_or("unknown") + ); + } + let truncated = listed.get("truncated").and_then(Value::as_bool) == Some(true); let projects = listed .get("projects") - .and_then(|v| v.as_array()) + .and_then(Value::as_array) .cloned() .unwrap_or_default(); - let hit = projects.into_iter().find(|p| { - p.get("title") - .and_then(|v| v.as_str()) - .map(|t| t.trim().to_ascii_lowercase().contains(&want)) - .unwrap_or(false) - }); + let hit = projects + .iter() + .find(|p| { + p.get("title") + .and_then(Value::as_str) + .is_some_and(|t| t.trim().to_lowercase() == want) + }) + .cloned() + .or_else(|| { + projects.into_iter().find(|p| { + p.get("title") + .and_then(Value::as_str) + .is_some_and(|t| t.trim().to_lowercase().contains(&want)) + }) + }); let Some(p) = hit else { + if truncated { + anyhow::bail!( + "Timed out scanning the Google Flow projects grid for title '{}'", + want + ); + } anyhow::bail!("No Google Flow project matches title '{}'", want); }; - target_id = p.get("id").and_then(|v| v.as_str()).map(|s| s.to_string()); - if let Some(t) = p.get("title").and_then(|v| v.as_str()) { + target_id = p.get("id").and_then(Value::as_str).map(str::to_string); + if let Some(t) = p.get("title").and_then(Value::as_str) { matched_title = Some(t.to_string()); } } @@ -672,35 +714,38 @@ async fn open_project( tokio::time::sleep(Duration::from_millis(800)).await; ensure_flow_store(engine).await?; let snap = read_snapshot(engine).await?; + let resolved_title = + clean_project_title(snap.get("projectTitle").and_then(Value::as_str), true) + .or(matched_title); Ok(json!({ "opened": true, "project_id": pid, - "title": snap.get("projectTitle").and_then(|v| v.as_str()).map(|s| s.to_string()).or(matched_title), + "title": resolved_title, "url": engine.current_url().await.unwrap_or(project_url), - "assets_count": snap.get("assets").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0), - "collections_count": snap.get("collections").and_then(|v| v.as_array()).map(|c| c.len()).unwrap_or(0), + "assets_count": snap.get("assets").and_then(Value::as_array).map_or(0, Vec::len), + "collections_count": snap.get("collections").and_then(Value::as_array).map_or(0, Vec::len), })) } -/// Polls project snapshots until `projectTitle` holds `desired` after a short settle delay. +/// Polls project snapshots until a verified `projectTitle` holds `desired` after a settle delay. async fn confirm_project_title(engine: &ChromeEngine, desired: &str) -> Result { - let deadline = Instant::now() + Duration::from_secs(6); - tokio::time::sleep(Duration::from_millis(250)).await; - while Instant::now() < deadline { - if let Ok(snap) = read_snapshot(engine).await + let matches_desired = |snap: &Value| { + snap.get("projectTitleVerified").and_then(Value::as_bool) != Some(false) && snap .get("projectTitle") .and_then(Value::as_str) .map(str::trim) == Some(desired) + }; + let deadline = Instant::now() + Duration::from_secs(6); + tokio::time::sleep(Duration::from_millis(250)).await; + while Instant::now() < deadline { + if let Ok(snap) = read_snapshot(engine).await + && matches_desired(&snap) { tokio::time::sleep(Duration::from_millis(200)).await; if let Ok(settled) = read_snapshot(engine).await - && settled - .get("projectTitle") - .and_then(Value::as_str) - .map(str::trim) - == Some(desired) + && matches_desired(&settled) { return Ok(desired.to_string()); } @@ -713,78 +758,25 @@ async fn confirm_project_title(engine: &ChromeEngine, desired: &str) -> Result, - title: Option<&str>, -) -> usize { - let want_id = id.map(str::trim).filter(|s| !s.is_empty()); - let want_title = title.map(str::trim).filter(|s| !s.is_empty()); - entries - .iter() - .filter(|entry| { - if let Some(wid) = want_id - && entry.get("id").and_then(Value::as_str) == Some(wid) - { - return true; - } - if let Some(wtitle) = want_title - && entry - .get("title") - .and_then(Value::as_str) - .is_some_and(|t| t.trim().eq_ignore_ascii_case(wtitle)) - { - return true; - } - false - }) - .count() -} - -/// Polls home-view project entries until the deleted project is absent from the page. -async fn confirm_project_deleted( - engine: &ChromeEngine, - deleted_id: Option<&str>, - title: Option<&str>, - before_matches: usize, -) -> Result<()> { - let want_id = deleted_id.map(str::trim).filter(|s| !s.is_empty()); - let deadline = Instant::now() + Duration::from_secs(5); - while Instant::now() < deadline { - let listed = run_projects_op(engine, json!({ "action": "list" })).await?; - if listed.get("ok").and_then(Value::as_bool) == Some(true) - && let Some(projects) = listed.get("projects").and_then(Value::as_array) - { - let gone = match want_id { - Some(did) => !projects - .iter() - .any(|p| p.get("id").and_then(Value::as_str) == Some(did)), - None => count_matching_project_entries(projects, None, title) < before_matches, - }; - if gone { - return Ok(()); - } - } - tokio::time::sleep(Duration::from_millis(250)).await; - } - anyhow::bail!("Failed to confirm project deletion on the Flow home page") -} - /// Renames the active project (or the project identified by `id`). async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> Result { let trimmed = title.trim(); if trimmed.is_empty() { anyhow::bail!("New project title must not be empty"); } - if let Some(pid) = id.map(|s| s.trim()).filter(|s| !s.is_empty()) { + if let Some(pid) = id.map(str::trim).filter(|s| !s.is_empty()) { let cur = engine.current_url().await.unwrap_or_default(); if project_id_from_url(&cur).as_deref() != Some(pid) { let _ = open_project(engine, Some(pid), None).await?; + } else { + ensure_project_route(engine, false).await?; + ensure_flow_store(engine).await?; } } else { + ensure_project_route(engine, false).await?; ensure_flow_store(engine).await?; } + ensure_project_route(engine, false).await?; let res = run_projects_op(engine, json!({ "action": "set_title", "title": trimmed })).await?; if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { anyhow::bail!( @@ -809,37 +801,36 @@ async fn delete_project( id: Option<&str>, title: Option<&str>, ) -> Result { - if id.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() - && title.map(|s| s.trim()).filter(|s| !s.is_empty()).is_none() - { + let clean_id = id.map(str::trim).filter(|s| !s.is_empty()); + let clean_title = title.map(str::trim).filter(|s| !s.is_empty()); + if clean_id.is_none() && clean_title.is_none() { anyhow::bail!("Provide `id` or `title` to delete a project"); } - open_signed_in_home_page(engine).await?; + let timeout_ms = open_signed_in_home_page(engine).await?; - let before_list = run_projects_op(engine, json!({ "action": "list" })).await?; - let before_matches = before_list - .get("projects") - .and_then(Value::as_array) - .map_or(1, |projects| { - count_matching_project_entries(projects, id, title) - }); - - let res = run_projects_op( + let response = run_projects_op( engine, - json!({ "action": "delete", "project_id": id, "title": title }), + json!({ + "action": "delete", + "project_id": clean_id, + "title": clean_title, + "timeout_ms": timeout_ms, + }), ) - .await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to delete project: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + .await; + match response { + Ok(res) if res.get("ok").and_then(Value::as_bool) == Some(true) => Ok(res), + Ok(res) if res.get("error").and_then(Value::as_str) == Some("outcome_unknown") => { + checked_runtime_result(res) + } + Ok(res) => { + let err = checked_runtime_result(res) + .err() + .unwrap_or_else(|| anyhow::anyhow!("unknown")); + anyhow::bail!("Failed to delete project: {err:#}"); + } + Err(err) => anyhow::bail!("outcome_unknown (delete project): {err:#}"), } - let deleted_id = res.get("deleted_id").and_then(Value::as_str).or(id); - confirm_project_deleted(engine, deleted_id, title, before_matches).await?; - Ok(res) } /// Dispatches `flow_projects` actions (`list`, `create`, `open`, `rename`, `delete`). diff --git a/src/project_route.rs b/src/project_route.rs index 5ce889c..1c3dbb2 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -7,14 +7,138 @@ use url::Url; use crate::config::FLOW_URL; +/// Extracts the URL path without query or fragment parameters. +fn url_route_path(url: &str) -> String { + if url.contains("://") + && let Ok(parsed) = Url::parse(url) + { + return parsed.path().to_string(); + } + url.split(['?', '#']).next().unwrap_or_default().to_string() +} + /// Extracts the `/project/` segment from a Flow project URL. pub(crate) fn project_id_from_url(url: &str) -> Option { - let path = url.split(['?', '#']).next()?; + let path = url_route_path(url); let (_, project) = path.split_once("/project/")?; let id = project.split('/').next()?.trim(); (!id.is_empty()).then(|| id.to_string()) } +/// Returns `true` when `url` points to a child route under `/project/`. +/// +/// When `allow_collection` is `true`, `/project//collection/` counts as a grid view +/// while deeper paths such as `/project//collection//character` remain subroutes. +pub(crate) fn is_project_subroute_url(url: &str, allow_collection: bool) -> bool { + let path = url_route_path(url); + let Some((_, project)) = path.split_once("/project/") else { + return false; + }; + let mut segs = project.trim_end_matches('/').split('/'); + if segs.next().is_none_or(|id| id.trim().is_empty()) { + return false; + } + match (segs.next(), segs.next(), segs.next()) { + (None, _, _) => false, + (Some("collection"), Some(cid), None) if allow_collection && !cid.trim().is_empty() => { + false + } + (Some(seg), _, _) => !seg.trim().is_empty(), + } +} + +/// Extracts the `` segment when `url` starts with `/project//collection/`. +pub(crate) fn collection_id_from_url(url: &str) -> Option { + let path = url_route_path(url); + let (_, project) = path.split_once("/project/")?; + let mut segs = project.trim_end_matches('/').split('/'); + if segs.next().is_none_or(|id| id.trim().is_empty()) || segs.next() != Some("collection") { + return None; + } + segs.next() + .map(str::trim) + .filter(|cid| !cid.is_empty()) + .map(str::to_string) +} + +/// Returns `true` when `url` points to a `/character` or `/character/` route under `/project/`. +pub(crate) fn is_character_route_url(url: &str) -> bool { + let path = url_route_path(url); + let Some((_, project)) = path.split_once("/project/") else { + return false; + }; + let mut segs = project.trim_end_matches('/').split('/'); + if segs.next().is_none_or(|id| id.trim().is_empty()) { + return false; + } + match (segs.next(), segs.next(), segs.next()) { + (Some("character"), _, _) => true, + (Some("collection"), Some(cid), Some("character")) => !cid.trim().is_empty(), + _ => false, + } +} + +/// Strips one case-insensitive ASCII `prefix` from the start of `text`. +fn strip_ascii_prefix_ci<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + let head = text.get(..prefix.len())?; + head.eq_ignore_ascii_case(prefix) + .then(|| text.get(prefix.len()..)) + .flatten() +} + +/// Strips one case-insensitive ASCII `suffix` from the end of `text`. +fn strip_ascii_suffix_ci<'a>(text: &'a str, suffix: &str) -> Option<&'a str> { + let start = text.len().checked_sub(suffix.len())?; + let tail = text.get(start..)?; + tail.eq_ignore_ascii_case(suffix) + .then(|| text.get(..start)) + .flatten() +} + +/// Removes one leading `"Google Flow - "` or trailing `"- Google Flow"` affix from `text`. +fn strip_google_flow_affix_once(text: &str) -> Option<&str> { + if let Some(rest) = strip_ascii_prefix_ci(text, "google flow") + && rest.starts_with(|ch: char| ch.is_whitespace() || matches!(ch, '-' | '–' | '—' | '|')) + && let Some(stripped) = rest.trim_start().strip_prefix(['-', '–', '—', '|']) + { + return Some(stripped.trim()); + } + if let Some(before) = strip_ascii_suffix_ci(text, "google flow") + && before.ends_with(|ch: char| ch.is_whitespace() || matches!(ch, '-' | '–' | '—' | '|')) + && let Some(stripped) = before.trim_end().strip_suffix(['-', '–', '—', '|']) + { + return Some(stripped.trim()); + } + None +} + +/// Returns a trimmed project title from the store or cleans one `"Google Flow"` wrapper from `document.title`. +pub(crate) fn clean_project_title(raw: Option<&str>, verified: bool) -> Option { + let text = raw?.trim(); + if text.is_empty() { + return None; + } + if verified { + return Some(text.to_string()); + } + if text.eq_ignore_ascii_case("google flow") + || text.eq_ignore_ascii_case("untitled") + || strip_ascii_prefix_ci(text, "google flow - ai creative studio").is_some() + || strip_ascii_prefix_ci(text, "ai creative studio").is_some() + { + return None; + } + let cleaned = strip_google_flow_affix_once(text).unwrap_or(text); + if cleaned.is_empty() + || cleaned.eq_ignore_ascii_case("google flow") + || cleaned.eq_ignore_ascii_case("untitled") + || strip_ascii_prefix_ci(cleaned, "ai creative studio").is_some() + { + return None; + } + Some(cleaned.to_string()) +} + /// Returns `true` when `host` is a Google Flow host (`flow.google.com` or `labs.google`). pub(crate) fn is_flow_origin_host(host: Option<&str>) -> bool { let Some(h) = host else { diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..35f60eb 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -98,8 +98,11 @@ impl<'a> ProjectStoreSession<'a> { /// Prepares the direct store for a status check without changing the page. pub(crate) async fn prepare_project_store_status(engine: &ChromeEngine, project_id: &str) { - if let Some(_guard) = engine.try_lock_project_store() { - let _ = bind_current_store(engine, project_id).await; + if let Some(_guard) = engine.try_lock_project_store() + && let Ok(status) = bind_current_store(engine, project_id).await + && status.get("error").and_then(Value::as_str) == Some("collection_store_not_bound") + { + let _ = engine.call_flow_async("discoverStore", json!([])).await; } } diff --git a/src/service.rs b/src/service.rs index 4b8223b..8291fa5 100644 --- a/src/service.rs +++ b/src/service.rs @@ -373,8 +373,13 @@ impl FlowService { .await?; } anyhow::ensure!(req.files.is_none(), "Use files with flow_assets upload"); - let list = assets::list_assets(&self.engine, &req).await?; - Ok(json!({ "count": list.len(), "assets": list })) + let snap = assets::list_assets_snapshot(&self.engine, &req).await?; + Ok(json!({ + "project_id": snap.project_id, + "project_title": snap.project_title, + "count": snap.assets.len(), + "assets": snap.assets, + })) } /// Renames one or more assets or collections in the active Google Flow project. diff --git a/ts/character_ops.ts b/ts/character_ops.ts index 788055c..30aafbe 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -59,6 +59,13 @@ export async function characterOp(req: CharacterOpRequest): Promise { } if (action === "finish") { + const isCharacterPath = (): boolean => + /\/character(?:\/|$)/.test(location.pathname || ""); + const isSubRoutePath = (): boolean => { + const path = location.pathname || ""; + if (!/\/project\/[^/?#]+\/[^/?#]+/.test(path)) return false; + return !/\/project\/[^/?#]+\/collection\/[^/?#]+\/?$/.test(path); + }; const backBtn = document.querySelector( 'flow-character-edit-header .back-button, button[aria-label="Go back"]', ); @@ -68,14 +75,15 @@ export async function characterOp(req: CharacterOpRequest): Promise { closed = true; } for (let i = 0; i < 25; i++) { - if (!location.pathname.includes("/character/")) break; + if (!isCharacterPath()) break; await delay(100); } - const exited = !location.pathname.includes("/character/"); + const exited = !isCharacterPath(); let inWorkspace = false; - if (exited) { + if (exited && !isSubRoutePath()) { for (let i = 0; i < 20; i++) { if ( + !isSubRoutePath() && document.querySelector("flow-project-page, flow-grid-tile-container") ) { inWorkspace = true; diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 9f32fc5..ec2b4c8 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -347,6 +347,8 @@ export interface ProjectStoreFormat { destroyed: string; /** Project ID signal. */ projectId: string; + /** Project title signal when present on the store. */ + title?: string; /** Service that owns the tile query and writes. */ tilesService: string; /** Query client on the tile service. */ @@ -440,6 +442,7 @@ const NOVEMBER_20_STORE: ProjectStoreFormat = { lifecycle: "Ba", destroyed: "Va", projectId: "ua", + title: "Jk", tilesService: "ma", queryClient: "Wa", dispatcher: "YJ", diff --git a/ts/project_nav.ts b/ts/project_nav.ts index 94db8e5..fd0b76a 100644 --- a/ts/project_nav.ts +++ b/ts/project_nav.ts @@ -88,7 +88,8 @@ export async function projectNav(action: string): Promise { return false; } - if (action === "exit_subroute") { + if (action === "exit_subroute" || action === "exit_to_root") { + const allowCollection = action === "exit_subroute"; const activeProject = (): string | undefined => /\/project\/([^/?#]+)/.exec(location.pathname || "")?.[1]; const pid = activeProject(); @@ -96,40 +97,46 @@ export async function projectNav(action: string): Promise { const workspace = buildProjectUrl(pid); const isOriginalProject = (): boolean => activeProject() === pid && buildProjectUrl(pid) === workspace; - const isSubRoute = (): boolean => - /\/project\/[^/?#]+\/(?:character|scene|edit|chat|tools?|create-tool|trash|collection\/[^/?#]+\/character)(?:\/|$)/.test( - location.pathname || "", - ); + const isCollectionRoot = (path: string): boolean => + /\/project\/[^/?#]+\/collection\/[^/?#]+\/?$/.test(path); + const isSubRoute = (): boolean => { + const path = location.pathname || ""; + if (!/\/project\/[^/?#]+\/[^/?#]+/.test(path)) return false; + return !(allowCollection && isCollectionRoot(path)); + }; if (!isSubRoute()) { return { ok: true, exited: true, method: "already_root" }; } - const direct = Array.from( - document.querySelectorAll( - 'button[aria-label="Done editing scene"], button[aria-label="Done editing"], flow-character-edit-header .back-button, flow-applet-view-header button[aria-label="Back"], button[aria-label="Back button to go to previous page"], flow-navigation-header .back-button:not([aria-label="Home"]), button[aria-label="Go back"]', - ), - ).find(isVisibleEnabled); + const startPath = location.pathname || ""; let clicked = false; - if (direct) { - const inner = - direct.tagName === "BUTTON" ? null : direct.querySelector("button"); - (isVisibleEnabled(inner) ? inner : direct).click(); - clicked = true; - } else { - const hit = Array.from( - document.querySelectorAll('button, [role="button"]'), - ).find((el): el is HTMLElement => { - if (!isVisibleEnabled(el)) return false; - const aria = (el.getAttribute("aria-label") || "").trim(); - const txt = elText(el); - return ( - /^(?:done(?: editing(?: scene)?)?|go back|back button to go to previous page)$/i.test( - aria, - ) || /^(?:done(?: editing(?: scene)?)?)$/i.test(txt) - ); - }); - if (hit) { - hit.click(); + if (!isCollectionRoot(startPath)) { + const direct = Array.from( + document.querySelectorAll( + 'button[aria-label="Done editing scene"], button[aria-label="Done editing"], flow-character-edit-header .back-button, flow-applet-view-header button[aria-label="Back"], button[aria-label="Back button to go to previous page"], flow-navigation-header .back-button:not([aria-label="Home"]), button[aria-label="Go back"]', + ), + ).find(isVisibleEnabled); + if (direct) { + const inner = + direct.tagName === "BUTTON" ? null : direct.querySelector("button"); + (isVisibleEnabled(inner) ? inner : direct).click(); clicked = true; + } else { + const hit = Array.from( + document.querySelectorAll('button, [role="button"]'), + ).find((el): el is HTMLElement => { + if (!isVisibleEnabled(el)) return false; + const aria = (el.getAttribute("aria-label") || "").trim(); + const txt = elText(el); + return ( + /^(?:done(?: editing(?: scene)?)?|go back|back button to go to previous page)$/i.test( + aria, + ) || /^(?:done(?: editing(?: scene)?)?)$/i.test(txt) + ); + }); + if (hit) { + hit.click(); + clicked = true; + } } } if (clicked) { @@ -140,11 +147,20 @@ export async function projectNav(action: string): Promise { clearStore(); return { ok: true, exited: true, method: "ui_done" }; } + if ((location.pathname || "") !== startPath) { + break; + } } } const router = isOriginalProject() ? findRouter() : null; if (router) { - await navigateSpa(router, ["/project", pid]); + const startCid = allowCollection + ? /\/project\/[^/?#]+\/collection\/([^/?#]+)\//.exec(startPath)?.[1] + : undefined; + await navigateSpa( + router, + startCid ? ["/project", pid, "collection", startCid] : ["/project", pid], + ); for (let i = 0; i < 25; i++) { await delay(100); if (!isOriginalProject()) break; diff --git a/ts/project_store.ts b/ts/project_store.ts index 983195b..4bfa731 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -96,11 +96,109 @@ export function currentProjectStore(projectId: string): ProjectStore | null { return active?.projectId === projectId ? active : null; } +/** Returns the query cache object on `store` when available. */ +function storeQueryCache({ service, format }: ProjectStore): object | null { + const tiles = readOwn(service, format.tilesService); + const cache = readOwn(readOwn(tiles, format.queryClient), "queryCache"); + return cache && typeof cache === "object" ? cache : null; +} + +/** Finds an exact `[scope, projectId]` query entry in the query cache of `store`. */ +function findScopedProjectQuery( + store: ProjectStore, + scope: string, +): { state?: { status?: string; fetchStatus?: string; data?: unknown } } | undefined { + const cache = storeQueryCache(store); + const find = readOwn(cache, "find"); + if (typeof find !== "function") return undefined; + return find.call(cache, { queryKey: [scope, store.projectId], exact: true }) as + | { state?: { status?: string; fetchStatus?: string; data?: unknown } } + | undefined; +} + +/** Extracts a title string (or `null` when explicitly empty) from a cached project object. */ +function extractCachedProjectTitle(data: unknown, projectId: string): string | null | undefined { + if (!data || typeof data !== "object") return undefined; + const candidates: unknown[] = [ + data, + readOwn(data, "project"), + readOwn(data, "details"), + readOwn(data, "metadata"), + ]; + for (const item of candidates) { + if (!item || typeof item !== "object") continue; + for (const key of ["title", "projectTitle", "displayName"]) { + const val = readOwn(item, key); + if (typeof val === "string") { + const trimmed = val.trim(); + return trimmed.length > 0 ? trimmed : null; + } + } + const nameVal = readOwn(item, "name"); + if (typeof nameVal === "string" && !nameVal.startsWith("projects/")) { + const trimmed = nameVal.trim(); + return trimmed.length > 0 ? trimmed : null; + } + } + const toJson = readOwn(data, "toJSON"); + if (typeof toJson === "function") { + try { + const raw: unknown = toJson.call(data); + if (Array.isArray(raw) && raw[0] === projectId && Array.isArray(raw[1])) { + const titleCell: unknown = raw[1][0]; + if (titleCell === undefined || titleCell === null) return null; + if (typeof titleCell === "string") { + const trimmed = titleCell.trim(); + return trimmed.length > 0 ? trimmed : null; + } + } + } catch { + // Ignore non-standard toJSON implementations. + } + } + return undefined; +} + +/** Reads the active project title and whether the store or cache verified it. */ +function readProjectTitleState(store: ProjectStore): { title: string | null; verified: boolean } { + if (!isCurrent(store)) return { title: null, verified: false }; + let signalVerified = false; + if (store.format.title) { + const titleSignal = readOwn(store.service, store.format.title); + if (typeof titleSignal === "function") { + try { + const value: unknown = titleSignal.call(store.service); + if (typeof value === "string") { + signalVerified = true; + const trimmed = value.trim(); + if (trimmed.length > 0) return { title: trimmed, verified: true }; + } + } catch { + // Fall through to query cache lookup. + } + } else if (typeof titleSignal === "string") { + signalVerified = true; + const trimmed = titleSignal.trim(); + if (trimmed.length > 0) return { title: trimmed, verified: true }; + } + } + for (const scope of ["PROJECT_DETAILS", "PROJECT"]) { + const entry = findScopedProjectQuery(store, scope); + if (!entry?.state || entry.state.data === undefined) continue; + const cached = extractCachedProjectTitle(entry.state.data, store.projectId); + if (cached !== undefined) { + return { title: cached, verified: true }; + } + } + return { title: null, verified: signalVerified }; +} + /** Finds the query by its full project key. */ -function projectQuery({ projectId, service, format }: ProjectStore): ProjectTileQuery | undefined { +function projectQuery(store: ProjectStore): ProjectTileQuery | undefined { + const { projectId, service, format } = store; const tiles = readOwn(service, format.tilesService); const queryKey = readOwn(tiles, "queryKey"); - const cache = readOwn(readOwn(tiles, format.queryClient), "queryCache"); + const cache = storeQueryCache(store); const find = readOwn(cache, "find"); if (typeof queryKey !== "function" || typeof find !== "function") return undefined; const key: unknown = queryKey.call(tiles, projectId); @@ -114,7 +212,7 @@ function isProjectKey(key: unknown, projectId: string): boolean { return Array.isArray(key) && key.length === 2 && key[0] === "PROJECT_TILES" && key[1] === projectId; } -/** Returns true while the verified tile query of `store` loads initial rows. */ +/** Returns true while the verified tile or metadata query of `store` loads initial data. */ export function isProjectStorePending(store: ProjectStore): boolean { if (!isCurrent(store)) return false; const signalQuery = readOwn(store.service, store.format.tileQuery); @@ -124,7 +222,9 @@ export function isProjectStorePending(store: ProjectStore): boolean { return true; } } - return projectQuery(store)?.state.status === "pending"; + if (projectQuery(store)?.state.status === "pending") return true; + const projectMeta = findScopedProjectQuery(store, "PROJECT")?.state; + return projectMeta?.status === "pending" && projectMeta?.fetchStatus === "fetching"; } /** Indexes a validated tile row array by tile ID. */ @@ -300,6 +400,8 @@ export function installProjectStore(store: ProjectStore, views?: Map isCurrent(store), getTileMap: () => readProjectStore(store), + getTitle: () => readProjectTitleState(store).title, + isTitleVerified: () => readProjectTitleState(store).verified, isReady: () => isCurrent(store) && !isProjectStorePending(store), mutate: (payload) => mutateStore(store, payload), rename: (id, displayName) => @@ -366,6 +468,7 @@ export function projectStoreStatus(projectId: string): ProjectStoreStatus { if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; const store = currentProjectStore(projectId); if (!store) return { ok: false, error: "collection_store_not_bound" }; + runtimeState.routePath = location.pathname; if (isProjectStorePending(store)) { return { ok: false, bound: true, error: "store_loading" }; } diff --git a/ts/projects_grid.ts b/ts/projects_grid.ts new file mode 100644 index 0000000..a1b5397 --- /dev/null +++ b/ts/projects_grid.ts @@ -0,0 +1,782 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Scan Google Flow home-page project cards and sentinel pages within one deadline. + +import { + buildProjectUrl, + readOwn, + resolveLView, + withMapCapture, + type NgContextCarrier, +} from "./angular"; +import { delay } from "./dom"; + +/** Default time limit in milliseconds for pagination and confirmation in `projectsOp`. */ +const DEFAULT_PROJECTS_OP_TIMEOUT_MS = 45_000; + +/** Maximum number of sentinel pages scrolled in one grid scan. */ +const MAX_GRID_PAGES = 50; + +/** Pattern that matches a standard UUID string. */ +const UUID_RE = + /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i; + +/** Selector for icon, button, badge, and hidden elements excluded from card titles. */ +const CARD_ICON_OR_META_SELECTOR = + 'mat-icon, [class*="mat-icon"], .google-symbols, .material-icons, [class*="material-symbols"], .shared-project-icon, .footer-actions, button, [role="button"], flow-project-owner-badge, .comment-count-badge, [aria-hidden="true"]'; + +/** Multi-token Material icon ligatures excluded from unstyled anchor fallbacks. */ +const LINK_ICON_LIGATURE_RE = /^(?:more_vert|chat_bubble)$/i; + +/** Card descriptor captured on the Flow projects grid. */ +export interface ScannedProjectCard { + /** Resolved project UUID if discovered. */ + id: string | null; + /** Visible project card title. */ + title: string | null; + /** Navigable project URL. */ + url: string | null; + /** Underlying card DOM element for delete triggers. */ + _card: HTMLElement; +} + +/** Shared deadline budget and network helpers for one `projectsOp` call. */ +export interface ProjectsGridContext { + /** Returns the remaining milliseconds before the deadline. */ + remainingMs: () => number; + /** Returns true when the deadline has passed. */ + deadlineExpired: () => boolean; + /** Waits up to `ms` without passing the deadline and returns true if time remains. */ + waitBeforeDeadline: (ms: number) => Promise; + /** Collects rendered project cards without scrolling sentinel pages. */ + collectRenderedCards: ( + hoverUnresolved: boolean, + ) => Promise; + /** Scrolls grid sentinel pages until `stopWhen` matches, pages settle, or the deadline expires. */ + scanGridCards: ( + stopWhen?: (items: ScannedProjectCard[]) => boolean, + ) => Promise<{ items: ScannedProjectCard[]; truncated: boolean }>; + /** Runs `triggerFn` and waits for non-telemetry requests within `maxWaitMs` and the deadline. */ + runAndAwaitNetwork: ( + triggerFn: () => Promise, + waitStartMs?: number, + maxWaitMs?: number, + ) => Promise; +} + +/** Returns true when `rawUrl` points to a Google telemetry or error-logging endpoint. */ +function isTelemetryUrl(rawUrl: unknown): boolean { + const s = String(rawUrl || ""); + return ( + s.includes("play.google.com/log") || + s.includes("/jserror") || + s.includes("google-analytics") + ); +} + +/** Searches `obj` recursively up to depth 4 for a project UUID field. */ +function extractIdFromObject( + obj: unknown, + depth: number, + seen: Set, +): string | null { + if (!obj || typeof obj !== "object" || depth > 4 || seen.has(obj)) { + return null; + } + seen.add(obj); + for (const k of ["projectId", "id", "uuid", "workflowId"]) { + const val = readOwn(obj, k); + if (typeof val === "string") { + const hit = UUID_RE.exec(val); + if (hit) return hit[0]; + } + } + if (Array.isArray(obj)) { + for (let i = 0; i < Math.min(obj.length, 25); i++) { + const hit = extractIdFromObject(obj[i], depth + 1, seen); + if (hit) return hit; + } + } else { + for (const k of Object.keys(obj).slice(0, 25)) { + if (k === "parent" || k === "ownerDocument" || k === "window") continue; + const hit = extractIdFromObject(readOwn(obj, k), depth + 1, seen); + if (hit) return hit; + } + } + return null; +} + +/** Extracts text from `el` while skipping icon ligatures, buttons, and metadata badges. */ +function cleanTitleElementText( + el: Element | null, + stripLinkLigatures = false, +): string | null { + if (!el) return null; + if (el instanceof HTMLInputElement) { + const val = el.value.trim(); + return val.length > 0 ? val : null; + } + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, { + acceptNode(node) { + const parent = node.parentElement; + if (!parent) return NodeFilter.FILTER_REJECT; + if ( + parent.matches( + 'mat-icon, [class*="mat-icon"], .google-symbols, .material-icons, [class*="material-symbols"], .shared-project-icon', + ) + ) { + return NodeFilter.FILTER_REJECT; + } + const metaAncestor = + parent !== el ? parent.closest(CARD_ICON_OR_META_SELECTOR) : null; + if (metaAncestor && metaAncestor !== el && el.contains(metaAncestor)) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + }, + }); + const parts: string[] = []; + let current = walker.nextNode(); + while (current) { + const txt = (current.nodeValue || "").replace(/\s+/g, " ").trim(); + if (txt) parts.push(txt); + current = walker.nextNode(); + } + const line = parts + .join(" ") + .split(/\r?\n/) + .map((s) => s.trim()) + .find( + (s) => + s.length > 0 && (!stripLinkLigatures || !LINK_ICON_LIGATURE_RE.test(s)), + ); + return line || null; +} + +/** Reads the clean project title from a `flow-project-card` element. */ +export function readCardTitle(card: HTMLElement): string | null { + const explicit = card.querySelector(".project-title-text"); + if (explicit) { + return cleanTitleElementText(explicit); + } + const fallback = card.querySelector( + '.project-title-label, [data-testid="project-title"], h2, h3, h4', + ); + return fallback ? cleanTitleElementText(fallback) : null; +} + +/** Reads the clean project title from an anchor element or its parent card. */ +function readLinkTitle(link: HTMLElement): string | null { + const parentCard = link.closest("flow-project-card"); + if (parentCard instanceof HTMLElement) { + return readCardTitle(parentCard); + } + const explicit = link.querySelector( + ".project-title-text, .project-title-label, h2, h3, h4", + ); + return cleanTitleElementText(explicit ?? link, !explicit); +} + +/** Collects scrollable ancestor elements of `target` plus `document.scrollingElement`. */ +function findScrollContainers(target: HTMLElement): HTMLElement[] { + const containers: HTMLElement[] = []; + let cur: HTMLElement | null = target.parentElement; + while (cur) { + const style = window.getComputedStyle(cur); + if ( + cur.scrollHeight > cur.clientHeight || + /^(?:auto|scroll|overlay)$/i.test(style.overflowY) + ) { + containers.push(cur); + } + cur = cur.parentElement; + } + if ( + document.scrollingElement instanceof HTMLElement && + !containers.includes(document.scrollingElement) + ) { + containers.push(document.scrollingElement); + } + return containers; +} + +/** Inspects the Angular infinite-query state on `grid` and optionally triggers `fetchNextPage`. */ +function probeInfiniteGridQuery( + grid: Element | null, + seenMaps: ReadonlySet>, + shouldNudge: boolean, +): { hasNext: boolean | null; fetching: boolean } { + if (!grid) return { hasNext: null, fetching: false }; + let lv: unknown[] | null = resolveLView(grid); + if (!Array.isArray(lv)) { + const ng = (grid as NgContextCarrier).__ngContext__; + if (typeof ng === "number") { + for (const sm of seenMaps) { + try { + const candLv = sm.get(ng); + if (Array.isArray(candLv)) { + lv = candLv; + break; + } + } catch { + // Ignore map read error. + } + } + } + } + if (!Array.isArray(lv)) return { hasNext: null, fetching: false }; + const seen = new Set(); + const state: { + componentHasNext: boolean | null; + componentFetching: boolean; + queryFound: boolean; + queryHasNext: boolean; + queryFetching: boolean; + } = { + componentHasNext: null, + componentFetching: false, + queryFound: false, + queryHasNext: false, + queryFetching: false, + }; + const queriesToNudge: Array<{ fetchNext: () => unknown; target: object }> = + []; + + const inspect = (cand: unknown, depth: number): void => { + if (!cand || typeof cand !== "object" || depth > 2 || seen.has(cand)) { + return; + } + seen.add(cand); + const hasNext = readOwn(cand, "hasNextPage"); + const fetchNext = readOwn(cand, "fetchNextPage"); + const isFetchingNext = readOwn(cand, "isFetchingNextPage"); + if (typeof hasNext === "function" && typeof fetchNext === "function") { + state.queryFound = true; + const nextAvailable = Boolean(hasNext.call(cand)); + if (nextAvailable) { + state.queryHasNext = true; + } + const isFetchingAny = readOwn(cand, "isFetching"); + const fetching = + (typeof isFetchingNext === "function" && + Boolean(isFetchingNext.call(cand))) || + (typeof isFetchingAny === "function" && + Boolean(isFetchingAny.call(cand))); + if (fetching) { + state.queryFetching = true; + } else if (nextAvailable && shouldNudge) { + const dataFn = readOwn(cand, "data"); + const isActive = + typeof dataFn !== "function" || dataFn.call(cand) !== undefined; + if (isActive) { + queriesToNudge.push({ + fetchNext: fetchNext as () => unknown, + target: cand, + }); + } + } + return; + } + if ( + typeof hasNext === "function" && + typeof isFetchingNext === "function" && + state.componentHasNext === null + ) { + state.componentHasNext = Boolean(hasNext.call(cand)); + state.componentFetching = Boolean(isFetchingNext.call(cand)); + } + if (!Array.isArray(cand) && !(cand instanceof Node)) { + for (const k of Object.keys(cand).slice(0, 25)) { + inspect(readOwn(cand, k), depth + 1); + } + } + }; + for (const slot of lv) { + inspect(slot, 0); + } + const hasNext = + state.componentHasNext !== null + ? state.componentHasNext + : state.queryFound + ? state.queryHasNext + : null; + let fetching = state.componentFetching || state.queryFetching; + if (hasNext === true && shouldNudge && !fetching && queriesToNudge.length > 0) { + for (const q of queriesToNudge) { + void Promise.resolve(q.fetchNext.call(q.target)).catch(() => null); + } + fetching = true; + } + return { hasNext, fetching }; +} + +/** Observes non-telemetry `fetch` and `XMLHttpRequest` promises while `fn` runs. */ +async function withNetworkObserver( + onRequest: (done: Promise) => void, + fn: () => Promise, +): Promise { + const origFetch = window.fetch; + const origXhrOpen = XMLHttpRequest.prototype.open; + const origXhrSend = XMLHttpRequest.prototype.send; + const xhrUrls = new WeakMap(); + + try { + window.fetch = function ( + this: Window, + input: RequestInfo | URL, + init?: RequestInit, + ): Promise { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url || ""; + const p = origFetch.call(this, input, init); + if (!isTelemetryUrl(url)) { + onRequest(p.then(() => undefined, () => undefined)); + } + return p; + }; + XMLHttpRequest.prototype.open = function ( + this: XMLHttpRequest, + method: string, + url: string | URL, + asyncFlag = true, + username?: string | null, + password?: string | null, + ): void { + xhrUrls.set(this, String(url || "")); + if (arguments.length <= 2) { + origXhrOpen.call(this, method, url, true); + } else { + origXhrOpen.call( + this, + method, + url, + Boolean(asyncFlag), + username ?? null, + password ?? null, + ); + } + }; + XMLHttpRequest.prototype.send = function ( + this: XMLHttpRequest, + body?: Document | XMLHttpRequestBodyInit | null, + ): void { + if (!isTelemetryUrl(xhrUrls.get(this))) { + onRequest( + new Promise((res) => { + this.addEventListener("loadend", () => res(), { once: true }); + }), + ); + } + origXhrSend.call(this, body); + }; + return await fn(); + } finally { + window.fetch = origFetch; + XMLHttpRequest.prototype.open = origXhrOpen; + XMLHttpRequest.prototype.send = origXhrSend; + } +} + +/** Creates deadline-bounded grid scanning and network helpers for one `projectsOp` call. */ +export function createProjectsGridContext( + rawTimeoutMs?: number, +): ProjectsGridContext { + const timeoutMs = + typeof rawTimeoutMs === "number" && Number.isFinite(rawTimeoutMs) + ? Math.max(0, rawTimeoutMs) + : DEFAULT_PROJECTS_OP_TIMEOUT_MS; + const deadline = globalThis.performance.now() + timeoutMs; + const remainingMs = (): number => deadline - globalThis.performance.now(); + const deadlineExpired = (): boolean => remainingMs() <= 0; + const waitBeforeDeadline = async (ms: number): Promise => { + const rem = remainingMs(); + if (rem <= 0) return false; + await delay(Math.min(ms, rem)); + return !deadlineExpired(); + }; + + const seenMaps = new Set>(); + const hoveredCards = new WeakSet(); + + const extractCardId = (card: HTMLElement): string | null => { + const link = card.querySelector('a[href*="/project/"]'); + const href = link?.getAttribute("href") || ""; + const m = /\/project\/([^/?#]+)/.exec(href); + if (m) return m[1]; + for (const attr of card.getAttributeNames()) { + const val = card.getAttribute(attr) || ""; + const um = UUID_RE.exec(val); + if (um) return um[0]; + } + const ng = (card as NgContextCarrier).__ngContext__; + if (Array.isArray(ng)) { + return extractIdFromObject(ng, 0, new Set()); + } + if (typeof ng === "number") { + for (const sm of seenMaps) { + try { + const lv = sm.get(ng); + if (Array.isArray(lv)) { + const pid = extractIdFromObject(lv, 0, new Set()); + if (pid) return pid; + } + } catch { + // Ignore map read error. + } + } + } + return null; + }; + + const collectRenderedCards = async ( + hoverUnresolved: boolean, + ): Promise => { + const cards = Array.from(document.querySelectorAll("flow-project-card")); + if (hoverUnresolved && !deadlineExpired()) { + const unresolved = cards.filter( + (card): card is HTMLElement => + card instanceof HTMLElement && + !hoveredCards.has(card) && + !extractCardId(card) && + typeof (card as NgContextCarrier).__ngContext__ === "number", + ); + if (unresolved.length > 0) { + await withMapCapture( + (map, _key, _value, write) => { + if (!write) seenMaps.add(map); + }, + async () => { + for (const card of unresolved) { + hoveredCards.add(card); + const r = card.getBoundingClientRect(); + card.dispatchEvent( + new PointerEvent("pointerenter", { + bubbles: false, + clientX: r.left + 12, + clientY: r.top + 12, + }), + ); + card.dispatchEvent( + new MouseEvent("mouseenter", { + bubbles: false, + clientX: r.left + 12, + clientY: r.top + 12, + }), + ); + } + await waitBeforeDeadline(80); + }, + ); + } + } + + const byId = new Map(); + for (let idx = 0; idx < cards.length; idx++) { + const card = cards[idx]; + if (!(card instanceof HTMLElement)) continue; + const pid = extractCardId(card); + const title = readCardTitle(card); + const key = pid || `card:${idx}`; + if (!byId.has(key)) { + byId.set(key, { + id: pid, + title, + url: pid ? buildProjectUrl(pid) : null, + _card: card, + }); + } + } + + for (const a of document.querySelectorAll('a[href*="/project/"]')) { + if (!(a instanceof HTMLElement)) continue; + const href = a.getAttribute("href") || ""; + const m = /\/project\/([^/?#]+)/.exec(href); + if (!m) continue; + const pid = m[1]; + if (!byId.has(pid)) { + const cardParent = a.closest("flow-project-card"); + byId.set(pid, { + id: pid, + title: readLinkTitle(a), + url: new URL(href, location.origin).href, + _card: cardParent instanceof HTMLElement ? cardParent : a, + }); + } + } + return Array.from(byId.values()); + }; + + const scanGridCards = async ( + stopWhen?: (items: ScannedProjectCard[]) => boolean, + ): Promise<{ items: ScannedProjectCard[]; truncated: boolean }> => { + let activeRequests = 0; + return await withNetworkObserver( + (done) => { + activeRequests++; + void done.finally(() => { + activeRequests = Math.max(0, activeRequests - 1); + }); + }, + async () => { + let lastCount = -1; + let stableTicks = 0; + let unmountedTicks = 0; + while (!deadlineExpired()) { + const loading = Boolean( + document.querySelector( + "flow-loading-page, .projects-loading-container", + ), + ); + const hasCreateBtn = Boolean( + document.querySelector( + "button.projects-grid-new-project-button, button.new-project-button", + ), + ); + const hasGridShell = Boolean( + document.querySelector("flow-projects-grid"), + ); + const cnt = document.querySelectorAll( + 'flow-project-card, a[href*="/project/"]', + ).length; + if (cnt > 0 && cnt === lastCount && !loading) { + stableTicks++; + if (stableTicks >= 3) break; + } else if ( + !loading && + hasCreateBtn && + cnt === 0 && + activeRequests === 0 + ) { + stableTicks++; + if (stableTicks >= 3) break; + } else { + lastCount = cnt; + stableTicks = 0; + if ( + !loading && + !hasGridShell && + !hasCreateBtn && + cnt === 0 && + activeRequests === 0 + ) { + unmountedTicks++; + if (unmountedTicks >= 20) break; + } else { + unmountedTicks = 0; + } + } + if (!(await waitBeforeDeadline(150))) break; + } + + let items = await collectRenderedCards(true); + if (stopWhen?.(items)) { + return { items, truncated: false }; + } + const isGridIncomplete = (): boolean => { + const grid = document.querySelector("flow-projects-grid"); + const sentinel = + grid?.querySelector(".load-more-sentinel") ?? + document.querySelector("flow-projects-grid .load-more-sentinel"); + if (sentinel instanceof HTMLElement) { + return ( + probeInfiniteGridQuery(grid, seenMaps, false).hasNext !== false + ); + } + const loading = Boolean( + document.querySelector( + "flow-loading-page, .projects-loading-container", + ), + ); + const hasReadyShell = Boolean( + grid || + document.querySelector( + "button.projects-grid-new-project-button, button.new-project-button", + ), + ); + return loading || activeRequests > 0 || (!hasReadyShell && items.length === 0); + }; + if (deadlineExpired()) { + return { + items, + truncated: isGridIncomplete(), + }; + } + + const countEntries = (): number => + document.querySelectorAll('flow-project-card, a[href*="/project/"]') + .length; + let pagesLoaded = 0; + let retryAttempt = 0; + let truncated = false; + + while (pagesLoaded < MAX_GRID_PAGES) { + const grid = document.querySelector("flow-projects-grid"); + const sentinel = + grid?.querySelector(".load-more-sentinel") ?? + document.querySelector("flow-projects-grid .load-more-sentinel"); + if (!(sentinel instanceof HTMLElement)) { + truncated = false; + break; + } + if (probeInfiniteGridQuery(grid, seenMaps, false).hasNext === false) { + truncated = false; + break; + } + if (deadlineExpired()) { + truncated = true; + break; + } + + const beforeCount = countEntries(); + const scrollers = findScrollContainers(sentinel); + if (retryAttempt > 0) { + for (const scroller of scrollers) { + scroller.scrollTop = Math.max( + 0, + scroller.scrollTop - Math.max(240, window.innerHeight), + ); + scroller.dispatchEvent(new Event("scroll", { bubbles: true })); + } + if (!(await waitBeforeDeadline(40))) { + truncated = true; + break; + } + } + sentinel.scrollIntoView({ block: "end", inline: "nearest" }); + for (const scroller of scrollers) { + scroller.scrollTop = scroller.scrollHeight; + scroller.dispatchEvent(new Event("scroll", { bubbles: true })); + } + window.dispatchEvent(new Event("scroll")); + + let advanced = false; + let nudgedQuery = false; + let reachedEnd = false; + const idleTickLimit = retryAttempt === 0 ? 15 : 25; + for (let tick = 0; !deadlineExpired(); tick++) { + if (!(await waitBeforeDeadline(100))) { + truncated = true; + break; + } + if (countEntries() > beforeCount) { + advanced = true; + break; + } + const liveSentinel = + grid?.querySelector(".load-more-sentinel") ?? + document.querySelector("flow-projects-grid .load-more-sentinel"); + if (!liveSentinel) { + reachedEnd = true; + break; + } + const shouldNudge = !nudgedQuery && tick >= 3; + if (shouldNudge) nudgedQuery = true; + const queryState = probeInfiniteGridQuery( + grid, + seenMaps, + shouldNudge, + ); + if (queryState.hasNext === false) { + reachedEnd = true; + break; + } + const spinnerBusy = Boolean( + liveSentinel.querySelector('mat-spinner, [role="progressbar"]') ?? + grid?.querySelector('mat-spinner, [role="progressbar"]'), + ); + const busy = + spinnerBusy || queryState.fetching || activeRequests > 0; + if (!busy && tick >= idleTickLimit) { + break; + } + } + + if (advanced) { + await waitBeforeDeadline(60); + } + items = await collectRenderedCards(true); + if (stopWhen?.(items)) { + return { items, truncated: false }; + } + if (truncated || deadlineExpired()) { + truncated = true; + break; + } + if (reachedEnd) { + truncated = false; + break; + } + if (advanced && countEntries() > beforeCount) { + pagesLoaded++; + retryAttempt = 0; + if (pagesLoaded >= MAX_GRID_PAGES) { + const stillHasSentinel = Boolean( + document.querySelector( + "flow-projects-grid .load-more-sentinel", + ), + ); + if ( + stillHasSentinel && + probeInfiniteGridQuery(grid, seenMaps, false).hasNext !== false + ) { + truncated = true; + } + } + } else { + retryAttempt++; + if ( + !(await waitBeforeDeadline(Math.min(400, 150 * retryAttempt))) + ) { + truncated = true; + break; + } + } + } + + return { items, truncated }; + }, + ); + }; + + const runAndAwaitNetwork = async ( + triggerFn: () => Promise, + waitStartMs = 350, + maxWaitMs = 8000, + ): Promise => { + const inFlight: Array> = []; + return await withNetworkObserver( + (done) => { + inFlight.push(done); + }, + async () => { + await triggerFn(); + await waitBeforeDeadline(waitStartMs); + if (inFlight.length === 0) { + return true; + } + const limitMs = Math.min(maxWaitMs, Math.max(0, remainingMs())); + if (limitMs <= 0) { + return false; + } + return await Promise.race([ + Promise.allSettled(inFlight).then(() => true), + delay(limitMs).then(() => false), + ]); + }, + ); + }; + + return { + remainingMs, + deadlineExpired, + waitBeforeDeadline, + collectRenderedCards, + scanGridCards, + runAndAwaitNetwork, + }; +} diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..0c2f92e 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -3,329 +3,112 @@ // List, rename, and delete Google Flow projects from the Flow UI. -import { - buildProjectUrl, - readOwn, - resolveLView, - withMapCapture, - type NgContextCarrier, -} from "./angular"; +import { readOwn, resolveLView } from "./angular"; import { delay, elText, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; +import { + createProjectsGridContext, + readCardTitle, + type ScannedProjectCard, +} from "./projects_grid"; import type { ProjectsOpRequest } from "./types"; -/** Internal card descriptor captured on the Flow projects grid. */ -interface ScannedProjectCard { - /** Resolved project UUID if discovered. */ - id: string | null; - /** Visible project card title. */ - title: string | null; - /** Navigable project URL. */ - url: string | null; - /** Underlying card DOM element for delete triggers. */ - _card: HTMLElement; -} - /** Lists, renames, or deletes Google Flow projects on home or workspace pages. */ export async function projectsOp(req: ProjectsOpRequest): Promise { - const UUID_RE = - /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i; - - function extractIdFromObject( - obj: unknown, - depth: number, - seen: Set, - ): string | null { - if (!obj || typeof obj !== "object" || depth > 4 || seen.has(obj)) { - return null; - } - seen.add(obj); - for (const k of ["projectId", "id", "uuid", "workflowId"]) { - const val = readOwn(obj, k); - if (typeof val === "string") { - const hit = UUID_RE.exec(val); - if (hit) return hit[0]; - } - } - if (Array.isArray(obj)) { - for (let i = 0; i < Math.min(obj.length, 25); i++) { - const hit = extractIdFromObject(obj[i], depth + 1, seen); - if (hit) return hit; - } - } else { - for (const k of Object.keys(obj).slice(0, 25)) { - if (k === "parent" || k === "ownerDocument" || k === "window") continue; - const hit = extractIdFromObject(readOwn(obj, k), depth + 1, seen); - if (hit) return hit; - } - } - return null; - } - - async function scanCards(): Promise { - let lastCount = -1; - let stableTicks = 0; - for (let i = 0; i < 60; i++) { - const loading = Boolean( - document.querySelector( - "flow-loading-page, .projects-loading-container", - ), - ); - const hasCreateBtn = Boolean( - document.querySelector( - "button.projects-grid-new-project-button, button.new-project-button", - ), - ); - const cnt = document.querySelectorAll( - 'flow-project-card, a[href*="/project/"]', - ).length; - if (cnt > 0 && cnt === lastCount) { - stableTicks++; - if (stableTicks >= 3) break; - } else if (!loading && hasCreateBtn && cnt === 0) { - stableTicks++; - if (stableTicks >= 3) break; - } else { - lastCount = cnt; - stableTicks = 0; - } - await delay(150); - } - - const seenMaps = new Set>(); - await withMapCapture((map, _key, _value, write) => { - if (!write) seenMaps.add(map); - }, async () => { - const cards = Array.from(document.querySelectorAll("flow-project-card")); - for (const card of cards.slice(0, 50)) { - const r = card.getBoundingClientRect(); - card.dispatchEvent( - new PointerEvent("pointerenter", { - bubbles: false, - clientX: r.left + 12, - clientY: r.top + 12, - }), - ); - card.dispatchEvent( - new MouseEvent("mouseenter", { - bubbles: false, - clientX: r.left + 12, - clientY: r.top + 12, - }), - ); - } - await delay(80); - }); - - const byId = new Map(); - const cards = Array.from(document.querySelectorAll("flow-project-card")); - for (const card of cards) { - if (!(card instanceof HTMLElement)) continue; - const link = card.querySelector('a[href*="/project/"]'); - const href = link?.getAttribute("href") || ""; - let pid: string | null = null; - const m = /\/project\/([^/?#]+)/.exec(href); - if (m) pid = m[1]; - if (!pid) { - for (const attr of card.getAttributeNames()) { - const val = card.getAttribute(attr) || ""; - const um = UUID_RE.exec(val); - if (um) { - pid = um[0]; - break; - } - } - } - if (!pid) { - const ng = (card as NgContextCarrier).__ngContext__; - if (Array.isArray(ng)) { - pid = extractIdFromObject(ng, 0, new Set()); - } else if (typeof ng === "number") { - for (const sm of seenMaps) { - try { - const lv = sm.get(ng); - if (Array.isArray(lv)) { - pid = extractIdFromObject(lv, 0, new Set()); - if (pid) break; - } - } catch { - // Ignore map read error. - } - } - } - } - const titleNode = - card.querySelector( - 'input[aria-label="Editable text"], [class*="title"], h2, h3, h4', - ) || card; - const rawText = ( - (titleNode instanceof HTMLInputElement ? titleNode.value : "") || - elText(titleNode) || - "" - ) - .split(/\r?\n/) - .map((s) => s.trim()) - .find((s) => s.length > 0 && !/^(?:more_vert|delete)$/i.test(s)); - const key = pid || `card:${rawText || byId.size}`; - if (!byId.has(key)) { - byId.set(key, { - id: pid, - title: rawText || null, - url: pid ? buildProjectUrl(pid) : null, - _card: card, - }); - } - } - - for (const a of document.querySelectorAll('a[href*="/project/"]')) { - if (!(a instanceof HTMLElement)) continue; - const href = a.getAttribute("href") || ""; - const m = /\/project\/([^/?#]+)/.exec(href); - if (!m) continue; - const pid = m[1]; - if (!byId.has(pid)) { - const title = elText(a) - .split(/\r?\n/) - .map((s) => s.trim()) - .find(Boolean); - const cardParent = a.closest("flow-project-card"); - byId.set(pid, { - id: pid, - title: title || null, - url: new URL(href, location.origin).href, - _card: cardParent instanceof HTMLElement ? cardParent : a, - }); - } - } - - return Array.from(byId.values()); - } - - async function runAndAwaitNetwork( - triggerFn: () => Promise, - waitStartMs = 350, - maxWaitMs = 8000, - ): Promise { - const origFetch = window.fetch; - const origXhrOpen = XMLHttpRequest.prototype.open; - const origXhrSend = XMLHttpRequest.prototype.send; - const xhrUrls = new WeakMap(); - const inFlight: Array> = []; - const isTelemetry = (rawUrl: unknown): boolean => { - const s = String(rawUrl || ""); - return ( - s.includes("play.google.com/log") || - s.includes("/jserror") || - s.includes("google-analytics") - ); - }; - - try { - window.fetch = function ( - this: Window, - input: RequestInfo | URL, - init?: RequestInit, - ): Promise { - const url = - typeof input === "string" - ? input - : input instanceof URL - ? input.href - : input.url || ""; - const p = origFetch.call(this, input, init); - if (!isTelemetry(url)) { - inFlight.push(p.catch(() => null)); - } - return p; - }; - XMLHttpRequest.prototype.open = function ( - this: XMLHttpRequest, - method: string, - url: string | URL, - asyncFlag = true, - username?: string | null, - password?: string | null, - ): void { - xhrUrls.set(this, String(url || "")); - if (arguments.length <= 2) { - origXhrOpen.call(this, method, url, true); - } else { - origXhrOpen.call( - this, - method, - url, - Boolean(asyncFlag), - username ?? null, - password ?? null, - ); - } - }; - XMLHttpRequest.prototype.send = function ( - this: XMLHttpRequest, - body?: Document | XMLHttpRequestBodyInit | null, - ): void { - if (!isTelemetry(xhrUrls.get(this))) { - inFlight.push( - new Promise((res) => { - this.addEventListener("loadend", () => res(), { once: true }); - }), - ); - } - origXhrSend.call(this, body); - }; - - await triggerFn(); - await delay(waitStartMs); - if (inFlight.length > 0) { - await Promise.race([Promise.allSettled(inFlight), delay(maxWaitMs)]); - } - } finally { - window.fetch = origFetch; - XMLHttpRequest.prototype.open = origXhrOpen; - XMLHttpRequest.prototype.send = origXhrSend; - } - } + const { + deadlineExpired, + waitBeforeDeadline, + collectRenderedCards, + scanGridCards, + runAndAwaitNetwork, + } = createProjectsGridContext(req?.timeout_ms); const action = String(req?.action || "list").toLowerCase(); if (action === "list") { - const items = await scanCards(); + const wantId = req?.project_id ? String(req.project_id).trim() : ""; + const wantTitle = req?.title ? String(req.title).trim().toLowerCase() : ""; + const stopWhen = + wantId || wantTitle + ? (cards: ScannedProjectCard[]): boolean => + cards.some((p) => { + if (wantId) return p.id === wantId; + return ( + Boolean(wantTitle) && + Boolean(p.title) && + (p.title || "").trim().toLowerCase() === wantTitle + ); + }) + : undefined; + const { items, truncated } = await scanGridCards(stopWhen); return { ok: true, projects: items.map(({ id, title, url }) => ({ id, title, url })), + ...(truncated ? { truncated: true } : {}), }; } if (action === "set_title") { const desired = String(req?.title || "").trim(); if (!desired) return { ok: false, error: "empty_title" }; + const isSubroutePath = (): boolean => + /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); + const isProjectRootPath = (): boolean => + /\/project\/[^/?#]+\/?$/.test(location.pathname || ""); + if (isSubroutePath()) { + return { ok: false, error: "project_subroute_active" }; + } + if (!isProjectRootPath()) { + return { ok: false, error: "not_in_project_root" }; + } + const headerHostSelector = + "flow-project-page flow-tile-view-header flow-navigation-header flow-editable-text"; + const headerInputSelector = `${headerHostSelector} input.editable-text-input, ${headerHostSelector} input[aria-label="Editable text"], ${headerHostSelector} input`; let input: HTMLInputElement | null = null; - for (let i = 0; i < 40; i++) { - const cand = document.querySelector( - 'flow-editable-text input.editable-text-input, input[aria-label="Editable text"], .editable-text-input', + for (let i = 0; i < 40 && !deadlineExpired(); i++) { + if (isSubroutePath()) { + return { ok: false, error: "project_subroute_active" }; + } + if (!isProjectRootPath()) { + return { ok: false, error: "not_in_project_root" }; + } + const candidates = Array.from( + document.querySelectorAll(headerInputSelector), + ); + const found = candidates.find( + (cand): cand is HTMLInputElement => + cand instanceof HTMLInputElement && + !cand.closest( + "flow-project-sidenav-container, mat-sidenav, aside", + ) && + cand.getClientRects().length > 0, ); - if (cand instanceof HTMLInputElement && cand.getClientRects().length > 0) { - input = cand; + if (found) { + input = found; break; } - await delay(100); + if (!(await waitBeforeDeadline(100))) break; } if (!input) return { ok: false, error: "project_title_input_not_found" }; const titleInput = input; - const host = titleInput.closest("flow-editable-text"); + const host = titleInput.closest(headerHostSelector); + if (!host) return { ok: false, error: "project_title_input_not_found" }; if ((titleInput.value || "").trim() === desired) { return { ok: true, title: desired }; } + let abortedOnRoute = false; await runAndAwaitNetwork( async () => { + if (isSubroutePath() || !isProjectRootPath()) { + abortedOnRoute = true; + return; + } titleInput.focus(); titleInput.dispatchEvent(new FocusEvent("focus", { bubbles: false })); await delay(50); setNativeValue(titleInput, desired); await delay(50); - const doneBtn = (host || document).querySelector( - 'button[aria-label="Done"]', - ); + const doneBtn = host.querySelector('button[aria-label="Done"]'); if (doneBtn instanceof HTMLElement) { doneBtn.click(); } else { @@ -342,9 +125,8 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } await delay(60); if ( - host && - (host.querySelector(".editable-text-container.editing") || - (titleInput.value || "").trim() !== desired) + host.querySelector(".editable-text-container.editing") || + (titleInput.value || "").trim() !== desired ) { try { const lv = resolveLView(host); @@ -375,18 +157,24 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { 400, 6000, ); + if (abortedOnRoute || isSubroutePath()) { + return { ok: false, error: "project_subroute_active" }; + } + if (!isProjectRootPath()) { + return { ok: false, error: "not_in_project_root" }; + } const isSettledTitle = (): boolean => - !host?.querySelector(".editable-text-container.editing") && + !host.querySelector(".editable-text-container.editing") && (titleInput.value || "").trim() === desired; - await delay(300); - for (let i = 0; i < 30; i++) { + await waitBeforeDeadline(300); + for (let i = 0; i < 30 && !deadlineExpired(); i++) { if (isSettledTitle()) { - await delay(200); + if (!(await waitBeforeDeadline(200))) break; if (isSettledTitle()) { return { ok: true, confirmed: true, title: desired }; } } - await delay(150); + if (!(await waitBeforeDeadline(150))) break; } return { ok: false, error: "project_title_not_confirmed" }; } @@ -394,27 +182,36 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { if (action === "delete") { const targetId = req?.project_id ? String(req.project_id).trim() : ""; const targetTitle = req?.title ? String(req.title).trim() : ""; + if (!targetId && !targetTitle) { + return { ok: false, error: "missing_project_target" }; + } + const targetTitleLower = targetTitle.toLowerCase(); const matchesTarget = (p: ScannedProjectCard): boolean => { - if (targetId && p.id === targetId) return true; - if ( - targetTitle && - p.title && - p.title.toLowerCase() === targetTitle.toLowerCase() - ) { - return true; - } - return false; + if (targetId) return p.id === targetId; + return ( + Boolean(targetTitleLower) && + Boolean(p.title) && + (p.title || "").trim().toLowerCase() === targetTitleLower + ); }; - const items = await scanCards(); + const { items, truncated } = await scanGridCards((cards) => + cards.some(matchesTarget), + ); const hit = items.find(matchesTarget); if (!hit || !hit._card) { - return { ok: false, error: "project_card_not_found" }; + return { + ok: false, + error: truncated ? "project_scan_timeout" : "project_card_not_found", + }; } - const beforeMatches = items.filter(matchesTarget).length; + const beforeRenderedMatches = items.filter(matchesTarget).length; const deletedId = hit.id; + const deletedTitle = hit.title; const card = hit._card; card.scrollIntoView({ block: "center" }); - await delay(100); + if (!(await waitBeforeDeadline(100))) { + return { ok: false, error: "project_scan_timeout" }; + } const r = card.getBoundingClientRect(); card.dispatchEvent( new PointerEvent("pointerenter", { @@ -430,7 +227,9 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { clientY: r.top + r.height / 2, }), ); - await delay(150); + if (!(await waitBeforeDeadline(150))) { + return { ok: false, error: "project_scan_timeout" }; + } let delBtn = card.querySelector('button[aria-label="Delete project"]'); if (!delBtn) { @@ -439,7 +238,12 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { ); if (moreBtn instanceof HTMLElement) { moreBtn.click(); - await delay(200); + if (!(await waitBeforeDeadline(200))) { + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + return { ok: false, error: "project_scan_timeout" }; + } delBtn = document.querySelector( 'button[aria-label="Delete project"], [role="menuitem"][aria-label*="Delete" i]', @@ -453,11 +257,17 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { if (!(delBtn instanceof HTMLElement)) { return { ok: false, error: "delete_project_button_not_found" }; } + if (deadlineExpired()) { + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + return { ok: false, error: "project_scan_timeout" }; + } delBtn.click(); let confirmBtn: HTMLElement | null = null; - for (let i = 0; i < 25; i++) { - await delay(100); + for (let i = 0; i < 25 && !deadlineExpired(); i++) { + if (!(await waitBeforeDeadline(100))) break; const dialogs = Array.from( document.querySelectorAll( '[role="dialog"], .mat-mdc-dialog-container, .cdk-overlay-pane', @@ -477,42 +287,76 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } if (confirmBtn) break; } - if (!confirmBtn) { - return { ok: false, error: "delete_confirm_button_not_found" }; + if (!confirmBtn || deadlineExpired()) { + const timedOut = deadlineExpired(); + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), + ); + return { + ok: false, + error: timedOut + ? "project_scan_timeout" + : "delete_confirm_button_not_found", + }; } + const finalConfirm = confirmBtn; - await runAndAwaitNetwork( + const outcomeUnknown = (): Record => ({ + ok: false, + error: "outcome_unknown", + stage: "confirm_project_delete", + project_id: deletedId, + title: deletedTitle, + }); + const networkSettled = await runAndAwaitNetwork( async () => { finalConfirm.click(); }, 350, 8000, ); - - for (let i = 0; i < 60; i++) { - if (!document.body.contains(card)) break; - await delay(100); + if (!networkSettled && deadlineExpired()) { + return outcomeUnknown(); } - const entryRemoved = (entries: ScannedProjectCard[]): boolean => - deletedId - ? !entries.some((p) => p.id === deletedId) - : entries.filter(matchesTarget).length < beforeMatches; - await delay(300); - for (let i = 0; i < 20; i++) { - if (entryRemoved(await scanCards())) { - await delay(250); - if (entryRemoved(await scanCards())) { + + const hasDeleteDialog = (): boolean => + Array.from( + document.querySelectorAll( + '[role="dialog"], .mat-mdc-dialog-container, .cdk-overlay-pane', + ), + ).some((dlg) => /delete this project/i.test(dlg.textContent || "")); + const entryRemoved = (entries: ScannedProjectCard[]): boolean => { + if (hasDeleteDialog()) return false; + if (deletedId) { + return !entries.some((p) => p.id === deletedId); + } + if (!document.body.contains(card)) { + return true; + } + const liveTitle = (readCardTitle(card) || "").trim().toLowerCase(); + return ( + liveTitle !== targetTitleLower && + entries.filter(matchesTarget).length < beforeRenderedMatches + ); + }; + + while (!deadlineExpired()) { + const current = await collectRenderedCards(true); + if (entryRemoved(current)) { + if (!(await waitBeforeDeadline(200))) break; + const recheck = await collectRenderedCards(true); + if (entryRemoved(recheck)) { return { ok: true, confirmed: true, - deleted_id: hit.id, - deleted_title: hit.title, + deleted_id: deletedId, + deleted_title: deletedTitle, }; } } - await delay(250); + if (!(await waitBeforeDeadline(150))) break; } - return { ok: false, error: "delete_card_still_present" }; + return outcomeUnknown(); } return { ok: false, error: `unknown_project_action:${action}` }; diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index ff0c6fb..719b27c 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -201,10 +201,11 @@ export function readStoreSnapshot(): StoreSnapshotResult { clearStore(); return { ok: false, error: "project_mismatch" }; } - if (!helper.isCurrent() || runtimeState.routePath !== location.pathname) { + if (!helper.isCurrent()) { clearStore(); return { ok: false, error: "route_changed" }; } + runtimeState.routePath = location.pathname; if (!helper.isReady()) { return { ok: false, error: "store_loading" }; } @@ -214,20 +215,55 @@ export function readStoreSnapshot(): StoreSnapshotResult { } const { assets, collections } = readStoreTiles(tileMap); - 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(); - const projectTitle = rawTitle || docTitle || null; + const rawStoreTitle = + typeof helper.getTitle === "function" ? helper.getTitle() : null; + const storeTitle = + typeof rawStoreTitle === "string" && rawStoreTitle.trim().length > 0 + ? rawStoreTitle.trim() + : null; + const titleVerified = + storeTitle !== null || Boolean(helper.isTitleVerified?.()); + let projectTitle: string | null = storeTitle; + if (!titleVerified) { + const rawDocTitle = (document.title || "").trim(); + if ( + !rawDocTitle || + /^(?:google\s+flow|untitled)$/i.test(rawDocTitle) || + /^(?:google\s+flow\s*[-–—|]\s*)?ai\s+creative\s+studio\b/i.test( + rawDocTitle, + ) + ) { + projectTitle = null; + } else { + const prefixStripped = rawDocTitle.replace( + /^google\s+flow\s*[-–—|]\s*/i, + "", + ); + const cleaned = ( + prefixStripped !== rawDocTitle + ? prefixStripped + : rawDocTitle.replace(/\s*[-–—|]\s*google\s+flow\s*$/i, "") + ).trim(); + projectTitle = + cleaned && + !/^(?:google\s+flow|untitled)$/i.test(cleaned) && + !/^ai\s+creative\s+studio\b/i.test(cleaned) + ? cleaned + : null; + } + } const credits = readMappedCredits() ?? readDomAccountCredits(); - return { ok: true, projectId, projectTitle, credits, assets, collections }; + return { + ok: true, + projectId, + projectTitle, + projectTitleVerified: titleVerified, + credits, + assets, + collections, + }; } /** Reads asset and collection details from the tile map. */ diff --git a/ts/types.ts b/ts/types.ts index 6e1c59b..69bc4b5 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -272,6 +272,10 @@ export interface FlowStoreHandle { isCurrent: () => boolean; /** Returns the current project tile map if available. */ getTileMap: () => Map | null | undefined; + /** Returns the project title from the store signal or query cache when available. */ + getTitle: () => string | null; + /** Returns true when a store title signal or project cache backs `getTitle`. */ + isTitleVerified?: () => boolean; /** Returns true when pending store fetches have settled. */ isReady: () => boolean; /** Dispatches a store mutation payload and waits for completion. */ @@ -579,6 +583,7 @@ export type StoreSnapshotResult = ok: true; projectId: string | null; projectTitle: string | null; + projectTitleVerified?: boolean; credits: number | null; assets: SnapshotAssetItem[]; collections: SnapshotCollectionItem[]; @@ -588,10 +593,12 @@ export type StoreSnapshotResult = export interface ProjectsOpRequest { /** Operation (`list`, `set_title`, or `delete`). */ action?: string; - /** Desired project title for `set_title` or target match for `delete`. */ + /** Desired project title for `set_title` or target match for `list` and `delete`. */ title?: string; - /** Project identifier for `delete`. */ + /** Project identifier for `list` and `delete`. */ project_id?: string; + /** Time limit in milliseconds for grid pagination and confirmation. */ + timeout_ms?: number; } /** Extra options for `assetOps("rename", ...)`. */