From 8d75fd37e29819b92f1e8e0734571f7530a06832 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:35:43 +0000 Subject: [PATCH 1/3] fix(flow): mutate project titles in store and read query caches - Map project metadata mutator and home grid queries in VERIFIED_BUILDS - Dispatch set_project_title in ProjectStore and verify the Jk signal - Route project create and rename through ProjectStoreSession - Exit collection subroutes on workspace return and keep file uploads - Reject subroutes in fallback set_title and scope inputs to the header - Read project titles from Jk and QueryClient caches without DOM inputs - Paginate owned and shared grid queries and strip mat-icon ligatures --- src/assets.rs | 26 +- src/characters.rs | 23 +- src/project.rs | 198 ++++---- src/project_route.rs | 143 ++++++ src/service.rs | 9 +- src/upload.rs | 2 +- ts/frontend_builds.ts | 73 ++- ts/frontend_compatibility.ts | 2 + ts/index.ts | 2 + ts/project_metadata.ts | 857 +++++++++++++++++++++++++++++++++++ ts/project_nav.ts | 4 +- ts/project_store.ts | 14 +- ts/projects_ops.ts | 284 +++++++++--- ts/read_store_snapshot.ts | 12 +- ts/types.ts | 6 + 15 files changed, 1445 insertions(+), 210 deletions(-) create mode 100644 ts/project_metadata.ts diff --git a/src/assets.rs b/src/assets.rs index c3c8975..fc47972 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -252,10 +252,8 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result Result> { +) -> Result { let snap = read_project_assets(engine).await?; let all = snap.assets; @@ -396,7 +394,19 @@ pub(crate) async fn list_assets( filtered.truncate(lim); } } - Ok(filtered) + Ok(ProjectAssetsSnapshot { + project_id: snap.project_id, + project_title: snap.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..35e52bb 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -20,7 +20,7 @@ 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_project_subroute_url}; use crate::project_store::ProjectStoreSession; use crate::queue::{ProgressCallback, SceneParams}; use crate::voices::{ @@ -140,31 +140,30 @@ pub(crate) async fn open_character_editor( /// Exits the character editor back to `/project/` and clears stale Angular store handles. pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Option<&str>) { - let before_finish = engine.current_url().await.unwrap_or_default(); - let in_character = before_finish.contains("/character/"); - let finish_res = engine + let before = engine.current_url().await.unwrap_or_default(); + let in_character = before.contains("/character"); + let in_workspace = engine .call_flow_async("characterOp", json!([{ "action": "finish" }])) - .await; - let in_workspace = finish_res - .as_ref() + .await .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 cur = engine.current_url().await.unwrap_or_default(); - if (in_character && !in_workspace) || cur.contains("/character/") { - if !cur.contains("/character/") { + if (in_character && !in_workspace) || cur.contains("/character") { + if !cur.contains("/character") { tokio::time::sleep(Duration::from_millis(400)).await; } if let Some(pid) = project_id .map(str::to_string) .or_else(|| project_id_from_url(&cur)) - .or_else(|| project_id_from_url(&before_finish)) + .or_else(|| project_id_from_url(&before)) { // 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; } + } else if is_project_subroute_url(&cur) { + let _ = ensure_project_workspace_root(engine).await; } let _ = ensure_flow_store(engine).await; } diff --git a/src/project.rs b/src/project.rs index e11643e..c431017 100644 --- a/src/project.rs +++ b/src/project.rs @@ -17,9 +17,10 @@ use crate::auth::{check_page_auth, check_page_signed_in, is_flow_host_url, redir use crate::config::{FLOW_URL, has_persisted_session}; use crate::engine::{ChromeEngine, ENGINE_NAME}; pub(crate) use crate::project_route::{ - project_id_from_url, project_subroute_url, project_workspace_url, + clean_flow_page_title, ensure_project_workspace_root, project_id_from_url, + project_subroute_url, project_workspace_url, }; -use crate::project_store::{bind_current_store, prepare_project_store_status}; +use crate::project_store::{ProjectStoreSession, 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"; @@ -86,57 +87,6 @@ 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, - } - }; - let current = engine.current_url().await?; - if !is_subroute(¤t) { - 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 returned = |url: &str| { - is_flow_host_url(url) - && !is_subroute(url) - && 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; - if returned(&engine.current_url().await.unwrap_or_default()) { - return Ok(()); - } - engine.navigate(&workspace).await?; - for _ in 0..10 { - if returned(&engine.current_url().await.unwrap_or_default()) { - return Ok(()); - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - anyhow::bail!("Cannot return to the active Flow project workspace") -} - /// 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 +191,19 @@ 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 = if in_project { + auth_check + .get("title") + .and_then(Value::as_str) + .and_then(clean_flow_page_title) + } else { + auth_check + .get("title") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; let mut credits = None; let mut assets_count = None; let mut collections_count = None; @@ -260,11 +218,10 @@ pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowSt .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()); - } + project = snap + .get("projectTitle") + .and_then(Value::as_str) + .and_then(clean_flow_page_title); credits = snap.get("credits").and_then(|v| v.as_i64()); assets_count = snap .get("assets") @@ -571,23 +528,7 @@ pub(crate) async fn create_project(engine: &ChromeEngine, title: Option<&str>) - if project_id.is_some() { let _ = ensure_flow_store(engine).await; if let Some(desired_title) = final_title.as_deref() { - let res = run_projects_op( - engine, - json!({ - "action": "set_title", - "title": desired_title, - }), - ) - .await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to set project title: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - final_title = Some(confirm_project_title(engine, desired_title).await?); + final_title = Some(apply_project_title(engine, desired_title).await?); } } Ok(json!({ @@ -617,6 +558,7 @@ async fn open_signed_in_home_page(engine: &ChromeEngine) -> Result<()> { /// 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 _ = engine.bind_angular_views("flow-projects-grid").await; let res = run_projects_op(engine, json!({ "action": "list" })).await?; if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { anyhow::bail!( @@ -649,12 +591,21 @@ async fn open_project( .and_then(|v| v.as_array()) .cloned() .unwrap_or_default(); - let hit = projects.into_iter().find(|p| { - p.get("title") - .and_then(|v| v.as_str()) - .map(|t| t.trim().to_ascii_lowercase().contains(&want)) - .unwrap_or(false) - }); + let hit = projects + .iter() + .find(|p| { + p.get("title") + .and_then(Value::as_str) + .is_some_and(|t| t.trim().eq_ignore_ascii_case(&want)) + }) + .or_else(|| { + projects.iter().find(|p| { + p.get("title") + .and_then(Value::as_str) + .is_some_and(|t| t.trim().to_ascii_lowercase().contains(&want)) + }) + }) + .cloned(); let Some(p) = hit else { anyhow::bail!("No Google Flow project matches title '{}'", want); }; @@ -675,13 +626,64 @@ async fn open_project( 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": snap + .get("projectTitle") + .and_then(Value::as_str) + .and_then(clean_flow_page_title) + .or(matched_title), "url": engine.current_url().await.unwrap_or(project_url), "assets_count": snap.get("assets").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0), "collections_count": snap.get("collections").and_then(|v| v.as_array()).map(|c| c.len()).unwrap_or(0), })) } +/// Applies `desired` through `ProjectStoreSession` on verified builds, or header DOM on legacy builds. +async fn apply_project_title(engine: &ChromeEngine, desired: &str) -> Result { + let verified = engine + .call_flow_js("probeBuild", json!([])) + .await + .ok() + .and_then(|v| v.get("checks").and_then(Value::as_array).cloned()) + .is_some_and(|checks| { + checks.iter().any(|c| { + c.get("name").and_then(Value::as_str) == Some("verified_build") + && c.get("ok").and_then(Value::as_bool) == Some(true) + }) + }); + if verified { + let session = ProjectStoreSession::open(engine).await?; + let outcome = session + .call( + "projectMetadataOp", + json!({ "action": "set_title", "title": desired }), + Some("set project title"), + ) + .await; + match outcome { + Ok(res) => { + return Ok(res + .get("title") + .and_then(Value::as_str) + .unwrap_or(desired) + .to_string()); + } + Err(err) if !err.to_string().starts_with("legacy_project_title") => return Err(err), + Err(_) => {} + } + } + ensure_project_workspace_root(engine).await?; + let res = run_projects_op(engine, json!({ "action": "set_title", "title": desired })).await?; + if res.get("ok").and_then(Value::as_bool) != Some(true) { + anyhow::bail!( + "Failed to set project title: {}", + res.get("error") + .and_then(Value::as_str) + .unwrap_or("unknown") + ); + } + confirm_project_title(engine, desired).await +} + /// Polls project snapshots until `projectTitle` holds `desired` after a short settle delay. async fn confirm_project_title(engine: &ChromeEngine, desired: &str) -> Result { let deadline = Instant::now() + Duration::from_secs(6); @@ -777,28 +779,19 @@ async fn rename_project(engine: &ChromeEngine, id: Option<&str>, title: &str) -> if trimmed.is_empty() { anyhow::bail!("New project title must not be empty"); } - if let Some(pid) = id.map(|s| s.trim()).filter(|s| !s.is_empty()) { - let cur = engine.current_url().await.unwrap_or_default(); + let cur = engine.current_url().await.unwrap_or_default(); + if let Some(pid) = id.map(str::trim).filter(|s| !s.is_empty()) { if project_id_from_url(&cur).as_deref() != Some(pid) { let _ = open_project(engine, Some(pid), None).await?; } - } else { + } else if project_id_from_url(&cur).is_none() { ensure_flow_store(engine).await?; } - let res = run_projects_op(engine, json!({ "action": "set_title", "title": trimmed })).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to rename project: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); - } - let confirmed_title = confirm_project_title(engine, trimmed).await?; - let cur = engine.current_url().await.unwrap_or_default(); + let confirmed_title = apply_project_title(engine, trimmed).await?; + let active_url = engine.current_url().await.unwrap_or_default(); Ok(json!({ "ok": true, - "project_id": project_id_from_url(&cur), + "project_id": project_id_from_url(&active_url), "title": confirmed_title, })) } @@ -815,6 +808,7 @@ async fn delete_project( anyhow::bail!("Provide `id` or `title` to delete a project"); } open_signed_in_home_page(engine).await?; + let _ = engine.bind_angular_views("flow-projects-grid").await; let before_list = run_projects_op(engine, json!({ "action": "list" })).await?; let before_matches = before_list diff --git a/src/project_route.rs b/src/project_route.rs index 5ce889c..6329e98 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -3,9 +3,14 @@ //! Parse and build Google Flow workspace routes. +use anyhow::Result; +use serde_json::json; +use tokio::time::Duration; use url::Url; +use crate::auth::is_flow_host_url; use crate::config::FLOW_URL; +use crate::engine::ChromeEngine; /// Extracts the `/project/` segment from a Flow project URL. pub(crate) fn project_id_from_url(url: &str) -> Option { @@ -15,6 +20,144 @@ pub(crate) fn project_id_from_url(url: &str) -> Option { (!id.is_empty()).then(|| id.to_string()) } +/// Returns `true` when `url` points to any `/project//...` subroute (including `/collection/`). +pub(crate) fn is_project_subroute_url(url: &str) -> bool { + 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; + } + segs.next().is_some_and(|seg| !seg.is_empty()) +} + +/// Returns `true` when `url` points to a non-upload `/project//...` subroute while keeping `/collection/`. +pub(crate) fn is_upload_subroute_url(url: &str) -> bool { + 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()) { + (None, _, _) => false, + (Some("collection"), Some(cid), None) => cid.is_empty(), + (Some(seg), _, _) => !seg.is_empty(), + } +} + +/// Strips `"Google Flow - "` wrappers and rejects generic application or trash document titles. +pub(crate) fn clean_flow_page_title(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + let lower = trimmed.to_ascii_lowercase(); + if let Some(after) = lower.strip_prefix("google flow") + && let Some(rest) = after + .trim_start() + .strip_prefix(['-', '–', '—', '|', ':']) + .map(str::trim_start) + && rest.starts_with("ai creative studio") + { + return None; + } + let without_prefix = strip_flow_title_prefix(trimmed); + let stripped = strip_flow_title_suffix(without_prefix).trim(); + if stripped.is_empty() + || stripped.eq_ignore_ascii_case("google flow") + || stripped.eq_ignore_ascii_case("flow") + || stripped.eq_ignore_ascii_case("trash") + { + return None; + } + Some(stripped.to_string()) +} + +/// Strips a leading `"Google Flow - "` or `"Flow - "` prefix from `value`. +fn strip_flow_title_prefix(value: &str) -> &str { + for prefix in ["google flow", "flow"] { + if value.len() >= prefix.len() + && value + .get(..prefix.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) + && let Some(tail) = value.get(prefix.len()..) + { + let rest = tail.trim_start(); + if let Some(after_sep) = rest.strip_prefix(['-', '–', '—', '|', ':']) { + return after_sep.trim_start(); + } + } + } + value +} + +/// Strips a trailing `"- Google Flow"` or `"- Flow"` suffix from `value`. +fn strip_flow_title_suffix(value: &str) -> &str { + for suffix in ["google flow", "flow"] { + if value.len() >= suffix.len() + && value + .get(value.len() - suffix.len()..) + .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix)) + && let Some(head) = value.get(..value.len() - suffix.len()) + { + let before = head.trim_end(); + if let Some(before_sep) = before.strip_suffix(['-', '–', '—', '|', ':']) { + return before_sep.trim_end(); + } + } + } + value +} + +/// Exits active project subroutes matched by `is_subroute` back to `/project/`. +async fn exit_matching_subroute( + engine: &ChromeEngine, + is_subroute: fn(&str) -> bool, +) -> Result<()> { + let current = engine.current_url().await?; + if !is_subroute(¤t) { + 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 returned = |url: &str| { + is_flow_host_url(url) + && !is_subroute(url) + && project_id_from_url(url).as_deref() == Some(project_id.as_str()) + && project_workspace_url(url, &project_id) == workspace + }; + let _ = engine + .call_flow_async("projectNav", json!(["exit_subroute"])) + .await; + if returned(&engine.current_url().await.unwrap_or_default()) { + return Ok(()); + } + engine.navigate(&workspace).await?; + for _ in 0..10 { + if returned(&engine.current_url().await.unwrap_or_default()) { + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + anyhow::bail!("Cannot return to the active Flow project workspace") +} + +/// Navigates back to `/project/` when Chrome is on any `/project//...` subroute. +pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Result<()> { + exit_matching_subroute(engine, is_project_subroute_url).await +} + +/// Navigates back to `/project/` from editor subroutes while keeping `/project//collection/`. +pub(crate) async fn ensure_project_upload_route(engine: &ChromeEngine) -> Result<()> { + exit_matching_subroute(engine, is_upload_subroute_url).await +} + /// 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/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/src/upload.rs b/src/upload.rs index 896bde0..46e8da7 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -46,7 +46,7 @@ pub(crate) async fn local_upload_paths(files: &[String], label: &str) -> Result< /// Uploads files to the pinned project and returns the saved assets. pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { - crate::project::ensure_project_workspace_root(engine).await?; + crate::project_route::ensure_project_upload_route(engine).await?; let project = ProjectStoreSession::open(engine).await?; let has_video = files.iter().any(|file| { mime_guess::from_path(file) diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index c10c146..8c6f3ac 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -410,7 +410,7 @@ const NOVEMBER_20_STORE: ProjectStoreFormat = { tileQuery: "rs", mutator: "ld", errorStream: "Da", - componentSlots: ["fh", "ha", "Ew", "la", "ka"], + componentSlots: ["fh", "ha", "Ew", "la", "ka", "mc", "na", "EP"], lContextView: "zp", scene: { clips: "Uc", history: "Cg" }, mutations: { @@ -718,6 +718,8 @@ interface FrontendBuildFields { characterCreate?: CharacterCreateFormat; /** Native fields of editable project titles. */ projectTitle?: ProjectTitleFormat; + /** Native fields for project metadata mutations, title signals, and grid queries. */ + projectMetadata?: ProjectMetadataFormat; } /** A verified build with full or pre-Agent operation coverage. */ @@ -794,6 +796,44 @@ export interface ProjectTitleFormat { stateSignal: string; } +/** Native fields for project metadata mutations, title caches, and home grid queries. */ +export interface ProjectMetadataFormat { + /** Injected metadata service property on the project store. */ + metadataService: string; + /** Exported metadata service class on the Angular frontend namespace. */ + metadataServiceClass: string; + /** Signal query property on the project store that loads `PROJECT` metadata. */ + metadataQuery: string; + /** Project metadata mutation runner property on the project store. */ + metadataMutator: string; + /** Async project metadata mutation dispatcher method on the metadata service. */ + metadataDispatcher: string; + /** Computed signal method on the project store returning the project title. */ + titleSignal: string; + /** Title field name inside a `set_project_title` mutation payload. */ + titleField: string; + /** Exported query-key builder function for `PROJECT` cache entries. */ + projectKey: string; + /** Getter method on a `PROJECT` protobuf message returning its metadata block. */ + projectInfoGetter: string; + /** Getter method on the `PROJECT` metadata block returning the title string. */ + projectTitleGetter: string; + /** Exported `flow-projects-grid` component class on the Angular frontend namespace. */ + gridClass: string; + /** Infinite query and page items property for `PROJECTS` on `flow-projects-grid`. */ + ownedQuery: string; + /** Infinite query and page items property for `SHARED_PROJECTS` on `flow-projects-grid`. */ + sharedQuery: string; + /** Getter method returning the project ID on a card or details protobuf message. */ + cardIdGetter: string; + /** Getter method returning the card metadata protobuf message. */ + cardMetadataGetter: string; + /** Getter method returning the project title string on card metadata. */ + cardTitleGetter: string; + /** Getter method returning the inner project protobuf on a shared project card entry. */ + sharedProjectGetter: string; +} + /** Character editor and query fields used to read the saved voice. */ export interface VoiceConfirmationFormat { /** Exported character editor class. */ @@ -887,6 +927,25 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ collections: ["tb", "ub"], completions: ["De", "ve"], created: ["NH"], }, projectTitle: { saveEmitter: "HSa", stateSignal: "state" }, + projectMetadata: { + metadataService: "Rb", + metadataServiceClass: "$N", + metadataQuery: "Ag", + metadataMutator: "Lc", + metadataDispatcher: "YJ", + titleSignal: "Jk", + titleField: "Sg", + projectKey: "pM", + projectInfoGetter: "AE", + projectTitleGetter: "tI", + gridClass: "Y7", + ownedQuery: "Id", + sharedQuery: "xs", + cardIdGetter: "Ub", + cardMetadataGetter: "getMetadata", + cardTitleGetter: "Qd", + sharedProjectGetter: "Jn", + }, operations: { collection_write: { tileId: "Xc", tileChange: "mf", moveTarget: "mk", moveTiles: "yb", deleteCollections: "mu", @@ -951,6 +1010,13 @@ export function withMutationAliases(payload: Record): Record unknown; + /** Returns true while initial data has not resolved yet. */ + isPending?: () => boolean; + /** Returns true while any fetch is in flight. */ + isFetching?: () => boolean; + /** Returns true while the query displays placeholder data. */ + isPlaceholderData?: () => boolean; + /** Returns true when the query encountered an error. */ + isError?: () => boolean; + /** Returns true when another page token is available. */ + hasNextPage?: () => boolean; + /** Returns true while `fetchNextPage()` is in flight. */ + isFetchingNextPage?: () => boolean; + /** Returns true when the most recent next-page fetch failed. */ + isFetchNextPageError?: () => boolean; + /** Requests the next page from the backend. */ + fetchNextPage?: () => Promise; +} + +/** Calls a zero-argument boolean method on `target` when present. */ +function callBool(target: unknown, key: string): boolean { + const fn = readOwn(target, key); + if (typeof fn === "function") { + try { + return Boolean(fn.call(target)); + } catch { + return false; + } + } + return fn === true; +} + +/** Calls a zero-argument getter method on `target` when present. */ +function callGetter(target: unknown, key: string): unknown { + const fn = readOwn(target, key); + if (typeof fn !== "function") return undefined; + try { + return fn.call(target); + } catch { + return undefined; + } +} + +/** Strips `"Google Flow - "` and `"- Google Flow"` wrappers and generic app titles. */ +export function cleanFlowDocumentTitle(raw: string | null | undefined): string | null { + const trimmed = typeof raw === "string" ? raw.trim() : ""; + if (!trimmed) return null; + if (/^google\s+flow\s*[-–|:—]\s*ai\s+creative\s+studio\b/i.test(trimmed)) { + return null; + } + const stripped = trimmed + .replace(/^(?:google\s+)?flow\s*[-–|:—]\s*/i, "") + .replace(/\s*[-–|:—]\s*(?:google\s+)?flow$/i, "") + .trim(); + if (!stripped || /^(?:google\s+flow|flow|trash)$/i.test(stripped)) { + return null; + } + return stripped; +} + +/** Checks the project metadata service, mutator, and title signal for `probeStore`. */ +export function projectMetadataChecks(buildLabel: string | null): StoreProbeCheck[] { + const format = frontendBuild(buildLabel)?.projectMetadata; + if (!format) return []; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const serviceClass = readOwn(namespace, format.metadataServiceClass); + const pid = projectInRoute(); + const store = pid ? currentProjectStore(pid) : null; + const metadataService = store ? readOwn(store.service, format.metadataService) : null; + const mutator = store + ? resolveAsyncMutator(store.service, readOwn(store.service, format.metadataMutator)) + : null; + const dispatcher = readOwn(metadataService, format.metadataDispatcher); + const titleSignal = store ? readOwn(store.service, format.titleSignal) : null; + return [ + { + name: "metadata_service", + ok: typeof serviceClass === "function" && typeof dispatcher === "function", + detail: typeof dispatcher === "function" ? "present" : "missing", + }, + { + name: "metadata_mutator", + ok: typeof mutator === "function" || typeof dispatcher === "function", + detail: typeof mutator === "function" ? "present" : "missing", + }, + { + name: "project_title_signal", + ok: typeof titleSignal === "function", + detail: typeof titleSignal === "function" ? "present" : "missing", + }, + ]; +} + +/** Resolves the active `ProjectStore` for `projectId` from bound state or captured `LView`s. */ +function resolveStoreForProject(projectId: string | null): ProjectStore | null { + if (!projectId) return null; + const direct = currentProjectStore(projectId); + if (direct) return direct; + const seen = new Set(); + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + const hits = findProjectStoreInView(view, projectId, seen); + if (hits.length > 0) return hits[0]; + } + return null; +} + +/** Checks whether `candidate` exposes `QueryClient.queryCache.find`. */ +function asQueryClient(candidate: unknown): QueryClient | undefined { + if (!candidate || typeof candidate !== "object") return undefined; + const client = candidate as QueryClient; + return typeof client.queryCache?.find === "function" ? client : undefined; +} + +/** Resolves the shared `QueryClient` from `store`, Angular views, or page components. */ +function findSharedQueryClient(store: ProjectStore | null): QueryClient | undefined { + if (store) { + const tilesClient = asQueryClient( + readOwn(readOwn(store.service, store.format.tilesService), store.format.queryClient), + ); + if (tilesClient) return tilesClient; + const metaFormat = activeProjectMetadataFormat(); + if (metaFormat) { + const metaService = readOwn(store.service, metaFormat.metadataService); + const metaClient = asQueryClient(readOwn(metaService, store.format.queryClient)); + if (metaClient) return metaClient; + } + } + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + if (!isLiveLView(view)) continue; + for (const slot of view) { + if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + const direct = asQueryClient(slot); + if (direct) return direct; + if (typeof (slot as AgentInjector).get === "function") { + const resolved = resolveQueryClient(slot as AgentInjector); + if (resolved) return resolved; + } + const viaPage = resolveQueryClient({}, slot as Record); + if (viaPage) return viaPage; + } + } + return undefined; +} + +/** Extracts a non-empty string from a JSPB message getter or raw JSPB array slot. */ +function readProtoString( + msg: unknown, + getterName: string | undefined, + fallbackFieldIndex?: number, +): string | null { + if (!msg || typeof msg !== "object") return null; + if (getterName) { + const val = callGetter(msg, getterName); + if (typeof val === "string") return val.trim() || null; + } + for (const candidate of Object.values(msg as Record)) { + if (Array.isArray(candidate) && fallbackFieldIndex !== undefined) { + const raw = candidate[fallbackFieldIndex - 1] ?? candidate[fallbackFieldIndex]; + if (typeof raw === "string" && raw.trim()) return raw.trim(); + } + } + return null; +} + +/** Extracts a project title from a cached `PROJECT` or `PROJECT_DETAILS` message. */ +function extractProjectDetailTitle( + data: unknown, + format?: ProjectMetadataFormat, +): string | null { + if (!data || typeof data !== "object") return null; + const infoGetter = format?.projectInfoGetter ?? "AE"; + const titleGetter = format?.projectTitleGetter ?? "tI"; + const metaGetter = format?.cardMetadataGetter ?? "getMetadata"; + const cardTitleGetter = format?.cardTitleGetter ?? "Qd"; + + const info = callGetter(data, infoGetter); + const fromInfo = readProtoString(info, titleGetter, 1); + if (fromInfo !== null) return fromInfo; + + const meta = callGetter(data, metaGetter); + const fromMeta = readProtoString(meta, cardTitleGetter, 1); + if (fromMeta !== null) return fromMeta; + + const directTitle = readOwn(data, "title") ?? readOwn(data, "displayName"); + if (typeof directTitle === "string" && directTitle.trim()) { + return directTitle.trim(); + } + return null; +} + +/** Extracts `{ id, title }` from one owned or shared project card protobuf entry. */ +function extractCardProtobuf( + rawEntry: unknown, + isShared: boolean, + format?: ProjectMetadataFormat, +): { id: string; title: string | null } | null { + if (!rawEntry || typeof rawEntry !== "object") return null; + const sharedGetter = format?.sharedProjectGetter ?? "Jn"; + const idGetter = format?.cardIdGetter ?? "Ub"; + const metaGetter = format?.cardMetadataGetter ?? "getMetadata"; + const titleGetter = format?.cardTitleGetter ?? "Qd"; + + const unwrapped = isShared ? (callGetter(rawEntry, sharedGetter) ?? rawEntry) : rawEntry; + if (!unwrapped || typeof unwrapped !== "object") return null; + + const id = + readProtoString(unwrapped, idGetter, 1) ?? + (typeof readOwn(unwrapped, "projectId") === "string" + ? String(readOwn(unwrapped, "projectId")).trim() + : null) ?? + (typeof readOwn(unwrapped, "id") === "string" + ? String(readOwn(unwrapped, "id")).trim() + : null); + if (!id) return null; + + const meta = callGetter(unwrapped, metaGetter); + const title = + readProtoString(meta, titleGetter, 1) ?? + extractProjectDetailTitle(unwrapped, format); + return { id, title }; +} + +/** Reads cached project entries from an infinite-query `data` value (`{ pages: [...] }`). */ +function collectPagesEntries( + data: unknown, + itemsKey: string, + isShared: boolean, + format: ProjectMetadataFormat | undefined, + into: Map, +): void { + const pages = readOwn(data, "pages"); + if (!Array.isArray(pages)) return; + for (const page of pages) { + if (!page || typeof page !== "object") continue; + let items = readOwn(page, itemsKey); + if (!Array.isArray(items)) { + for (const value of Object.values(page as Record)) { + if (Array.isArray(value)) { + items = value; + break; + } + } + } + if (!Array.isArray(items)) continue; + for (const rawItem of items) { + const parsed = extractCardProtobuf(rawItem, isShared, format); + if (!parsed || into.has(parsed.id)) continue; + into.set(parsed.id, { + id: parsed.id, + title: parsed.title, + url: buildProjectUrl(parsed.id), + }); + } + } +} + +/** Reads the title for `projectId` from `QueryClient` (`PROJECT`, `PROJECT_DETAILS`, or grid caches). */ +function readTitleFromQueryClient( + client: QueryClient | undefined, + projectId: string, + format?: ProjectMetadataFormat, +): string | null { + const cache = client?.queryCache; + if (!cache) return null; + + const candidateKeys: unknown[][] = [ + ["PROJECT", projectId], + ["PROJECT_DETAILS", projectId], + ]; + if (format?.projectKey) { + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const keyFn = readOwn(namespace, format.projectKey); + if (typeof keyFn === "function") { + try { + const built: unknown = keyFn(projectId); + if (Array.isArray(built)) candidateKeys.unshift(built); + } catch { + // Ignore key builder error and inspect standard keys. + } + } + } + + if (typeof client?.ha === "function") { + for (const queryKey of candidateKeys) { + const title = extractProjectDetailTitle(client.ha(queryKey), format); + if (title !== null) return title; + } + } + + if (typeof cache.find === "function") { + for (const queryKey of candidateKeys) { + const query = cache.find({ queryKey, exact: true }); + const title = extractProjectDetailTitle(readOwn(query?.state, "data"), format); + if (title !== null) return title; + } + } + + const findAll = readOwn(cache, "findAll"); + if (typeof findAll === "function") { + const allQueries: unknown = findAll.call(cache); + if (Array.isArray(allQueries)) { + for (const query of allQueries) { + const key = readOwn(query, "queryKey"); + if ( + Array.isArray(key) && + key.length >= 2 && + (key[0] === "PROJECT" || key[0] === "PROJECT_DETAILS") && + key[1] === projectId + ) { + const state = readOwn(query, "state"); + const title = extractProjectDetailTitle(readOwn(state, "data"), format); + if (title !== null) return title; + } + } + const cards = new Map(); + for (const query of allQueries) { + const key = readOwn(query, "queryKey"); + if (!Array.isArray(key) || typeof key[0] !== "string") continue; + const state = readOwn(query, "state"); + const data = readOwn(state, "data"); + if (key[0] === "PROJECTS") { + collectPagesEntries(data, format?.ownedQuery ?? "Id", false, format, cards); + } else if (key[0] === "SHARED_PROJECTS") { + collectPagesEntries(data, format?.sharedQuery ?? "xs", true, format, cards); + } + } + const fromCard = cards.get(projectId)?.title ?? null; + if (fromCard !== null) return fromCard; + } + } + return null; +} + +/** Reads the authoritative project title from `Jk()`, `QueryClient`, or stripped `document.title`. */ +export function readProjectTitle(projectId: string | null): string | null { + const format = activeProjectMetadataFormat(); + const store = resolveStoreForProject(projectId); + if (store) { + const signalName = format?.titleSignal ?? "Jk"; + const rawSignalTitle = callGetter(store.service, signalName); + if (typeof rawSignalTitle === "string" && rawSignalTitle.trim()) { + return rawSignalTitle.trim(); + } + } + const client = findSharedQueryClient(store); + if (projectId) { + const cachedTitle = readTitleFromQueryClient(client, projectId, format); + if (cachedTitle !== null) return cachedTitle; + } + const onSubroute = /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); + if (onSubroute && store && format?.metadataQuery) { + const querySignal = readOwn(store.service, format.metadataQuery); + if (callGetter(querySignal, "data") !== undefined) { + return null; + } + } + return cleanFlowDocumentTitle(document.title); +} + +/** Waits for the store's `PROJECT` metadata query (`Ag`) to populate initial data before mutating. */ +async function ensureProjectMetadataLoaded( + store: ProjectStore, + format: ProjectMetadataFormat, +): Promise { + const querySignal = readOwn(store.service, format.metadataQuery); + const client = findSharedQueryClient(store); + const hasMetadata = (): boolean => { + if (callGetter(querySignal, "data") !== undefined) return true; + const direct = client?.ha?.(["PROJECT", store.projectId]); + if (direct !== undefined) return true; + const query = client?.queryCache?.find?.({ + queryKey: ["PROJECT", store.projectId], + exact: true, + }); + return readOwn(query?.state, "data") !== undefined; + }; + if (hasMetadata()) return; + + const refetch = readOwn(querySignal, "refetch"); + if (typeof refetch === "function" && !callBool(querySignal, "isFetching")) { + void Promise.resolve(refetch.call(querySignal)).catch(() => null); + } + const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; + while (Date.now() < deadline && isCurrent(store)) { + if (hasMetadata() || callBool(querySignal, "isError")) return; + await delay(QUERY_POLL_MS); + } +} + +/** Dispatches `set_project_title` through `ProjectStore` (`Lc` on `GO` or `YJ` on `$N`). */ +async function dispatchSetProjectTitle( + store: ProjectStore, + format: ProjectMetadataFormat, + desiredTitle: string, +): Promise { + if (!activeProjectStoreFormat()) { + clearProjectStore(); + throw new Error("unsupported_front_end"); + } + if (currentProjectStore(store.projectId) !== store || !isCurrent(store)) { + clearProjectStore(); + throw new Error("project_store_changed"); + } + await ensureProjectMetadataLoaded(store, format); + const payload = withMutationAliases({ + type: "set_project_title", + [format.titleField]: desiredTitle, + }); + + const mutator = resolveAsyncMutator( + store.service, + readOwn(store.service, format.metadataMutator), + ); + if (mutator) { + await mutator(payload); + return; + } + + const metadataService = readOwn(store.service, format.metadataService); + const dispatcher = readOwn(metadataService, format.metadataDispatcher); + if (typeof dispatcher === "function") { + await dispatcher.call(metadataService, store.projectId, payload); + const querySignal = readOwn(store.service, format.metadataQuery); + const refetch = readOwn(querySignal, "refetch"); + if (typeof refetch === "function") { + await Promise.resolve(refetch.call(querySignal)).catch(() => null); + } + return; + } + throw new Error("metadata_mutator_missing"); +} + +/** Runs a project metadata operation (`set_title`) in the pinned `ProjectStore` session. */ +export async function projectMetadataOp( + projectId: string, + session: string, + req: ProjectMetadataRequest, +): Promise { + const label = readBuildLabel(); + const build = frontendBuild(label); + if (!build) { + return { ok: false, error: "unsupported_front_end", build: label }; + } + const store = projectStore(projectId, session); + if (!store) { + return { ok: false, error: "project_changed" }; + } + const format = build.projectMetadata; + if (!format) { + return { ok: false, error: "legacy_project_title", build: label }; + } + + const action = String(req?.action || "").toLowerCase(); + if (action !== "set_title") { + return { ok: false, error: `unknown_project_metadata_action:${action}` }; + } + const desired = String(req?.title ?? "").trim(); + if (!desired) { + return { ok: false, error: "empty_title" }; + } + + const matchesDesired = (): boolean => { + const signalVal = callGetter(store.service, format.titleSignal); + if (typeof signalVal === "string" && signalVal.trim() === desired) { + return true; + } + const client = findSharedQueryClient(store); + return readTitleFromQueryClient(client, projectId, format) === desired; + }; + + await serializeStoreMutation(() => dispatchSetProjectTitle(store, format, desired)); + + const deadline = Date.now() + TITLE_CONFIRM_TIMEOUT_MS; + while (Date.now() < deadline && projectStore(projectId, session) === store && isCurrent(store)) { + const mutatorObj = readOwn(store.service, format.metadataMutator); + const mutating = callBool(mutatorObj, "isPending"); + if (!mutating && matchesDesired()) { + await delay(120); + if (matchesDesired()) { + return { + ok: true, + confirmed: true, + project_id: projectId, + title: desired, + }; + } + } + await delay(QUERY_POLL_MS); + } + return { ok: false, error: "project_title_not_confirmed" }; +} + +/** Checks whether `candidate` is a `flow-projects-grid` (`Y7`) component instance. */ +function isProjectsGridComponent( + candidate: unknown, + gridClass: unknown, + ownedKey: string, + sharedKey: string, +): candidate is Record { + if (!candidate || typeof candidate !== "object" || candidate instanceof Node) { + return false; + } + if (typeof gridClass === "function" && candidate instanceof gridClass) { + return true; + } + const owned = readOwn(candidate, ownedKey); + const shared = readOwn(candidate, sharedKey); + return ( + Boolean(owned && typeof owned === "object" && typeof readOwn(owned, "fetchNextPage") === "function") && + Boolean(shared && typeof shared === "object" && typeof readOwn(shared, "fetchNextPage") === "function") + ); +} + +/** Resolves the mounted `flow-projects-grid` (`Y7`) component instance on the Flow home page. */ +async function findProjectsGridComponent(): Promise<{ + grid: Record | null; + format: ProjectMetadataFormat | undefined; +}> { + const format = activeProjectMetadataFormat(); + const ownedKey = format?.ownedQuery ?? "Id"; + const sharedKey = format?.sharedQuery ?? "xs"; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const gridClass = format ? readOwn(namespace, format.gridClass) : undefined; + + const locate = (extraMaps?: Iterable>): Record | null => { + const host = document.querySelector("flow-projects-grid"); + if (host) { + const view = resolveLView(host); + const hit = view?.find((slot) => + isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), + ); + if (hit && typeof hit === "object") return hit as Record; + const ctx = (host as unknown as { __ngContext__?: unknown }).__ngContext__; + if (typeof ctx === "number" && extraMaps) { + for (const map of extraMaps) { + const candidateView = map.get(ctx); + if (!Array.isArray(candidateView)) continue; + const mappedHit = candidateView.find((slot) => + isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), + ); + if (mappedHit && typeof mappedHit === "object") { + runtimeState.ngLViewMap = map as Map; + return mappedHit as Record; + } + } + } + } + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + if (!isLiveLView(view)) continue; + const hit = view.find((slot) => + isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), + ); + if (hit && typeof hit === "object") return hit as Record; + } + return null; + }; + + let grid = locate(); + if (grid) return { grid, format }; + + for (let attempt = 0; attempt < 25; attempt += 1) { + const host = document.querySelector("flow-projects-grid"); + if (host) { + const captured = new Set>(); + await withMapCapture( + (map, _key, _value, write) => { + if (!write) captured.add(map); + }, + async () => { + const card = host.querySelector("flow-project-card, button"); + if (card instanceof HTMLElement) { + card.dispatchEvent(new PointerEvent("pointerenter", { bubbles: false })); + card.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false })); + } + await delay(40); + }, + ); + grid = locate(captured); + if (grid) return { grid, format }; + } + const loading = Boolean( + document.querySelector("flow-loading-page, .projects-loading-container"), + ); + if (!loading && !host && attempt >= 4) break; + await delay(120); + } + return { grid: locate(), format }; +} + +/** Returns the number of loaded pages in an infinite query signal. */ +function readPagesCount(query: InfiniteQuerySignal): number { + const data = callGetter(query, "data"); + const pages = readOwn(data, "pages"); + return Array.isArray(pages) ? pages.length : 0; +} + +/** Waits until an infinite query finishes its initial load or in-flight next-page fetch. */ +async function waitInfiniteQueryIdle( + query: InfiniteQuerySignal, + waitInitial: boolean, +): Promise { + const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; + while (Date.now() < deadline) { + if (callBool(query, "isError")) return; + const fetchingNext = callBool(query, "isFetchingNextPage"); + const placeholder = callBool(query, "isPlaceholderData"); + const initialBusy = + waitInitial && + readPagesCount(query) === 0 && + (callBool(query, "isFetching") || placeholder); + if (!fetchingNext && !initialBusy) return; + await delay(QUERY_POLL_MS); + } +} + +/** Fetches all remaining pages of `query` up to `MAX_GRID_PAGES` (`50`). */ +async function fetchAllInfinitePages( + query: InfiniteQuerySignal | undefined, + enabled: boolean, +): Promise { + if (!query || !enabled || typeof query.fetchNextPage !== "function") return; + await waitInfiniteQueryIdle(query, true); + for (let page = 0; page < MAX_GRID_PAGES; page += 1) { + await waitInfiniteQueryIdle(query, false); + if (!callBool(query, "hasNextPage") || callBool(query, "isFetchNextPageError")) { + break; + } + const beforePages = readPagesCount(query); + try { + await Promise.resolve(query.fetchNextPage()); + } catch { + break; + } + await waitInfiniteQueryIdle(query, false); + const afterPages = readPagesCount(query); + if (afterPages <= beforePages && callBool(query, "hasNextPage")) { + break; + } + } +} + +/** Collects cached dashboard project cards from `QueryClient` when `PROJECTS` or `SHARED_PROJECTS` exist. */ +function collectProjectsFromQueryCache( + client: QueryClient | undefined, + ownedKey: string, + sharedKey: string, + format: ProjectMetadataFormat | undefined, +): { sawProjectsQuery: boolean; items: Map } { + const items = new Map(); + let sawProjectsQuery = false; + const findAll = readOwn(client?.queryCache, "findAll"); + if (typeof findAll !== "function") return { sawProjectsQuery, items }; + const queries: unknown = findAll.call(client?.queryCache); + if (!Array.isArray(queries)) return { sawProjectsQuery, items }; + for (const query of queries) { + const key = readOwn(query, "queryKey"); + if (!Array.isArray(key) || typeof key[0] !== "string") continue; + const data = readOwn(readOwn(query, "state"), "data"); + if (key[0] === "PROJECTS") { + sawProjectsQuery = true; + collectPagesEntries(data, ownedKey, false, format, items); + } else if (key[0] === "SHARED_PROJECTS") { + sawProjectsQuery = true; + collectPagesEntries(data, sharedKey, true, format, items); + } + } + return { sawProjectsQuery, items }; +} + +/** Inspects `flow-projects-grid` (`PROJECTS` and `SHARED_PROJECTS`), fetches all pages, and reads cached card protobufs. */ +export async function listCachedProjects(): Promise { + const { grid, format } = await findProjectsGridComponent(); + const ownedKey = format?.ownedQuery ?? "Id"; + const sharedKey = format?.sharedQuery ?? "xs"; + + if (grid) { + const ownedQuery = readOwn(grid, ownedKey) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, sharedKey) as InfiniteQuerySignal | undefined; + const sharedEnabled = + typeof readOwn(grid, "zf") === "function" + ? callBool(grid, "zf") + : Boolean( + callGetter(sharedQuery, "data") !== undefined || + callBool(sharedQuery, "isFetching") || + callBool(sharedQuery, "hasNextPage"), + ); + + await Promise.all([ + fetchAllInfinitePages(ownedQuery, true), + fetchAllInfinitePages(sharedQuery, sharedEnabled), + ]); + + const items = new Map(); + collectPagesEntries(callGetter(ownedQuery, "data"), ownedKey, false, format, items); + if (sharedEnabled) { + collectPagesEntries(callGetter(sharedQuery, "data"), sharedKey, true, format, items); + } + return [...items.values()]; + } + + const cached = collectProjectsFromQueryCache( + findSharedQueryClient(null), + ownedKey, + sharedKey, + format, + ); + return cached.sawProjectsQuery ? [...cached.items.values()] : null; +} + +/** Reads currently loaded dashboard card protobufs without triggering additional pagination. */ +export function snapshotLoadedGridProjects(): Map { + const format = activeProjectMetadataFormat(); + const ownedKey = format?.ownedQuery ?? "Id"; + const sharedKey = format?.sharedQuery ?? "xs"; + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const gridClass = format ? readOwn(namespace, format.gridClass) : undefined; + const items = new Map(); + + const host = document.querySelector("flow-projects-grid"); + const view = host ? resolveLView(host) : null; + const grid = view?.find((slot) => + isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), + ) as Record | undefined; + + if (grid) { + const ownedQuery = readOwn(grid, ownedKey); + const sharedQuery = readOwn(grid, sharedKey); + collectPagesEntries(callGetter(ownedQuery, "data"), ownedKey, false, format, items); + collectPagesEntries(callGetter(sharedQuery, "data"), sharedKey, true, format, items); + return items; + } + + return collectProjectsFromQueryCache(findSharedQueryClient(null), ownedKey, sharedKey, format) + .items; +} + +/** Advances `flow-projects-grid` by one page when `hasNextPage()` is true, returning whether a page was fetched. */ +export async function advanceProjectsGridPage(): Promise { + const { grid, format } = await findProjectsGridComponent(); + if (!grid) return false; + const ownedKey = format?.ownedQuery ?? "Id"; + const sharedKey = format?.sharedQuery ?? "xs"; + const ownedQuery = readOwn(grid, ownedKey) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, sharedKey) as InfiniteQuerySignal | undefined; + const sharedEnabled = + typeof readOwn(grid, "zf") === "function" + ? callBool(grid, "zf") + : Boolean(callBool(sharedQuery, "hasNextPage")); + + await Promise.all([ + ownedQuery ? waitInfiniteQueryIdle(ownedQuery, true) : Promise.resolve(), + sharedQuery && sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, true) : Promise.resolve(), + ]); + + const tasks: Array> = []; + const beforeOwned = ownedQuery ? readPagesCount(ownedQuery) : 0; + const beforeShared = sharedQuery ? readPagesCount(sharedQuery) : 0; + + if ( + ownedQuery && + typeof ownedQuery.fetchNextPage === "function" && + callBool(ownedQuery, "hasNextPage") && + !callBool(ownedQuery, "isFetchNextPageError") + ) { + tasks.push(Promise.resolve(ownedQuery.fetchNextPage()).catch(() => null)); + } + if ( + sharedEnabled && + sharedQuery && + typeof sharedQuery.fetchNextPage === "function" && + callBool(sharedQuery, "hasNextPage") && + !callBool(sharedQuery, "isFetchNextPageError") + ) { + tasks.push(Promise.resolve(sharedQuery.fetchNextPage()).catch(() => null)); + } + if (tasks.length === 0) return false; + + await Promise.all(tasks); + await Promise.all([ + ownedQuery ? waitInfiniteQueryIdle(ownedQuery, false) : Promise.resolve(), + sharedQuery && sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, false) : Promise.resolve(), + ]); + + const afterOwned = ownedQuery ? readPagesCount(ownedQuery) : 0; + const afterShared = sharedQuery ? readPagesCount(sharedQuery) : 0; + return afterOwned > beforeOwned || afterShared > beforeShared; +} diff --git a/ts/project_nav.ts b/ts/project_nav.ts index 94db8e5..89fdf37 100644 --- a/ts/project_nav.ts +++ b/ts/project_nav.ts @@ -97,9 +97,7 @@ export async function projectNav(action: string): Promise { 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 || "", - ); + /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); if (!isSubRoute()) { return { ok: true, exited: true, method: "already_root" }; } diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..10b2646 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -171,7 +171,7 @@ function isAngularSignal(fn: Function): boolean { } /** Resolves an async promise runner from the verified `mutator` field on the store. */ -function resolveAsyncMutator( +export function resolveAsyncMutator( owner: object, mutator: unknown, ): ((payload: Record) => Promise) | null { @@ -281,13 +281,18 @@ async function dispatchStoreMutation( throw new Error("store_mutate_missing"); } -/** Serializes general store mutations in the current page session. */ -function mutateStore(store: ProjectStore, payload: Record): Promise { - const run = mutationChain.then(() => dispatchStoreMutation(store, payload)); +/** Serializes one async store operation on the current document's mutation chain. */ +export function serializeStoreMutation(operation: () => Promise): Promise { + const run = mutationChain.then(operation); mutationChain = run.then(() => undefined, () => undefined); return run; } +/** Serializes general store mutations in the current page session. */ +function mutateStore(store: ProjectStore, payload: Record): Promise { + return serializeStoreMutation(() => dispatchStoreMutation(store, payload)); +} + /** Installs `store` into both `boundStore` and `runtimeState.store`. */ export function installProjectStore(store: ProjectStore, views?: Map): void { const handle: FlowStoreHandle = { @@ -366,6 +371,7 @@ export function projectStoreStatus(projectId: string): ProjectStoreStatus { if (!readProjectStore(store)) { return { ok: false, error: "collection_store_not_bound" }; } + runtimeState.routePath = location.pathname; session ??= crypto.randomUUID(); return { ok: true, bound: true, session }; } diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..a633e84 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -1,7 +1,7 @@ // Copyright 2026 ByteLand Technology Limited // SPDX-License-Identifier: MIT -// List, rename, and delete Google Flow projects from the Flow UI. +// List, rename, and delete Google Flow projects from the Flow UI and query caches. import { buildProjectUrl, @@ -12,13 +12,19 @@ import { } from "./angular"; import { delay, elText, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; +import { + MAX_GRID_PAGES, + advanceProjectsGridPage, + listCachedProjects, + snapshotLoadedGridProjects, +} from "./project_metadata"; 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. */ + /** Visible or cached project card title. */ title: string | null; /** Navigable project URL. */ url: string | null; @@ -26,6 +32,84 @@ interface ScannedProjectCard { _card: HTMLElement; } +/** Material icon ligatures excluded from card and anchor title extraction. */ +const ICON_LIGATURE_RE = + /^(?:group|edit|more_vert|more_horiz|delete|share|visibility|visibility_off|lock|public|check|close|add|arrow_back|arrow_forward|folder|home_storage|push_pin)$/i; + +/** Selector matching icon and action elements stripped before reading card or link text. */ +const STRIPPED_LABEL_NODES = + 'mat-icon, flow-material-icon, .shared-project-icon, .google-symbols, .material-icons, button, [role="button"], [aria-hidden="true"]'; + +/** Selector matching non-header containers where fallback `set_title` must never edit inputs. */ +const FORBIDDEN_TITLE_ANCESTOR = + 'mat-sidenav, [flow-sidenav], aside, flow-project-nav-list, flow-agent-panel, flow-applet-chat-sidebar, flow-project-card, flow-grid-tile-container, flow-character-edit-header, flow-character-header, flow-applet-view-header, main, [role="dialog"], .cdk-overlay-container'; + +/** Selector matching workspace header containers that host the legacy project title input. */ +const WORKSPACE_HEADER_SELECTOR = + "flow-navigation-header, flow-project-header, nav.nav-header, header.header-base, header"; + +/** Extracts clean text from `node` after stripping `mat-icon` ligatures and action buttons. */ +function cleanCardOrLinkTitle(node: Element | null): string | null { + if (!node) return null; + const clone = node.cloneNode(true); + if (clone instanceof Element) { + for (const icon of Array.from(clone.querySelectorAll(STRIPPED_LABEL_NODES))) { + icon.remove(); + } + const line = (clone.textContent || "") + .split(/\r?\n/) + .map((part) => part.trim()) + .find((part) => part.length > 0 && !ICON_LIGATURE_RE.test(part)); + if (line) return line; + } + const fallback = elText(node) + .split(/\r?\n/) + .map((part) => part.trim()) + .find((part) => part.length > 0 && !ICON_LIGATURE_RE.test(part)); + return fallback || null; +} + +/** Scrolls `.load-more-sentinel` and its scrollable ancestors so `IntersectionObserver` fires. */ +function scrollLoadMoreSentinel(): HTMLElement | null { + const sentinel = document.querySelector( + "flow-projects-grid .load-more-sentinel, .load-more-sentinel", + ); + if (!(sentinel instanceof HTMLElement)) return null; + sentinel.scrollIntoView({ block: "end", inline: "nearest" }); + let parent: HTMLElement | null = sentinel.parentElement; + while (parent) { + if (parent.scrollHeight > parent.clientHeight) { + parent.scrollTop = parent.scrollHeight; + } + parent = parent.parentElement; + } + window.scrollTo(0, document.documentElement.scrollHeight); + return sentinel; +} + +/** Finds the visible `` input inside the workspace header only. */ +function findWorkspaceHeaderTitleInput(): HTMLInputElement | null { + const headers = Array.from(document.querySelectorAll(WORKSPACE_HEADER_SELECTOR)); + for (const header of headers) { + if (header.closest(FORBIDDEN_TITLE_ANCESTOR)) continue; + const candidates = Array.from( + header.querySelectorAll( + 'flow-editable-text input.editable-text-input, input[aria-label="Editable text"], .editable-text-input', + ), + ); + for (const candidate of candidates) { + if ( + candidate instanceof HTMLInputElement && + !candidate.closest(FORBIDDEN_TITLE_ANCESTOR) && + candidate.getClientRects().length > 0 + ) { + return candidate; + } + } + } + return null; +} + /** Lists, renames, or deletes Google Flow projects on home or workspace pages. */ export async function projectsOp(req: ProjectsOpRequest): Promise { const UUID_RE = @@ -40,6 +124,17 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { return null; } seen.add(obj); + const ubFn = readOwn(obj, "Ub"); + if (typeof ubFn === "function") { + try { + const rawUb: unknown = ubFn.call(obj); + if (typeof rawUb === "string" && rawUb.trim()) { + return rawUb.trim(); + } + } catch { + // Ignore getter failure and inspect plain keys. + } + } for (const k of ["projectId", "id", "uuid", "workflowId"]) { const val = readOwn(obj, k); if (typeof val === "string") { @@ -62,34 +157,36 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { 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; + async function scanCards(waitInitial = true): Promise { + if (waitInitial) { + 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); } - await delay(150); } const seenMaps = new Set>(); @@ -114,9 +211,10 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { }), ); } - await delay(80); + await delay(60); }); + const cachedById = snapshotLoadedGridProjects(); const byId = new Map(); const cards = Array.from(document.querySelectorAll("flow-project-card")); for (const card of cards) { @@ -154,23 +252,18 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } } + const cachedTitle = pid ? (cachedById.get(pid)?.title ?? null) : null; 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}`; + card.querySelector(".project-title-text") || + card.querySelector('[class*="title"]:not(.project-card-edit-form *), h2, h3, h4') || + card; + const domTitle = cleanCardOrLinkTitle(titleNode); + const resolvedTitle = cachedTitle ?? domTitle; + const key = pid || `card:${resolvedTitle || byId.size}`; if (!byId.has(key)) { byId.set(key, { id: pid, - title: rawText || null, + title: resolvedTitle, url: pid ? buildProjectUrl(pid) : null, _card: card, }); @@ -184,14 +277,16 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { 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"); + const titleTarget = + a.querySelector(".project-title-text") || + cardParent?.querySelector(".project-title-text") || + a; + const title = + cachedById.get(pid)?.title ?? cleanCardOrLinkTitle(titleTarget); byId.set(pid, { id: pid, - title: title || null, + title, url: new URL(href, location.origin).href, _card: cardParent instanceof HTMLElement ? cardParent : a, }); @@ -289,7 +384,34 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { const action = String(req?.action || "list").toLowerCase(); if (action === "list") { - const items = await scanCards(); + const cached = await listCachedProjects(); + if (cached !== null) { + const merged = new Map(); + for (const item of cached) { + merged.set(item.id, { id: item.id, title: item.title, url: item.url }); + } + const domCards = await scanCards(cached.length === 0); + for (const dom of domCards) { + const key = dom.id || `dom:${dom.title || merged.size}`; + const existing = dom.id ? merged.get(dom.id) : undefined; + if (!existing) { + merged.set(key, { id: dom.id, title: dom.title, url: dom.url }); + } else if (!existing.title && dom.title) { + existing.title = dom.title; + } + } + return { ok: true, projects: Array.from(merged.values()) }; + } + + await scanCards(true); + for (let page = 0; page < MAX_GRID_PAGES; page += 1) { + const before = document.querySelectorAll("flow-project-card").length; + if (!scrollLoadMoreSentinel()) break; + await delay(250); + const after = document.querySelectorAll("flow-project-card").length; + if (after <= before) break; + } + const items = await scanCards(false); return { ok: true, projects: items.map(({ id, title, url }) => ({ id, title, url })), @@ -297,17 +419,19 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } if (action === "set_title") { + const pathname = location.pathname || ""; + if (/\/project\/[^/?#]+\/[^/?#]+/.test(pathname)) { + return { ok: false, error: "project_title_subroute" }; + } + if (!/\/project\/[^/?#]+\/?$/.test(pathname)) { + return { ok: false, error: "not_in_project" }; + } const desired = String(req?.title || "").trim(); if (!desired) return { ok: false, error: "empty_title" }; 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', - ); - if (cand instanceof HTMLInputElement && cand.getClientRects().length > 0) { - input = cand; - break; - } + input = findWorkspaceHeaderTitleInput(); + if (input) break; await delay(100); } if (!input) return { ok: false, error: "project_title_input_not_found" }; @@ -323,9 +447,7 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { 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 { @@ -394,7 +516,7 @@ 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() : ""; - const matchesTarget = (p: ScannedProjectCard): boolean => { + const matchesTarget = (p: { id: string | null; title: string | null }): boolean => { if (targetId && p.id === targetId) return true; if ( targetTitle && @@ -405,12 +527,36 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } return false; }; - const items = await scanCards(); - const hit = items.find(matchesTarget); + + let items = await scanCards(true); + let hit = items.find(matchesTarget); + for (let page = 0; !hit && page < MAX_GRID_PAGES; page += 1) { + const beforeCount = document.querySelectorAll("flow-project-card").length; + const sentinel = scrollLoadMoreSentinel(); + const advanced = await advanceProjectsGridPage(); + await delay(200); + items = await scanCards(false); + hit = items.find(matchesTarget); + if (hit) break; + const afterCount = document.querySelectorAll("flow-project-card").length; + if (!advanced && afterCount <= beforeCount) { + if (!sentinel) break; + scrollLoadMoreSentinel(); + await delay(250); + if (document.querySelectorAll("flow-project-card").length <= beforeCount) { + break; + } + items = await scanCards(false); + hit = items.find(matchesTarget); + } + } + if (!hit || !hit._card) { return { ok: false, error: "project_card_not_found" }; } - const beforeMatches = items.filter(matchesTarget).length; + const beforeCached = await listCachedProjects(); + const beforePool = beforeCached ?? items; + const beforeMatches = beforePool.filter(matchesTarget).length; const deletedId = hit.id; const card = hit._card; card.scrollIntoView({ block: "center" }); @@ -493,15 +639,19 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { if (!document.body.contains(card)) break; await delay(100); } - const entryRemoved = (entries: ScannedProjectCard[]): boolean => - deletedId + const isRemovedNow = async (): Promise => { + if (document.body.contains(card)) return false; + const currentCached = await listCachedProjects(); + const entries = currentCached ?? (await scanCards(false)); + return 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())) { + if (await isRemovedNow()) { await delay(250); - if (entryRemoved(await scanCards())) { + if (await isRemovedNow()) { return { ok: true, confirmed: true, diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..8b7015b 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -6,6 +6,7 @@ import { readOwn } from "./angular"; import { characterPersonalityNotes, characterVoice } from "./character_bio"; import { activeProjectStoreFormat, snapshotFormat } from "./frontend_builds"; +import { readProjectTitle } from "./project_metadata"; import { currentProjectStore, projectInRoute } from "./project_store"; import { sceneContents } from "./scene_tiles"; import { @@ -213,16 +214,7 @@ 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 projectTitle = readProjectTitle(projectId); const credits = readMappedCredits() ?? readDomAccountCredits(); diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..d1cf9cc 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -815,6 +815,12 @@ export interface FlowMcpRuntime { projectNav: (action: string) => Promise; /** Lists, renames, or deletes Google Flow projects on home or workspace pages. */ projectsOp: (req: ProjectsOpRequest) => Promise; + /** Mutates project metadata in the pinned project store. */ + projectMetadataOp: ( + projectId: string, + session: string, + request: import("./project_metadata").ProjectMetadataRequest, + ) => Promise; /** Renames or moves asset tiles to trash. */ assetOps: (action: string, id: string, extra: AssetRenameExtra | null) => Promise; /** Moves one asset to trash in the pinned project store. */ From 6e21a2b7c841636dab955fbafa6d5ccfbf7172fe Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:11:07 +0000 Subject: [PATCH 2/3] fix: preserve collection routes and project titles - Keep /collection/ in ensure_project_workspace_root - Add ensure_project_root_route for legacy DOM title fallback - Clean Google Flow wrappers only on document.title - Strip icon nodes in card fallback without filtering plain words - Allow workspace header inside main for legacy title edits - Read protobuf fields only from configured getters and keys - Require loaded PROJECT metadata before title mutations - Confirm card deletion without full-cache list pagination - Document project_title in flow_assets list reference --- docs/en/tools-reference.md | 2 +- docs/ja/tools-reference.md | 2 +- docs/zh-CN/tools-reference.md | 2 +- src/assets.rs | 4 +- src/characters.rs | 23 +- src/project.rs | 82 +---- src/project_route.rs | 81 ++--- src/upload.rs | 2 +- ts/project_metadata.ts | 642 +++++++++++++++------------------- ts/project_nav.ts | 68 ++-- ts/projects_ops.ts | 121 +++---- 11 files changed, 448 insertions(+), 581 deletions(-) diff --git a/docs/en/tools-reference.md b/docs/en/tools-reference.md index d8d6f6a..33ba0c4 100644 --- a/docs/en/tools-reference.md +++ b/docs/en/tools-reference.md @@ -352,7 +352,7 @@ Open the target project workspace before you upload. Upload works from the proje } ``` -The result gives `project_id`, `count`, and `assets`. Each asset gives its `id`, `name`, `kind`, and `primary_media_id` when available. +The `list` result gives `project_id`, `project_title`, `count`, and `assets`. The `upload` result gives `project_id`, `count`, and `assets`. Each asset gives its `id`, `name`, `kind`, and `primary_media_id` when available. If the batch stops, the error gives the assets that Flow confirms before the failure. It also gives `file` if the tool can identify the file in progress. If you get `outcome_unknown`, check the project before you retry. diff --git a/docs/ja/tools-reference.md b/docs/ja/tools-reference.md index 559b074..e5bce73 100644 --- a/docs/ja/tools-reference.md +++ b/docs/ja/tools-reference.md @@ -352,7 +352,7 @@ Flow シーンタイムラインの一覧表示、作成、クリップ追加、 } ``` -結果には `project_id`、`count`、`assets` が含まれます。各アセットには `id`、`name`、`kind`、取得できる場合は `primary_media_id` が含まれます。 +`list` の結果には `project_id`、`project_title`、`count`、`assets` が含まれます。`upload` の結果には `project_id`、`count`、`assets` が含まれます。各アセットには `id`、`name`、`kind`、取得できる場合は `primary_media_id` が含まれます。 途中で失敗した場合、エラーには Flow が確認済みのアセットが含まれます。処理中のファイルを特定できる場合は `file` も返ります。`outcome_unknown` が返った場合は、再試行の前にプロジェクトを確認してください。 diff --git a/docs/zh-CN/tools-reference.md b/docs/zh-CN/tools-reference.md index 748749e..f04c430 100644 --- a/docs/zh-CN/tools-reference.md +++ b/docs/zh-CN/tools-reference.md @@ -352,7 +352,7 @@ flow-mcp [OPTIONS] } ``` -返回 `project_id`、`count` 和 `assets`。每项包含 `id`、`name`、`kind`,并在可用时返回 `primary_media_id`。 +`list` 返回 `project_id`、`project_title`、`count` 和 `assets`。`upload` 返回 `project_id`、`count` 和 `assets`。每项包含 `id`、`name`、`kind`,并在可用时返回 `primary_media_id`。 批次中途失败时,错误包含 Flow 已确认的资源。若能确定处理到哪个文件,也会返回 `file`。收到 `outcome_unknown` 时,请检查项目后再重试。 diff --git a/src/assets.rs b/src/assets.rs index fc47972..8e4fe6b 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -253,7 +253,9 @@ async fn read_project_assets(engine: &ChromeEngine) -> Result` and clears stale Angular store handles. pub(crate) async fn exit_character_editor(engine: &ChromeEngine, project_id: Option<&str>) { - let before = engine.current_url().await.unwrap_or_default(); - let in_character = before.contains("/character"); - let in_workspace = engine + let before_finish = engine.current_url().await.unwrap_or_default(); + let in_character = before_finish.contains("/character/"); + let finish_res = engine .call_flow_async("characterOp", json!([{ "action": "finish" }])) - .await + .await; + let in_workspace = finish_res + .as_ref() .ok() - .and_then(|v| v.get("in_workspace").and_then(Value::as_bool)) + .and_then(|v| v.get("in_workspace")) + .and_then(|v| v.as_bool()) .unwrap_or(false); let cur = engine.current_url().await.unwrap_or_default(); - if (in_character && !in_workspace) || cur.contains("/character") { - if !cur.contains("/character") { + if (in_character && !in_workspace) || cur.contains("/character/") { + if !cur.contains("/character/") { tokio::time::sleep(Duration::from_millis(400)).await; } if let Some(pid) = project_id .map(str::to_string) .or_else(|| project_id_from_url(&cur)) - .or_else(|| project_id_from_url(&before)) + .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; } - } else if is_project_subroute_url(&cur) { - let _ = ensure_project_workspace_root(engine).await; } let _ = ensure_flow_store(engine).await; } diff --git a/src/project.rs b/src/project.rs index c431017..f75156e 100644 --- a/src/project.rs +++ b/src/project.rs @@ -16,9 +16,9 @@ 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::project_route::{clean_flow_page_title, ensure_project_root_route}; pub(crate) use crate::project_route::{ - clean_flow_page_title, ensure_project_workspace_root, project_id_from_url, - project_subroute_url, project_workspace_url, + ensure_project_workspace_root, project_id_from_url, project_subroute_url, project_workspace_url, }; use crate::project_store::{ProjectStoreSession, bind_current_store, prepare_project_store_status}; @@ -221,7 +221,9 @@ pub(crate) async fn get_flow_state(engine: &ChromeEngine, probe: bool) -> FlowSt project = snap .get("projectTitle") .and_then(Value::as_str) - .and_then(clean_flow_page_title); + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); credits = snap.get("credits").and_then(|v| v.as_i64()); assets_count = snap .get("assets") @@ -629,7 +631,9 @@ async fn open_project( "title": snap .get("projectTitle") .and_then(Value::as_str) - .and_then(clean_flow_page_title) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) .or(matched_title), "url": engine.current_url().await.unwrap_or(project_url), "assets_count": snap.get("assets").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0), @@ -671,7 +675,7 @@ async fn apply_project_title(engine: &ChromeEngine, desired: &str) -> Result {} } } - ensure_project_workspace_root(engine).await?; + ensure_project_root_route(engine).await?; let res = run_projects_op(engine, json!({ "action": "set_title", "title": desired })).await?; if res.get("ok").and_then(Value::as_bool) != Some(true) { anyhow::bail!( @@ -715,64 +719,6 @@ 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(); @@ -810,14 +756,6 @@ async fn delete_project( open_signed_in_home_page(engine).await?; let _ = engine.bind_angular_views("flow-projects-grid").await; - let before_list = run_projects_op(engine, json!({ "action": "list" })).await?; - let before_matches = before_list - .get("projects") - .and_then(Value::as_array) - .map_or(1, |projects| { - count_matching_project_entries(projects, id, title) - }); - let res = run_projects_op( engine, json!({ "action": "delete", "project_id": id, "title": title }), @@ -831,8 +769,6 @@ async fn delete_project( .unwrap_or("unknown") ); } - let deleted_id = res.get("deleted_id").and_then(Value::as_str).or(id); - confirm_project_deleted(engine, deleted_id, title, before_matches).await?; Ok(res) } diff --git a/src/project_route.rs b/src/project_route.rs index 6329e98..a6ba5a6 100644 --- a/src/project_route.rs +++ b/src/project_route.rs @@ -33,8 +33,8 @@ pub(crate) fn is_project_subroute_url(url: &str) -> bool { segs.next().is_some_and(|seg| !seg.is_empty()) } -/// Returns `true` when `url` points to a non-upload `/project//...` subroute while keeping `/collection/`. -pub(crate) fn is_upload_subroute_url(url: &str) -> bool { +/// Returns `true` when `url` points to a non-grid `/project//...` subroute while keeping `/collection/`. +pub(crate) fn is_non_grid_subroute_url(url: &str) -> bool { let path = url.split(['?', '#']).next().unwrap_or_default(); let Some((_, project)) = path.split_once("/project/") else { return false; @@ -50,7 +50,7 @@ pub(crate) fn is_upload_subroute_url(url: &str) -> bool { } } -/// Strips `"Google Flow - "` wrappers and rejects generic application or trash document titles. +/// Strips `"Google Flow - "` wrappers and rejects generic `"Google Flow"` `document.title` values. pub(crate) fn clean_flow_page_title(raw: &str) -> Option { let trimmed = raw.trim(); if trimmed.is_empty() { @@ -66,57 +66,48 @@ pub(crate) fn clean_flow_page_title(raw: &str) -> Option { { return None; } - let without_prefix = strip_flow_title_prefix(trimmed); - let stripped = strip_flow_title_suffix(without_prefix).trim(); - if stripped.is_empty() - || stripped.eq_ignore_ascii_case("google flow") - || stripped.eq_ignore_ascii_case("flow") - || stripped.eq_ignore_ascii_case("trash") - { + let without_prefix = strip_google_flow_prefix(trimmed); + let stripped = strip_google_flow_suffix(without_prefix).trim(); + if stripped.is_empty() || stripped.eq_ignore_ascii_case("google flow") { return None; } Some(stripped.to_string()) } -/// Strips a leading `"Google Flow - "` or `"Flow - "` prefix from `value`. -fn strip_flow_title_prefix(value: &str) -> &str { - for prefix in ["google flow", "flow"] { - if value.len() >= prefix.len() - && value - .get(..prefix.len()) - .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) - && let Some(tail) = value.get(prefix.len()..) - { - let rest = tail.trim_start(); - if let Some(after_sep) = rest.strip_prefix(['-', '–', '—', '|', ':']) { - return after_sep.trim_start(); - } - } +/// Strips a leading `"Google Flow - "` prefix from a `document.title` string. +fn strip_google_flow_prefix(value: &str) -> &str { + let prefix = "google flow"; + if value.len() >= prefix.len() + && value + .get(..prefix.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(prefix)) + && let Some(tail) = value.get(prefix.len()..) + && let Some(after_sep) = tail.trim_start().strip_prefix(['-', '–', '—', '|', ':']) + { + return after_sep.trim_start(); } value } -/// Strips a trailing `"- Google Flow"` or `"- Flow"` suffix from `value`. -fn strip_flow_title_suffix(value: &str) -> &str { - for suffix in ["google flow", "flow"] { - if value.len() >= suffix.len() - && value - .get(value.len() - suffix.len()..) - .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix)) - && let Some(head) = value.get(..value.len() - suffix.len()) - { - let before = head.trim_end(); - if let Some(before_sep) = before.strip_suffix(['-', '–', '—', '|', ':']) { - return before_sep.trim_end(); - } - } +/// Strips a trailing `"- Google Flow"` suffix from a `document.title` string. +fn strip_google_flow_suffix(value: &str) -> &str { + let suffix = "google flow"; + if value.len() >= suffix.len() + && value + .get(value.len() - suffix.len()..) + .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix)) + && let Some(head) = value.get(..value.len() - suffix.len()) + && let Some(before_sep) = head.trim_end().strip_suffix(['-', '–', '—', '|', ':']) + { + return before_sep.trim_end(); } value } -/// Exits active project subroutes matched by `is_subroute` back to `/project/`. +/// Exits active project subroutes matched by `is_subroute` using `nav_action` or direct navigation. async fn exit_matching_subroute( engine: &ChromeEngine, + nav_action: &str, is_subroute: fn(&str) -> bool, ) -> Result<()> { let current = engine.current_url().await?; @@ -133,7 +124,7 @@ async fn exit_matching_subroute( && project_workspace_url(url, &project_id) == workspace }; let _ = engine - .call_flow_async("projectNav", json!(["exit_subroute"])) + .call_flow_async("projectNav", json!([nav_action])) .await; if returned(&engine.current_url().await.unwrap_or_default()) { return Ok(()); @@ -148,14 +139,14 @@ async fn exit_matching_subroute( anyhow::bail!("Cannot return to the active Flow project workspace") } -/// Navigates back to `/project/` when Chrome is on any `/project//...` subroute. +/// Navigates back to `/project/` from non-grid subroutes while keeping `/project//collection/`. pub(crate) async fn ensure_project_workspace_root(engine: &ChromeEngine) -> Result<()> { - exit_matching_subroute(engine, is_project_subroute_url).await + exit_matching_subroute(engine, "exit_subroute", is_non_grid_subroute_url).await } -/// Navigates back to `/project/` from editor subroutes while keeping `/project//collection/`. -pub(crate) async fn ensure_project_upload_route(engine: &ChromeEngine) -> Result<()> { - exit_matching_subroute(engine, is_upload_subroute_url).await +/// Navigates back to `/project/` when Chrome is on any `/project//...` subroute. +pub(crate) async fn ensure_project_root_route(engine: &ChromeEngine) -> Result<()> { + exit_matching_subroute(engine, "exit_to_project_root", is_project_subroute_url).await } /// Returns `true` when `host` is a Google Flow host (`flow.google.com` or `labs.google`). diff --git a/src/upload.rs b/src/upload.rs index 46e8da7..896bde0 100644 --- a/src/upload.rs +++ b/src/upload.rs @@ -46,7 +46,7 @@ pub(crate) async fn local_upload_paths(files: &[String], label: &str) -> Result< /// Uploads files to the pinned project and returns the saved assets. pub(crate) async fn upload_project_files(engine: &ChromeEngine, files: &[String]) -> Result { - crate::project_route::ensure_project_upload_route(engine).await?; + crate::project::ensure_project_workspace_root(engine).await?; let project = ProjectStoreSession::open(engine).await?; let has_video = files.iter().any(|file| { mime_guess::from_path(file) diff --git a/ts/project_metadata.ts b/ts/project_metadata.ts index a431190..261aaa3 100644 --- a/ts/project_metadata.ts +++ b/ts/project_metadata.ts @@ -47,6 +47,10 @@ const QUERY_POLL_MS = 80; /** Confirmation timeout in milliseconds after dispatching `set_project_title`. */ const TITLE_CONFIRM_TIMEOUT_MS = 6_000; +/** Strict UUID pattern used when reading plain `projectId` properties. */ +const UUID_EXACT_RE = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + /** Request payload accepted by `projectMetadataOp`. */ export interface ProjectMetadataRequest { /** Action name (`"set_title"`). */ @@ -57,7 +61,7 @@ export interface ProjectMetadataRequest { /** Normalized project summary read from cached dashboard card protobufs. */ export interface CachedProjectItem { - /** Project UUID read from the card protobuf. */ + /** Project ID read from the card protobuf. */ id: string; /** Project title read from the card metadata protobuf, or null when unset. */ title: string | null; @@ -69,8 +73,6 @@ export interface CachedProjectItem { interface InfiniteQuerySignal { /** Returns cached infinite-query data (`{ pages: unknown[] }`). */ data?: () => unknown; - /** Returns true while initial data has not resolved yet. */ - isPending?: () => boolean; /** Returns true while any fetch is in flight. */ isFetching?: () => boolean; /** Returns true while the query displays placeholder data. */ @@ -87,6 +89,18 @@ interface InfiniteQuerySignal { fetchNextPage?: () => Promise; } +/** Resolved infinite-query handles for a mounted `flow-projects-grid` component. */ +interface ResolvedGridQueries { + /** Verified metadata format for the active build. */ + format: ProjectMetadataFormat; + /** Owned `PROJECTS` infinite query signal. */ + ownedQuery: InfiniteQuerySignal | undefined; + /** Shared `SHARED_PROJECTS` infinite query signal. */ + sharedQuery: InfiniteQuerySignal | undefined; + /** True when the `SHARED_PROJECTS` query is enabled on the grid. */ + sharedEnabled: boolean; +} + /** Calls a zero-argument boolean method on `target` when present. */ function callBool(target: unknown, key: string): boolean { const fn = readOwn(target, key); @@ -111,7 +125,7 @@ function callGetter(target: unknown, key: string): unknown { } } -/** Strips `"Google Flow - "` and `"- Google Flow"` wrappers and generic app titles. */ +/** Strips `"Google Flow - "` wrappers and generic `"Google Flow"` titles from `document.title`. */ export function cleanFlowDocumentTitle(raw: string | null | undefined): string | null { const trimmed = typeof raw === "string" ? raw.trim() : ""; if (!trimmed) return null; @@ -119,10 +133,10 @@ export function cleanFlowDocumentTitle(raw: string | null | undefined): string | return null; } const stripped = trimmed - .replace(/^(?:google\s+)?flow\s*[-–|:—]\s*/i, "") - .replace(/\s*[-–|:—]\s*(?:google\s+)?flow$/i, "") + .replace(/^google\s+flow\s*[-–|:—]\s*/i, "") + .replace(/\s*[-–|:—]\s*google\s+flow$/i, "") .trim(); - if (!stripped || /^(?:google\s+flow|flow|trash)$/i.test(stripped)) { + if (!stripped || /^google\s+flow$/i.test(stripped)) { return null; } return stripped; @@ -212,80 +226,57 @@ function findSharedQueryClient(store: ProjectStore | null): QueryClient | undefi return undefined; } -/** Extracts a non-empty string from a JSPB message getter or raw JSPB array slot. */ -function readProtoString( - msg: unknown, - getterName: string | undefined, - fallbackFieldIndex?: number, -): string | null { - if (!msg || typeof msg !== "object") return null; - if (getterName) { - const val = callGetter(msg, getterName); - if (typeof val === "string") return val.trim() || null; - } - for (const candidate of Object.values(msg as Record)) { - if (Array.isArray(candidate) && fallbackFieldIndex !== undefined) { - const raw = candidate[fallbackFieldIndex - 1] ?? candidate[fallbackFieldIndex]; - if (typeof raw === "string" && raw.trim()) return raw.trim(); - } - } - return null; +/** Calls `getterName` on a protobuf message and returns a trimmed non-empty string, or `null`. */ +function readProtoString(msg: unknown, getterName: string | undefined): string | null { + if (!msg || typeof msg !== "object" || !getterName) return null; + const val = callGetter(msg, getterName); + return typeof val === "string" && val.trim() ? val.trim() : null; } /** Extracts a project title from a cached `PROJECT` or `PROJECT_DETAILS` message. */ function extractProjectDetailTitle( data: unknown, - format?: ProjectMetadataFormat, + format: ProjectMetadataFormat | undefined, ): string | null { if (!data || typeof data !== "object") return null; - const infoGetter = format?.projectInfoGetter ?? "AE"; - const titleGetter = format?.projectTitleGetter ?? "tI"; - const metaGetter = format?.cardMetadataGetter ?? "getMetadata"; - const cardTitleGetter = format?.cardTitleGetter ?? "Qd"; - - const info = callGetter(data, infoGetter); - const fromInfo = readProtoString(info, titleGetter, 1); - if (fromInfo !== null) return fromInfo; - - const meta = callGetter(data, metaGetter); - const fromMeta = readProtoString(meta, cardTitleGetter, 1); - if (fromMeta !== null) return fromMeta; - - const directTitle = readOwn(data, "title") ?? readOwn(data, "displayName"); - if (typeof directTitle === "string" && directTitle.trim()) { - return directTitle.trim(); + if (format) { + const fromInfo = readProtoString( + callGetter(data, format.projectInfoGetter), + format.projectTitleGetter, + ); + if (fromInfo !== null) return fromInfo; + const fromMeta = readProtoString( + callGetter(data, format.cardMetadataGetter), + format.cardTitleGetter, + ); + if (fromMeta !== null) return fromMeta; } - return null; + const directTitle = readOwn(data, "title") ?? readOwn(data, "displayName"); + return typeof directTitle === "string" && directTitle.trim() ? directTitle.trim() : null; } /** Extracts `{ id, title }` from one owned or shared project card protobuf entry. */ function extractCardProtobuf( rawEntry: unknown, isShared: boolean, - format?: ProjectMetadataFormat, + format: ProjectMetadataFormat, ): { id: string; title: string | null } | null { if (!rawEntry || typeof rawEntry !== "object") return null; - const sharedGetter = format?.sharedProjectGetter ?? "Jn"; - const idGetter = format?.cardIdGetter ?? "Ub"; - const metaGetter = format?.cardMetadataGetter ?? "getMetadata"; - const titleGetter = format?.cardTitleGetter ?? "Qd"; - - const unwrapped = isShared ? (callGetter(rawEntry, sharedGetter) ?? rawEntry) : rawEntry; + const unwrapped = isShared ? callGetter(rawEntry, format.sharedProjectGetter) : rawEntry; if (!unwrapped || typeof unwrapped !== "object") return null; - const id = - readProtoString(unwrapped, idGetter, 1) ?? - (typeof readOwn(unwrapped, "projectId") === "string" - ? String(readOwn(unwrapped, "projectId")).trim() - : null) ?? - (typeof readOwn(unwrapped, "id") === "string" - ? String(readOwn(unwrapped, "id")).trim() - : null); + let id = readProtoString(unwrapped, format.cardIdGetter); + if (!id) { + const plain = readOwn(unwrapped, "projectId"); + if (typeof plain === "string" && UUID_EXACT_RE.test(plain.trim())) { + id = plain.trim(); + } + } if (!id) return null; - const meta = callGetter(unwrapped, metaGetter); + const meta = callGetter(unwrapped, format.cardMetadataGetter); const title = - readProtoString(meta, titleGetter, 1) ?? + readProtoString(meta, format.cardTitleGetter) ?? extractProjectDetailTitle(unwrapped, format); return { id, title }; } @@ -295,22 +286,13 @@ function collectPagesEntries( data: unknown, itemsKey: string, isShared: boolean, - format: ProjectMetadataFormat | undefined, + format: ProjectMetadataFormat, into: Map, ): void { const pages = readOwn(data, "pages"); if (!Array.isArray(pages)) return; for (const page of pages) { - if (!page || typeof page !== "object") continue; - let items = readOwn(page, itemsKey); - if (!Array.isArray(items)) { - for (const value of Object.values(page as Record)) { - if (Array.isArray(value)) { - items = value; - break; - } - } - } + const items = readOwn(page, itemsKey); if (!Array.isArray(items)) continue; for (const rawItem of items) { const parsed = extractCardProtobuf(rawItem, isShared, format); @@ -324,16 +306,12 @@ function collectPagesEntries( } } -/** Reads the title for `projectId` from `QueryClient` (`PROJECT`, `PROJECT_DETAILS`, or grid caches). */ -function readTitleFromQueryClient( - client: QueryClient | undefined, +/** Builds the candidate `QueryClient` keys for `projectId`. */ +function buildCandidateProjectKeys( projectId: string, - format?: ProjectMetadataFormat, -): string | null { - const cache = client?.queryCache; - if (!cache) return null; - - const candidateKeys: unknown[][] = [ + format: ProjectMetadataFormat | undefined, +): unknown[][] { + const keys: unknown[][] = [ ["PROJECT", projectId], ["PROJECT_DETAILS", projectId], ]; @@ -343,71 +321,45 @@ function readTitleFromQueryClient( if (typeof keyFn === "function") { try { const built: unknown = keyFn(projectId); - if (Array.isArray(built)) candidateKeys.unshift(built); + if (Array.isArray(built)) keys.unshift(built); } catch { // Ignore key builder error and inspect standard keys. } } } + return keys; +} - if (typeof client?.ha === "function") { - for (const queryKey of candidateKeys) { - const title = extractProjectDetailTitle(client.ha(queryKey), format); - if (title !== null) return title; - } - } +/** Reads the title for `projectId` from `QueryClient` (`PROJECT`, `PROJECT_DETAILS`, or grid caches). */ +function readTitleFromQueryClient( + client: QueryClient | undefined, + projectId: string, + format: ProjectMetadataFormat | undefined, +): string | null { + const cache = client?.queryCache; + if (!cache) return null; - if (typeof cache.find === "function") { - for (const queryKey of candidateKeys) { - const query = cache.find({ queryKey, exact: true }); - const title = extractProjectDetailTitle(readOwn(query?.state, "data"), format); - if (title !== null) return title; - } - } + for (const queryKey of buildCandidateProjectKeys(projectId, format)) { + const direct = typeof client?.ha === "function" ? client.ha(queryKey) : undefined; + const fromDirect = extractProjectDetailTitle(direct, format); + if (fromDirect !== null) return fromDirect; - const findAll = readOwn(cache, "findAll"); - if (typeof findAll === "function") { - const allQueries: unknown = findAll.call(cache); - if (Array.isArray(allQueries)) { - for (const query of allQueries) { - const key = readOwn(query, "queryKey"); - if ( - Array.isArray(key) && - key.length >= 2 && - (key[0] === "PROJECT" || key[0] === "PROJECT_DETAILS") && - key[1] === projectId - ) { - const state = readOwn(query, "state"); - const title = extractProjectDetailTitle(readOwn(state, "data"), format); - if (title !== null) return title; - } - } - const cards = new Map(); - for (const query of allQueries) { - const key = readOwn(query, "queryKey"); - if (!Array.isArray(key) || typeof key[0] !== "string") continue; - const state = readOwn(query, "state"); - const data = readOwn(state, "data"); - if (key[0] === "PROJECTS") { - collectPagesEntries(data, format?.ownedQuery ?? "Id", false, format, cards); - } else if (key[0] === "SHARED_PROJECTS") { - collectPagesEntries(data, format?.sharedQuery ?? "xs", true, format, cards); - } - } - const fromCard = cards.get(projectId)?.title ?? null; - if (fromCard !== null) return fromCard; - } + const query = cache.find?.({ queryKey, exact: true }); + const fromFind = extractProjectDetailTitle(readOwn(query?.state, "data"), format); + if (fromFind !== null) return fromFind; } - return null; + + if (!format) return null; + const cached = collectProjectsFromQueryCache(client, format); + return cached.items.get(projectId)?.title ?? null; } -/** Reads the authoritative project title from `Jk()`, `QueryClient`, or stripped `document.title`. */ +/** Reads the authoritative project title from `Jk()`, `QueryClient`, or cleaned `document.title`. */ export function readProjectTitle(projectId: string | null): string | null { const format = activeProjectMetadataFormat(); const store = resolveStoreForProject(projectId); - if (store) { - const signalName = format?.titleSignal ?? "Jk"; - const rawSignalTitle = callGetter(store.service, signalName); + if (store && format) { + const rawSignalTitle = callGetter(store.service, format.titleSignal); if (typeof rawSignalTitle === "string" && rawSignalTitle.trim()) { return rawSignalTitle.trim(); } @@ -418,7 +370,7 @@ export function readProjectTitle(projectId: string | null): string | null { if (cachedTitle !== null) return cachedTitle; } const onSubroute = /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); - if (onSubroute && store && format?.metadataQuery) { + if (onSubroute && store && format) { const querySignal = readOwn(store.service, format.metadataQuery); if (callGetter(querySignal, "data") !== undefined) { return null; @@ -434,15 +386,17 @@ async function ensureProjectMetadataLoaded( ): Promise { const querySignal = readOwn(store.service, format.metadataQuery); const client = findSharedQueryClient(store); + const projectKeys = buildCandidateProjectKeys(store.projectId, format).filter( + (key) => key[0] !== "PROJECT_DETAILS", + ); const hasMetadata = (): boolean => { if (callGetter(querySignal, "data") !== undefined) return true; - const direct = client?.ha?.(["PROJECT", store.projectId]); - if (direct !== undefined) return true; - const query = client?.queryCache?.find?.({ - queryKey: ["PROJECT", store.projectId], - exact: true, - }); - return readOwn(query?.state, "data") !== undefined; + for (const queryKey of projectKeys) { + if (client?.ha?.(queryKey) !== undefined) return true; + const query = client?.queryCache?.find?.({ queryKey, exact: true }); + if (readOwn(query?.state, "data") !== undefined) return true; + } + return false; }; if (hasMetadata()) return; @@ -451,56 +405,22 @@ async function ensureProjectMetadataLoaded( void Promise.resolve(refetch.call(querySignal)).catch(() => null); } const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; - while (Date.now() < deadline && isCurrent(store)) { - if (hasMetadata() || callBool(querySignal, "isError")) return; - await delay(QUERY_POLL_MS); - } -} - -/** Dispatches `set_project_title` through `ProjectStore` (`Lc` on `GO` or `YJ` on `$N`). */ -async function dispatchSetProjectTitle( - store: ProjectStore, - format: ProjectMetadataFormat, - desiredTitle: string, -): Promise { - if (!activeProjectStoreFormat()) { - clearProjectStore(); - throw new Error("unsupported_front_end"); - } - if (currentProjectStore(store.projectId) !== store || !isCurrent(store)) { - clearProjectStore(); - throw new Error("project_store_changed"); - } - await ensureProjectMetadataLoaded(store, format); - const payload = withMutationAliases({ - type: "set_project_title", - [format.titleField]: desiredTitle, - }); - - const mutator = resolveAsyncMutator( - store.service, - readOwn(store.service, format.metadataMutator), - ); - if (mutator) { - await mutator(payload); - return; - } - - const metadataService = readOwn(store.service, format.metadataService); - const dispatcher = readOwn(metadataService, format.metadataDispatcher); - if (typeof dispatcher === "function") { - await dispatcher.call(metadataService, store.projectId, payload); - const querySignal = readOwn(store.service, format.metadataQuery); - const refetch = readOwn(querySignal, "refetch"); - if (typeof refetch === "function") { - await Promise.resolve(refetch.call(querySignal)).catch(() => null); + while (Date.now() < deadline) { + if (currentProjectStore(store.projectId) !== store || !isCurrent(store)) { + clearProjectStore(); + throw new Error("project_store_changed"); } - return; + if (hasMetadata()) return; + if (callBool(querySignal, "isError") && !callBool(querySignal, "isFetching")) { + throw new Error("project_metadata_load_failed"); + } + await delay(QUERY_POLL_MS); } - throw new Error("metadata_mutator_missing"); + if (hasMetadata()) return; + throw new Error("project_metadata_not_loaded"); } -/** Runs a project metadata operation (`set_title`) in the pinned `ProjectStore` session. */ +/** Runs `projectMetadataOp` (`set_title`) in the pinned `ProjectStore` session. */ export async function projectMetadataOp( projectId: string, session: string, @@ -529,30 +449,65 @@ export async function projectMetadataOp( return { ok: false, error: "empty_title" }; } + let writeStarted = false; + try { + await serializeStoreMutation(async () => { + if (!activeProjectStoreFormat()) { + clearProjectStore(); + throw new Error("unsupported_front_end"); + } + if (currentProjectStore(store.projectId) !== store || !isCurrent(store)) { + clearProjectStore(); + throw new Error("project_store_changed"); + } + await ensureProjectMetadataLoaded(store, format); + const payload = withMutationAliases({ + type: "set_project_title", + [format.titleField]: desired, + }); + const mutator = resolveAsyncMutator( + store.service, + readOwn(store.service, format.metadataMutator), + ); + if (mutator) { + writeStarted = true; + await mutator(payload); + return; + } + const metadataService = readOwn(store.service, format.metadataService); + const dispatcher = readOwn(metadataService, format.metadataDispatcher); + if (typeof dispatcher === "function") { + writeStarted = true; + await dispatcher.call(metadataService, store.projectId, payload); + const querySignal = readOwn(store.service, format.metadataQuery); + const refetch = readOwn(querySignal, "refetch"); + if (typeof refetch === "function") { + await Promise.resolve(refetch.call(querySignal)).catch(() => null); + } + return; + } + throw new Error("metadata_mutator_missing"); + }); + } catch (err) { + if (!writeStarted) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + throw err; + } + const matchesDesired = (): boolean => { const signalVal = callGetter(store.service, format.titleSignal); - if (typeof signalVal === "string" && signalVal.trim() === desired) { - return true; - } - const client = findSharedQueryClient(store); - return readTitleFromQueryClient(client, projectId, format) === desired; + if (typeof signalVal === "string" && signalVal.trim() === desired) return true; + return readTitleFromQueryClient(findSharedQueryClient(store), projectId, format) === desired; }; - await serializeStoreMutation(() => dispatchSetProjectTitle(store, format, desired)); - const deadline = Date.now() + TITLE_CONFIRM_TIMEOUT_MS; while (Date.now() < deadline && projectStore(projectId, session) === store && isCurrent(store)) { - const mutatorObj = readOwn(store.service, format.metadataMutator); - const mutating = callBool(mutatorObj, "isPending"); + const mutating = callBool(readOwn(store.service, format.metadataMutator), "isPending"); if (!mutating && matchesDesired()) { await delay(120); if (matchesDesired()) { - return { - ok: true, - confirmed: true, - project_id: projectId, - title: desired, - }; + return { ok: true, confirmed: true, project_id: projectId, title: desired }; } } await delay(QUERY_POLL_MS); @@ -564,120 +519,120 @@ export async function projectMetadataOp( function isProjectsGridComponent( candidate: unknown, gridClass: unknown, - ownedKey: string, - sharedKey: string, + format: ProjectMetadataFormat, ): candidate is Record { - if (!candidate || typeof candidate !== "object" || candidate instanceof Node) { - return false; - } - if (typeof gridClass === "function" && candidate instanceof gridClass) { - return true; - } - const owned = readOwn(candidate, ownedKey); - const shared = readOwn(candidate, sharedKey); + if (!candidate || typeof candidate !== "object" || candidate instanceof Node) return false; + if (typeof gridClass === "function" && candidate instanceof gridClass) return true; + const owned = readOwn(candidate, format.ownedQuery); + const shared = readOwn(candidate, format.sharedQuery); return ( - Boolean(owned && typeof owned === "object" && typeof readOwn(owned, "fetchNextPage") === "function") && - Boolean(shared && typeof shared === "object" && typeof readOwn(shared, "fetchNextPage") === "function") + typeof readOwn(owned, "fetchNextPage") === "function" && + typeof readOwn(shared, "fetchNextPage") === "function" ); } -/** Resolves the mounted `flow-projects-grid` (`Y7`) component instance on the Flow home page. */ -async function findProjectsGridComponent(): Promise<{ - grid: Record | null; - format: ProjectMetadataFormat | undefined; -}> { - const format = activeProjectMetadataFormat(); - const ownedKey = format?.ownedQuery ?? "Id"; - const sharedKey = format?.sharedQuery ?? "xs"; +/** Locates a mounted `flow-projects-grid` component synchronously without DOM events. */ +function locateProjectsGridSync( + format: ProjectMetadataFormat, + extraMaps?: Iterable>, +): Record | null { const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); - const gridClass = format ? readOwn(namespace, format.gridClass) : undefined; - - const locate = (extraMaps?: Iterable>): Record | null => { - const host = document.querySelector("flow-projects-grid"); - if (host) { - const view = resolveLView(host); - const hit = view?.find((slot) => - isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), - ); - if (hit && typeof hit === "object") return hit as Record; - const ctx = (host as unknown as { __ngContext__?: unknown }).__ngContext__; - if (typeof ctx === "number" && extraMaps) { - for (const map of extraMaps) { - const candidateView = map.get(ctx); - if (!Array.isArray(candidateView)) continue; - const mappedHit = candidateView.find((slot) => - isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), - ); - if (mappedHit && typeof mappedHit === "object") { - runtimeState.ngLViewMap = map as Map; - return mappedHit as Record; - } + const gridClass = readOwn(namespace, format.gridClass); + const host = document.querySelector("flow-projects-grid"); + if (host) { + const directHit = resolveLView(host)?.find((slot) => + isProjectsGridComponent(slot, gridClass, format), + ); + if (directHit) return directHit; + const ctx = (host as unknown as { __ngContext__?: unknown }).__ngContext__; + if (typeof ctx === "number" && extraMaps) { + for (const map of extraMaps) { + const view = map.get(ctx); + const mappedHit = Array.isArray(view) + ? view.find((slot) => isProjectsGridComponent(slot, gridClass, format)) + : undefined; + if (mappedHit) { + runtimeState.ngLViewMap = map as Map; + return mappedHit; } } } - for (const view of runtimeState.ngLViewMap?.values() ?? []) { - if (!isLiveLView(view)) continue; - const hit = view.find((slot) => - isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), - ); - if (hit && typeof hit === "object") return hit as Record; - } - return null; - }; + } + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + if (!isLiveLView(view)) continue; + const hit = view.find((slot) => isProjectsGridComponent(slot, gridClass, format)); + if (hit) return hit; + } + return null; +} - let grid = locate(); - if (grid) return { grid, format }; - - for (let attempt = 0; attempt < 25; attempt += 1) { - const host = document.querySelector("flow-projects-grid"); - if (host) { - const captured = new Set>(); - await withMapCapture( - (map, _key, _value, write) => { - if (!write) captured.add(map); - }, - async () => { - const card = host.querySelector("flow-project-card, button"); - if (card instanceof HTMLElement) { - card.dispatchEvent(new PointerEvent("pointerenter", { bubbles: false })); - card.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false })); - } - await delay(40); - }, +/** Resolves the mounted `flow-projects-grid` (`Y7`) infinite queries on the Flow home page. */ +async function resolveProjectsGridQueries(waitMount: boolean): Promise { + const format = activeProjectMetadataFormat(); + if (!format) return null; + let grid = locateProjectsGridSync(format); + if (!grid && waitMount) { + for (let attempt = 0; attempt < 25 && !grid; attempt += 1) { + const host = document.querySelector("flow-projects-grid"); + if (host) { + const captured = new Set>(); + await withMapCapture( + (map, _key, _value, write) => { + if (!write) captured.add(map); + }, + async () => { + const card = host.querySelector("flow-project-card, button"); + if (card instanceof HTMLElement) { + card.dispatchEvent(new PointerEvent("pointerenter", { bubbles: false })); + card.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false })); + } + await delay(40); + }, + ); + grid = locateProjectsGridSync(format, captured); + if (grid) break; + } + const loading = Boolean( + document.querySelector("flow-loading-page, .projects-loading-container"), ); - grid = locate(captured); - if (grid) return { grid, format }; + if (!loading && !host && attempt >= 4) break; + await delay(120); } - const loading = Boolean( - document.querySelector("flow-loading-page, .projects-loading-container"), - ); - if (!loading && !host && attempt >= 4) break; - await delay(120); } - return { grid: locate(), format }; + if (!grid) return null; + const ownedQuery = readOwn(grid, format.ownedQuery) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, format.sharedQuery) as InfiniteQuerySignal | undefined; + const sharedEnabled = + typeof readOwn(grid, "zf") === "function" + ? callBool(grid, "zf") + : Boolean( + callGetter(sharedQuery, "data") !== undefined || + callBool(sharedQuery, "isFetching") || + callBool(sharedQuery, "hasNextPage"), + ); + return { format, ownedQuery, sharedQuery, sharedEnabled }; } /** Returns the number of loaded pages in an infinite query signal. */ -function readPagesCount(query: InfiniteQuerySignal): number { - const data = callGetter(query, "data"); - const pages = readOwn(data, "pages"); +function readPagesCount(query: InfiniteQuerySignal | undefined): number { + const pages = readOwn(callGetter(query, "data"), "pages"); return Array.isArray(pages) ? pages.length : 0; } /** Waits until an infinite query finishes its initial load or in-flight next-page fetch. */ async function waitInfiniteQueryIdle( - query: InfiniteQuerySignal, + query: InfiniteQuerySignal | undefined, waitInitial: boolean, ): Promise { + if (!query) return; const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; while (Date.now() < deadline) { if (callBool(query, "isError")) return; const fetchingNext = callBool(query, "isFetchingNextPage"); - const placeholder = callBool(query, "isPlaceholderData"); const initialBusy = waitInitial && readPagesCount(query) === 0 && - (callBool(query, "isFetching") || placeholder); + (callBool(query, "isFetching") || callBool(query, "isPlaceholderData")); if (!fetchingNext && !initialBusy) return; await delay(QUERY_POLL_MS); } @@ -692,9 +647,7 @@ async function fetchAllInfinitePages( await waitInfiniteQueryIdle(query, true); for (let page = 0; page < MAX_GRID_PAGES; page += 1) { await waitInfiniteQueryIdle(query, false); - if (!callBool(query, "hasNextPage") || callBool(query, "isFetchNextPageError")) { - break; - } + if (!callBool(query, "hasNextPage") || callBool(query, "isFetchNextPageError")) break; const beforePages = readPagesCount(query); try { await Promise.resolve(query.fetchNextPage()); @@ -702,19 +655,14 @@ async function fetchAllInfinitePages( break; } await waitInfiniteQueryIdle(query, false); - const afterPages = readPagesCount(query); - if (afterPages <= beforePages && callBool(query, "hasNextPage")) { - break; - } + if (readPagesCount(query) <= beforePages && callBool(query, "hasNextPage")) break; } } -/** Collects cached dashboard project cards from `QueryClient` when `PROJECTS` or `SHARED_PROJECTS` exist. */ +/** Collects cached dashboard project cards from `QueryClient` without triggering fetches. */ function collectProjectsFromQueryCache( client: QueryClient | undefined, - ownedKey: string, - sharedKey: string, - format: ProjectMetadataFormat | undefined, + format: ProjectMetadataFormat, ): { sawProjectsQuery: boolean; items: Map } { const items = new Map(); let sawProjectsQuery = false; @@ -728,10 +676,10 @@ function collectProjectsFromQueryCache( const data = readOwn(readOwn(query, "state"), "data"); if (key[0] === "PROJECTS") { sawProjectsQuery = true; - collectPagesEntries(data, ownedKey, false, format, items); + collectPagesEntries(data, format.ownedQuery, false, format, items); } else if (key[0] === "SHARED_PROJECTS") { sawProjectsQuery = true; - collectPagesEntries(data, sharedKey, true, format, items); + collectPagesEntries(data, format.sharedQuery, true, format, items); } } return { sawProjectsQuery, items }; @@ -739,92 +687,68 @@ function collectProjectsFromQueryCache( /** Inspects `flow-projects-grid` (`PROJECTS` and `SHARED_PROJECTS`), fetches all pages, and reads cached card protobufs. */ export async function listCachedProjects(): Promise { - const { grid, format } = await findProjectsGridComponent(); - const ownedKey = format?.ownedQuery ?? "Id"; - const sharedKey = format?.sharedQuery ?? "xs"; - - if (grid) { - const ownedQuery = readOwn(grid, ownedKey) as InfiniteQuerySignal | undefined; - const sharedQuery = readOwn(grid, sharedKey) as InfiniteQuerySignal | undefined; - const sharedEnabled = - typeof readOwn(grid, "zf") === "function" - ? callBool(grid, "zf") - : Boolean( - callGetter(sharedQuery, "data") !== undefined || - callBool(sharedQuery, "isFetching") || - callBool(sharedQuery, "hasNextPage"), - ); - + const resolved = await resolveProjectsGridQueries(true); + if (resolved) { + const { format, ownedQuery, sharedQuery, sharedEnabled } = resolved; await Promise.all([ fetchAllInfinitePages(ownedQuery, true), fetchAllInfinitePages(sharedQuery, sharedEnabled), ]); - const items = new Map(); - collectPagesEntries(callGetter(ownedQuery, "data"), ownedKey, false, format, items); + collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); if (sharedEnabled) { - collectPagesEntries(callGetter(sharedQuery, "data"), sharedKey, true, format, items); + collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); } return [...items.values()]; } - - const cached = collectProjectsFromQueryCache( - findSharedQueryClient(null), - ownedKey, - sharedKey, - format, - ); + const format = activeProjectMetadataFormat(); + if (!format) return null; + const cached = collectProjectsFromQueryCache(findSharedQueryClient(null), format); return cached.sawProjectsQuery ? [...cached.items.values()] : null; } /** Reads currently loaded dashboard card protobufs without triggering additional pagination. */ export function snapshotLoadedGridProjects(): Map { const format = activeProjectMetadataFormat(); - const ownedKey = format?.ownedQuery ?? "Id"; - const sharedKey = format?.sharedQuery ?? "xs"; - const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); - const gridClass = format ? readOwn(namespace, format.gridClass) : undefined; - const items = new Map(); - - const host = document.querySelector("flow-projects-grid"); - const view = host ? resolveLView(host) : null; - const grid = view?.find((slot) => - isProjectsGridComponent(slot, gridClass, ownedKey, sharedKey), - ) as Record | undefined; - + if (!format) return new Map(); + const grid = locateProjectsGridSync(format); if (grid) { - const ownedQuery = readOwn(grid, ownedKey); - const sharedQuery = readOwn(grid, sharedKey); - collectPagesEntries(callGetter(ownedQuery, "data"), ownedKey, false, format, items); - collectPagesEntries(callGetter(sharedQuery, "data"), sharedKey, true, format, items); + const items = new Map(); + const ownedQuery = readOwn(grid, format.ownedQuery); + const sharedQuery = readOwn(grid, format.sharedQuery); + collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); + collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); return items; } + return collectProjectsFromQueryCache(findSharedQueryClient(null), format).items; +} - return collectProjectsFromQueryCache(findSharedQueryClient(null), ownedKey, sharedKey, format) - .items; +/** Returns `true` when `flow-projects-grid` currently has an in-flight `PROJECTS` or `SHARED_PROJECTS` fetch. */ +export function isProjectsGridFetching(): boolean { + const format = activeProjectMetadataFormat(); + if (!format) return false; + const grid = locateProjectsGridSync(format); + if (!grid) return false; + const ownedBusy = callBool(readOwn(grid, format.ownedQuery), "isFetching"); + const sharedBusy = + callBool(grid, "zf") && callBool(readOwn(grid, format.sharedQuery), "isFetching"); + return ownedBusy || sharedBusy; } /** Advances `flow-projects-grid` by one page when `hasNextPage()` is true, returning whether a page was fetched. */ export async function advanceProjectsGridPage(): Promise { - const { grid, format } = await findProjectsGridComponent(); - if (!grid) return false; - const ownedKey = format?.ownedQuery ?? "Id"; - const sharedKey = format?.sharedQuery ?? "xs"; - const ownedQuery = readOwn(grid, ownedKey) as InfiniteQuerySignal | undefined; - const sharedQuery = readOwn(grid, sharedKey) as InfiniteQuerySignal | undefined; - const sharedEnabled = - typeof readOwn(grid, "zf") === "function" - ? callBool(grid, "zf") - : Boolean(callBool(sharedQuery, "hasNextPage")); + const resolved = await resolveProjectsGridQueries(true); + if (!resolved) return false; + const { ownedQuery, sharedQuery, sharedEnabled } = resolved; await Promise.all([ - ownedQuery ? waitInfiniteQueryIdle(ownedQuery, true) : Promise.resolve(), - sharedQuery && sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, true) : Promise.resolve(), + waitInfiniteQueryIdle(ownedQuery, true), + sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, true) : Promise.resolve(), ]); const tasks: Array> = []; - const beforeOwned = ownedQuery ? readPagesCount(ownedQuery) : 0; - const beforeShared = sharedQuery ? readPagesCount(sharedQuery) : 0; + const beforeOwned = readPagesCount(ownedQuery); + const beforeShared = readPagesCount(sharedQuery); if ( ownedQuery && @@ -847,11 +771,9 @@ export async function advanceProjectsGridPage(): Promise { await Promise.all(tasks); await Promise.all([ - ownedQuery ? waitInfiniteQueryIdle(ownedQuery, false) : Promise.resolve(), - sharedQuery && sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, false) : Promise.resolve(), + waitInfiniteQueryIdle(ownedQuery, false), + sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, false) : Promise.resolve(), ]); - const afterOwned = ownedQuery ? readPagesCount(ownedQuery) : 0; - const afterShared = sharedQuery ? readPagesCount(sharedQuery) : 0; - return afterOwned > beforeOwned || afterShared > beforeShared; + return readPagesCount(ownedQuery) > beforeOwned || readPagesCount(sharedQuery) > beforeShared; } diff --git a/ts/project_nav.ts b/ts/project_nav.ts index 89fdf37..baf59c7 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_project_root") { + const strictRoot = action === "exit_to_project_root"; const activeProject = (): string | undefined => /\/project\/([^/?#]+)/.exec(location.pathname || "")?.[1]; const pid = activeProject(); @@ -96,38 +97,49 @@ export async function projectNav(action: string): Promise { const workspace = buildProjectUrl(pid); const isOriginalProject = (): boolean => activeProject() === pid && buildProjectUrl(pid) === workspace; - const isSubRoute = (): boolean => - /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); + const isCollectionRoot = (): boolean => { + const match = /\/project\/[^/?#]+\/(.+)/.exec( + (location.pathname || "").replace(/\/+$/, ""), + ); + return Boolean(match && /^collection\/[^/?#]+$/.test(match[1])); + }; + const isSubRoute = (): boolean => { + const hasChild = /\/project\/[^/?#]+\/[^/?#]+/.test(location.pathname || ""); + if (!hasChild) return false; + return strictRoot || !isCollectionRoot(); + }; 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); 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()) { + 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) { diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index a633e84..ec27996 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -15,6 +15,7 @@ import { projectTitleFormat } from "./frontend_builds"; import { MAX_GRID_PAGES, advanceProjectsGridPage, + isProjectsGridFetching, listCachedProjects, snapshotLoadedGridProjects, } from "./project_metadata"; @@ -32,41 +33,35 @@ interface ScannedProjectCard { _card: HTMLElement; } -/** Material icon ligatures excluded from card and anchor title extraction. */ -const ICON_LIGATURE_RE = - /^(?:group|edit|more_vert|more_horiz|delete|share|visibility|visibility_off|lock|public|check|close|add|arrow_back|arrow_forward|folder|home_storage|push_pin)$/i; - -/** Selector matching icon and action elements stripped before reading card or link text. */ +/** Selector matching icon, form, and action elements excluded when reading card or link text. */ const STRIPPED_LABEL_NODES = - 'mat-icon, flow-material-icon, .shared-project-icon, .google-symbols, .material-icons, button, [role="button"], [aria-hidden="true"]'; + 'mat-icon, flow-material-icon, .shared-project-icon, .google-symbols, .material-icons, [class*="material-symbols"], button, [role="button"], [aria-hidden="true"], .project-card-edit-form'; /** Selector matching non-header containers where fallback `set_title` must never edit inputs. */ const FORBIDDEN_TITLE_ANCESTOR = - 'mat-sidenav, [flow-sidenav], aside, flow-project-nav-list, flow-agent-panel, flow-applet-chat-sidebar, flow-project-card, flow-grid-tile-container, flow-character-edit-header, flow-character-header, flow-applet-view-header, main, [role="dialog"], .cdk-overlay-container'; + 'mat-sidenav, [flow-sidenav], aside, flow-project-nav-list, flow-agent-panel, flow-applet-chat-sidebar, flow-project-card, flow-grid-tile-container, flow-character-edit-header, flow-character-header, flow-applet-view-header, flow-scene-editor, [role="dialog"], .cdk-overlay-container'; /** Selector matching workspace header containers that host the legacy project title input. */ const WORKSPACE_HEADER_SELECTOR = - "flow-navigation-header, flow-project-header, nav.nav-header, header.header-base, header"; + "flow-navigation-header, flow-tile-view-header, flow-project-header, nav.nav-header, header.header-base, header"; -/** Extracts clean text from `node` after stripping `mat-icon` ligatures and action buttons. */ +/** Extracts clean text from `node` via `TreeWalker` after skipping icon and action elements. */ function cleanCardOrLinkTitle(node: Element | null): string | null { - if (!node) return null; - const clone = node.cloneNode(true); - if (clone instanceof Element) { - for (const icon of Array.from(clone.querySelectorAll(STRIPPED_LABEL_NODES))) { - icon.remove(); - } - const line = (clone.textContent || "") - .split(/\r?\n/) - .map((part) => part.trim()) - .find((part) => part.length > 0 && !ICON_LIGATURE_RE.test(part)); - if (line) return line; + if (!node || node.matches(STRIPPED_LABEL_NODES)) return null; + const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT); + const parts: string[] = []; + for (let cur = walker.nextNode(); cur; cur = walker.nextNode()) { + const parent = cur.parentElement; + if (parent && parent.closest(STRIPPED_LABEL_NODES)) continue; + const val = cur.nodeValue; + if (val) parts.push(val); } - const fallback = elText(node) + const line = parts + .join("") .split(/\r?\n/) .map((part) => part.trim()) - .find((part) => part.length > 0 && !ICON_LIGATURE_RE.test(part)); - return fallback || null; + .find((part) => part.length > 0); + return line || null; } /** Scrolls `.load-more-sentinel` and its scrollable ancestors so `IntersectionObserver` fires. */ @@ -189,35 +184,43 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } - 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(60); + const rawCards = Array.from(document.querySelectorAll("flow-project-card")); + const needsNgProbe = rawCards.some((card) => { + if (card.querySelector('a[href*="/project/"]')) return false; + return !card.getAttributeNames().some((attr) => UUID_RE.test(card.getAttribute(attr) || "")); }); + const seenMaps = new Set>(); + if (needsNgProbe) { + await withMapCapture( + (map, _key, _value, write) => { + if (!write) seenMaps.add(map); + }, + async () => { + for (const card of rawCards.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(60); + }, + ); + } const cachedById = snapshotLoadedGridProjects(); const byId = new Map(); - const cards = Array.from(document.querySelectorAll("flow-project-card")); - for (const card of cards) { + for (const card of rawCards) { if (!(card instanceof HTMLElement)) continue; const link = card.querySelector('a[href*="/project/"]'); const href = link?.getAttribute("href") || ""; @@ -253,11 +256,14 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } const cachedTitle = pid ? (cachedById.get(pid)?.title ?? null) : null; - const titleNode = - card.querySelector(".project-title-text") || - card.querySelector('[class*="title"]:not(.project-card-edit-form *), h2, h3, h4') || - card; - const domTitle = cleanCardOrLinkTitle(titleNode); + const explicitTitleNode = card.querySelector(".project-title-text"); + const domTitle = explicitTitleNode + ? cleanCardOrLinkTitle(explicitTitleNode) + : cleanCardOrLinkTitle( + card.querySelector('[class*="title"]:not(.project-card-edit-form *), h2, h3, h4') || + link || + card, + ); const resolvedTitle = cachedTitle ?? domTitle; const key = pid || `card:${resolvedTitle || byId.size}`; if (!byId.has(key)) { @@ -554,9 +560,7 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { if (!hit || !hit._card) { return { ok: false, error: "project_card_not_found" }; } - const beforeCached = await listCachedProjects(); - const beforePool = beforeCached ?? items; - const beforeMatches = beforePool.filter(matchesTarget).length; + const beforeMatches = items.filter(matchesTarget).length; const deletedId = hit.id; const card = hit._card; card.scrollIntoView({ block: "center" }); @@ -640,9 +644,8 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { await delay(100); } const isRemovedNow = async (): Promise => { - if (document.body.contains(card)) return false; - const currentCached = await listCachedProjects(); - const entries = currentCached ?? (await scanCards(false)); + if (document.body.contains(card) || isProjectsGridFetching()) return false; + const entries = await scanCards(false); return deletedId ? !entries.some((p) => p.id === deletedId) : entries.filter(matchesTarget).length < beforeMatches; From 9b66a8640c92f7fda0313b54e8e294ba5419f88c Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:03:07 +0000 Subject: [PATCH 3/3] refactor(flow): split dashboard grid cache from project metadata --- ts/frontend_builds.ts | 12 +- ts/frontend_nov29.ts | 3 +- ts/project_metadata.ts | 484 ++------------------------------------ ts/projects_grid_cache.ts | 484 ++++++++++++++++++++++++++++++++++++++ ts/projects_ops.ts | 2 +- ts/types.ts | 4 +- 6 files changed, 519 insertions(+), 470 deletions(-) create mode 100644 ts/projects_grid_cache.ts diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 78ec80e..d0d46fb 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -969,8 +969,9 @@ const VERIFIED_BUILDS: ReadonlyMap = new Map([ metadataService: "Rb", metadataServiceClass: "$N", metadataQuery: "Ag", metadataMutator: "Lc", metadataDispatcher: "YJ", titleSignal: "Jk", titleField: "Sg", projectKey: "pM", projectInfoGetter: "AE", projectTitleGetter: "tI", gridClass: "Y7", - ownedQuery: "Id", sharedQuery: "xs", sharedEnabled: "zf", cardIdGetter: "Ub", - cardMetadataGetter: "getMetadata", cardTitleGetter: "Qd", sharedProjectGetter: "Jn", + ownedQuery: "Id", sharedQuery: "xs", sharedEnabled: "zf", gridFlags: "ha", + cardIdGetter: "Ub", cardMetadataGetter: "getMetadata", cardTitleGetter: "Qd", + sharedProjectGetter: "Jn", }, operations: { collection_write: { @@ -1052,10 +1053,9 @@ export function withMutationAliases(payload: Record): Record unknown; - /** Returns true while any fetch is in flight. */ - isFetching?: () => boolean; - /** Returns true while the query displays placeholder data. */ - isPlaceholderData?: () => boolean; - /** Returns true when the query encountered an error. */ - isError?: () => boolean; - /** Returns true when another page token is available. */ - hasNextPage?: () => boolean; - /** Returns true while `fetchNextPage()` is in flight. */ - isFetchingNextPage?: () => boolean; - /** Returns true when the most recent next-page fetch failed. */ - isFetchNextPageError?: () => boolean; - /** Requests the next page from the backend. */ - fetchNextPage?: () => Promise; -} - -/** Resolved infinite-query handles for a mounted `flow-projects-grid` component. */ -interface ResolvedGridQueries { - /** Verified metadata format for the active build. */ - format: ProjectMetadataFormat; - /** Owned `PROJECTS` infinite query signal. */ - ownedQuery: InfiniteQuerySignal | undefined; - /** Shared `SHARED_PROJECTS` infinite query signal. */ - sharedQuery: InfiniteQuerySignal | undefined; - /** True when the `SHARED_PROJECTS` query is enabled on the grid. */ - sharedEnabled: boolean; -} - -/** Calls a zero-argument boolean method on `target` when present. */ -function callBool(target: unknown, key: string): boolean { - const fn = readOwn(target, key); - if (typeof fn === "function") { - try { - return Boolean(fn.call(target)); - } catch { - return false; - } - } - return fn === true; -} - -/** Calls a zero-argument getter method on `target` when present. */ -function callGetter(target: unknown, key: string): unknown { - const fn = readOwn(target, key); - if (typeof fn !== "function") return undefined; - try { - return fn.call(target); - } catch { - return undefined; - } -} - /** Strips `"Google Flow - "` wrappers and generic `"Google Flow"` titles from `document.title`. */ export function cleanFlowDocumentTitle(raw: string | null | undefined): string | null { const trimmed = typeof raw === "string" ? raw.trim() : ""; @@ -188,14 +116,7 @@ function resolveStoreForProject(projectId: string | null): ProjectStore | null { return null; } -/** Checks whether `candidate` exposes `QueryClient.queryCache.find`. */ -function asQueryClient(candidate: unknown): QueryClient | undefined { - if (!candidate || typeof candidate !== "object") return undefined; - const client = candidate as QueryClient; - return typeof client.queryCache?.find === "function" ? client : undefined; -} - -/** Resolves the shared `QueryClient` from `store`, Angular views, or page components. */ +/** Resolves the shared `QueryClient` from `store` or captured Angular views. */ function findSharedQueryClient(store: ProjectStore | null): QueryClient | undefined { if (store) { const tilesClient = asQueryClient( @@ -209,101 +130,7 @@ function findSharedQueryClient(store: ProjectStore | null): QueryClient | undefi if (metaClient) return metaClient; } } - for (const view of runtimeState.ngLViewMap?.values() ?? []) { - if (!isLiveLView(view)) continue; - for (const slot of view) { - if (!slot || typeof slot !== "object" || slot instanceof Node) continue; - const direct = asQueryClient(slot); - if (direct) return direct; - if (typeof (slot as AgentInjector).get === "function") { - const resolved = resolveQueryClient(slot as AgentInjector); - if (resolved) return resolved; - } - const viaPage = resolveQueryClient({}, slot as Record); - if (viaPage) return viaPage; - } - } - return undefined; -} - -/** Calls `getterName` on a protobuf message and returns a trimmed non-empty string, or `null`. */ -function readProtoString(msg: unknown, getterName: string | undefined): string | null { - if (!msg || typeof msg !== "object" || !getterName) return null; - const val = callGetter(msg, getterName); - return typeof val === "string" && val.trim() ? val.trim() : null; -} - -/** Extracts a project title from a cached `PROJECT` or `PROJECT_DETAILS` message. */ -function extractProjectDetailTitle( - data: unknown, - format: ProjectMetadataFormat | undefined, -): string | null { - if (!data || typeof data !== "object") return null; - if (format) { - const fromInfo = readProtoString( - callGetter(data, format.projectInfoGetter), - format.projectTitleGetter, - ); - if (fromInfo !== null) return fromInfo; - const fromMeta = readProtoString( - callGetter(data, format.cardMetadataGetter), - format.cardTitleGetter, - ); - if (fromMeta !== null) return fromMeta; - } - const directTitle = readOwn(data, "title") ?? readOwn(data, "displayName"); - return typeof directTitle === "string" && directTitle.trim() ? directTitle.trim() : null; -} - -/** Extracts `{ id, title }` from one owned or shared project card protobuf entry. */ -function extractCardProtobuf( - rawEntry: unknown, - isShared: boolean, - format: ProjectMetadataFormat, -): { id: string; title: string | null } | null { - if (!rawEntry || typeof rawEntry !== "object") return null; - const unwrapped = isShared ? callGetter(rawEntry, format.sharedProjectGetter) : rawEntry; - if (!unwrapped || typeof unwrapped !== "object") return null; - - let id = readProtoString(unwrapped, format.cardIdGetter); - if (!id) { - const plain = readOwn(unwrapped, "projectId"); - if (typeof plain === "string" && UUID_EXACT_RE.test(plain.trim())) { - id = plain.trim(); - } - } - if (!id) return null; - - const meta = callGetter(unwrapped, format.cardMetadataGetter); - const title = - readProtoString(meta, format.cardTitleGetter) ?? - extractProjectDetailTitle(unwrapped, format); - return { id, title }; -} - -/** Reads cached project entries from an infinite-query `data` value (`{ pages: [...] }`). */ -function collectPagesEntries( - data: unknown, - itemsKey: string, - isShared: boolean, - format: ProjectMetadataFormat, - into: Map, -): void { - const pages = readOwn(data, "pages"); - if (!Array.isArray(pages)) return; - for (const page of pages) { - const items = readOwn(page, itemsKey); - if (!Array.isArray(items)) continue; - for (const rawItem of items) { - const parsed = extractCardProtobuf(rawItem, isShared, format); - if (!parsed || into.has(parsed.id)) continue; - into.set(parsed.id, { - id: parsed.id, - title: parsed.title, - url: buildProjectUrl(parsed.id), - }); - } - } + return findLiveQueryClient(); } /** Builds the candidate `QueryClient` keys for `projectId`. */ @@ -354,7 +181,7 @@ function readTitleFromQueryClient( return cached.items.get(projectId)?.title ?? null; } -/** Reads the authoritative project title from `Jk()`, `QueryClient`, or cleaned `document.title`. */ +/** Reads the authoritative project title from `ProjectStore`, `QueryClient`, or cleaned `document.title`. */ export function readProjectTitle(projectId: string | null): string | null { const format = activeProjectMetadataFormat(); const store = resolveStoreForProject(projectId); @@ -379,7 +206,7 @@ export function readProjectTitle(projectId: string | null): string | null { return cleanFlowDocumentTitle(document.title); } -/** Waits for the store's `PROJECT` metadata query (`Ag`) to populate initial data before mutating. */ +/** Waits for the store's `PROJECT` metadata query to populate initial data before mutating. */ async function ensureProjectMetadataLoaded( store: ProjectStore, format: ProjectMetadataFormat, @@ -404,7 +231,7 @@ async function ensureProjectMetadataLoaded( if (typeof refetch === "function" && !callBool(querySignal, "isFetching")) { void Promise.resolve(refetch.call(querySignal)).catch(() => null); } - const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; + const deadline = Date.now() + METADATA_SETTLE_TIMEOUT_MS; while (Date.now() < deadline) { if (currentProjectStore(store.projectId) !== store || !isCurrent(store)) { clearProjectStore(); @@ -414,7 +241,7 @@ async function ensureProjectMetadataLoaded( if (callBool(querySignal, "isError") && !callBool(querySignal, "isFetching")) { throw new Error("project_metadata_load_failed"); } - await delay(QUERY_POLL_MS); + await delay(METADATA_POLL_MS); } if (hasMetadata()) return; throw new Error("project_metadata_not_loaded"); @@ -510,272 +337,7 @@ export async function projectMetadataOp( return { ok: true, confirmed: true, project_id: projectId, title: desired }; } } - await delay(QUERY_POLL_MS); + await delay(METADATA_POLL_MS); } return { ok: false, error: "project_title_not_confirmed" }; } - -/** Checks whether `candidate` is a `flow-projects-grid` (`Y7`) component instance. */ -function isProjectsGridComponent( - candidate: unknown, - gridClass: unknown, - format: ProjectMetadataFormat, -): candidate is Record { - if (!candidate || typeof candidate !== "object" || candidate instanceof Node) return false; - if (typeof gridClass === "function" && candidate instanceof gridClass) return true; - const owned = readOwn(candidate, format.ownedQuery); - const shared = readOwn(candidate, format.sharedQuery); - return ( - typeof readOwn(owned, "fetchNextPage") === "function" && - typeof readOwn(shared, "fetchNextPage") === "function" - ); -} - -/** Locates a mounted `flow-projects-grid` component synchronously without DOM events. */ -function locateProjectsGridSync( - format: ProjectMetadataFormat, - extraMaps?: Iterable>, -): Record | null { - const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); - const gridClass = readOwn(namespace, format.gridClass); - const host = document.querySelector("flow-projects-grid"); - if (host) { - const directHit = resolveLView(host)?.find((slot) => - isProjectsGridComponent(slot, gridClass, format), - ); - if (directHit) return directHit; - const ctx = (host as unknown as { __ngContext__?: unknown }).__ngContext__; - if (typeof ctx === "number" && extraMaps) { - for (const map of extraMaps) { - const view = map.get(ctx); - const mappedHit = Array.isArray(view) - ? view.find((slot) => isProjectsGridComponent(slot, gridClass, format)) - : undefined; - if (mappedHit) { - runtimeState.ngLViewMap = map as Map; - return mappedHit; - } - } - } - } - for (const view of runtimeState.ngLViewMap?.values() ?? []) { - if (!isLiveLView(view)) continue; - const hit = view.find((slot) => isProjectsGridComponent(slot, gridClass, format)); - if (hit) return hit; - } - return null; -} - -/** Resolves the mounted `flow-projects-grid` (`Y7`) infinite queries on the Flow home page. */ -async function resolveProjectsGridQueries(waitMount: boolean): Promise { - const format = activeProjectMetadataFormat(); - if (!format) return null; - let grid = locateProjectsGridSync(format); - if (!grid && waitMount) { - for (let attempt = 0; attempt < 25 && !grid; attempt += 1) { - const host = document.querySelector("flow-projects-grid"); - if (host) { - const captured = new Set>(); - await withMapCapture( - (map, _key, _value, write) => { - if (!write) captured.add(map); - }, - async () => { - const card = host.querySelector("flow-project-card, button"); - if (card instanceof HTMLElement) { - card.dispatchEvent(new PointerEvent("pointerenter", { bubbles: false })); - card.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false })); - } - await delay(40); - }, - ); - grid = locateProjectsGridSync(format, captured); - if (grid) break; - } - const loading = Boolean( - document.querySelector("flow-loading-page, .projects-loading-container"), - ); - if (!loading && !host && attempt >= 4) break; - await delay(120); - } - } - if (!grid) return null; - const ownedQuery = readOwn(grid, format.ownedQuery) as InfiniteQuerySignal | undefined; - const sharedQuery = readOwn(grid, format.sharedQuery) as InfiniteQuerySignal | undefined; - const sharedFlag = format.sharedEnabled ?? "zf"; - const sharedEnabled = - typeof readOwn(grid, sharedFlag) === "function" - ? callBool(grid, sharedFlag) - : Boolean( - callGetter(sharedQuery, "data") !== undefined || - callBool(sharedQuery, "isFetching") || - callBool(sharedQuery, "hasNextPage"), - ); - return { format, ownedQuery, sharedQuery, sharedEnabled }; -} - -/** Returns the number of loaded pages in an infinite query signal. */ -function readPagesCount(query: InfiniteQuerySignal | undefined): number { - const pages = readOwn(callGetter(query, "data"), "pages"); - return Array.isArray(pages) ? pages.length : 0; -} - -/** Waits until an infinite query finishes its initial load or in-flight next-page fetch. */ -async function waitInfiniteQueryIdle( - query: InfiniteQuerySignal | undefined, - waitInitial: boolean, -): Promise { - if (!query) return; - const deadline = Date.now() + QUERY_SETTLE_TIMEOUT_MS; - while (Date.now() < deadline) { - if (callBool(query, "isError")) return; - const fetchingNext = callBool(query, "isFetchingNextPage"); - const initialBusy = - waitInitial && - readPagesCount(query) === 0 && - (callBool(query, "isFetching") || callBool(query, "isPlaceholderData")); - if (!fetchingNext && !initialBusy) return; - await delay(QUERY_POLL_MS); - } -} - -/** Fetches all remaining pages of `query` up to `MAX_GRID_PAGES` (`50`). */ -async function fetchAllInfinitePages( - query: InfiniteQuerySignal | undefined, - enabled: boolean, -): Promise { - if (!query || !enabled || typeof query.fetchNextPage !== "function") return; - await waitInfiniteQueryIdle(query, true); - for (let page = 0; page < MAX_GRID_PAGES; page += 1) { - await waitInfiniteQueryIdle(query, false); - if (!callBool(query, "hasNextPage") || callBool(query, "isFetchNextPageError")) break; - const beforePages = readPagesCount(query); - try { - await Promise.resolve(query.fetchNextPage()); - } catch { - break; - } - await waitInfiniteQueryIdle(query, false); - if (readPagesCount(query) <= beforePages && callBool(query, "hasNextPage")) break; - } -} - -/** Collects cached dashboard project cards from `QueryClient` without triggering fetches. */ -function collectProjectsFromQueryCache( - client: QueryClient | undefined, - format: ProjectMetadataFormat, -): { sawProjectsQuery: boolean; items: Map } { - const items = new Map(); - let sawProjectsQuery = false; - const findAll = readOwn(client?.queryCache, "findAll"); - if (typeof findAll !== "function") return { sawProjectsQuery, items }; - const queries: unknown = findAll.call(client?.queryCache); - if (!Array.isArray(queries)) return { sawProjectsQuery, items }; - for (const query of queries) { - const key = readOwn(query, "queryKey"); - if (!Array.isArray(key) || typeof key[0] !== "string") continue; - const data = readOwn(readOwn(query, "state"), "data"); - if (key[0] === "PROJECTS") { - sawProjectsQuery = true; - collectPagesEntries(data, format.ownedQuery, false, format, items); - } else if (key[0] === "SHARED_PROJECTS") { - sawProjectsQuery = true; - collectPagesEntries(data, format.sharedQuery, true, format, items); - } - } - return { sawProjectsQuery, items }; -} - -/** Inspects `flow-projects-grid` (`PROJECTS` and `SHARED_PROJECTS`), fetches all pages, and reads cached card protobufs. */ -export async function listCachedProjects(): Promise { - const resolved = await resolveProjectsGridQueries(true); - if (resolved) { - const { format, ownedQuery, sharedQuery, sharedEnabled } = resolved; - await Promise.all([ - fetchAllInfinitePages(ownedQuery, true), - fetchAllInfinitePages(sharedQuery, sharedEnabled), - ]); - const items = new Map(); - collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); - if (sharedEnabled) { - collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); - } - return [...items.values()]; - } - const format = activeProjectMetadataFormat(); - if (!format) return null; - const cached = collectProjectsFromQueryCache(findSharedQueryClient(null), format); - return cached.sawProjectsQuery ? [...cached.items.values()] : null; -} - -/** Reads currently loaded dashboard card protobufs without triggering additional pagination. */ -export function snapshotLoadedGridProjects(): Map { - const format = activeProjectMetadataFormat(); - if (!format) return new Map(); - const grid = locateProjectsGridSync(format); - if (grid) { - const items = new Map(); - const ownedQuery = readOwn(grid, format.ownedQuery); - const sharedQuery = readOwn(grid, format.sharedQuery); - collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); - collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); - return items; - } - return collectProjectsFromQueryCache(findSharedQueryClient(null), format).items; -} - -/** Returns `true` when `flow-projects-grid` currently has an in-flight `PROJECTS` or `SHARED_PROJECTS` fetch. */ -export function isProjectsGridFetching(): boolean { - const format = activeProjectMetadataFormat(); - if (!format) return false; - const grid = locateProjectsGridSync(format); - if (!grid) return false; - const ownedBusy = callBool(readOwn(grid, format.ownedQuery), "isFetching"); - const sharedFlag = format.sharedEnabled ?? "zf"; - const sharedBusy = - callBool(grid, sharedFlag) && callBool(readOwn(grid, format.sharedQuery), "isFetching"); - return ownedBusy || sharedBusy; -} - -/** Advances `flow-projects-grid` by one page when `hasNextPage()` is true, returning whether a page was fetched. */ -export async function advanceProjectsGridPage(): Promise { - const resolved = await resolveProjectsGridQueries(true); - if (!resolved) return false; - const { ownedQuery, sharedQuery, sharedEnabled } = resolved; - - await Promise.all([ - waitInfiniteQueryIdle(ownedQuery, true), - sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, true) : Promise.resolve(), - ]); - - const tasks: Array> = []; - const beforeOwned = readPagesCount(ownedQuery); - const beforeShared = readPagesCount(sharedQuery); - - if ( - ownedQuery && - typeof ownedQuery.fetchNextPage === "function" && - callBool(ownedQuery, "hasNextPage") && - !callBool(ownedQuery, "isFetchNextPageError") - ) { - tasks.push(Promise.resolve(ownedQuery.fetchNextPage()).catch(() => null)); - } - if ( - sharedEnabled && - sharedQuery && - typeof sharedQuery.fetchNextPage === "function" && - callBool(sharedQuery, "hasNextPage") && - !callBool(sharedQuery, "isFetchNextPageError") - ) { - tasks.push(Promise.resolve(sharedQuery.fetchNextPage()).catch(() => null)); - } - if (tasks.length === 0) return false; - - await Promise.all(tasks); - await Promise.all([ - waitInfiniteQueryIdle(ownedQuery, false), - sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, false) : Promise.resolve(), - ]); - - return readPagesCount(ownedQuery) > beforeOwned || readPagesCount(sharedQuery) > beforeShared; -} diff --git a/ts/projects_grid_cache.ts b/ts/projects_grid_cache.ts new file mode 100644 index 0000000..cdd0efa --- /dev/null +++ b/ts/projects_grid_cache.ts @@ -0,0 +1,484 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Read and paginate home dashboard project card queries from Angular views and QueryClient. + +import { resolveQueryClient } from "./agent_settings"; +import type { AgentInjector, QueryClient } from "./agent_settings"; +import { + buildProjectUrl, + isLiveLView, + readOwn, + resolveLView, + withMapCapture, +} from "./angular"; +import { delay } from "./dom"; +import { activeProjectMetadataFormat } from "./frontend_builds"; +import type { ProjectMetadataFormat } from "./frontend_builds"; +import { runtimeState } from "./state"; +import type { NgLView } from "./types"; + +/** Maximum number of pagination requests allowed per dashboard query or sentinel loop. */ +export const MAX_GRID_PAGES = 50; + +/** Maximum wait in milliseconds for initial grid queries to settle. */ +const GRID_QUERY_SETTLE_TIMEOUT_MS = 8_000; + +/** Polling interval in milliseconds while waiting on infinite-page queries. */ +const GRID_QUERY_POLL_MS = 80; + +/** Strict UUID pattern used when reading plain `projectId` properties. */ +const UUID_EXACT_RE = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** Normalized project summary read from cached dashboard card protobufs. */ +export interface CachedProjectItem { + /** Project ID read from the card protobuf. */ + id: string; + /** Project title read from the card metadata protobuf, or null when unset. */ + title: string | null; + /** Canonical workspace URL for the project. */ + url: string; +} + +/** Infinite query signal surface exposed on `flow-projects-grid`. */ +interface InfiniteQuerySignal { + /** Returns cached infinite-query data (`{ pages: unknown[] }`). */ + data?: () => unknown; + /** Returns true while any fetch is in flight. */ + isFetching?: () => boolean; + /** Returns true while the query displays placeholder data. */ + isPlaceholderData?: () => boolean; + /** Returns true when the query encountered an error. */ + isError?: () => boolean; + /** Returns true when another page token is available. */ + hasNextPage?: () => boolean; + /** Returns true while `fetchNextPage()` is in flight. */ + isFetchingNextPage?: () => boolean; + /** Returns true when the most recent next-page fetch failed. */ + isFetchNextPageError?: () => boolean; + /** Requests the next page from the backend. */ + fetchNextPage?: () => Promise; +} + +/** Resolved infinite-query handles for a mounted `flow-projects-grid` component. */ +interface ResolvedGridQueries { + /** Verified metadata format for the active build. */ + format: ProjectMetadataFormat; + /** Owned `PROJECTS` infinite query signal. */ + ownedQuery: InfiniteQuerySignal | undefined; + /** Shared `SHARED_PROJECTS` infinite query signal. */ + sharedQuery: InfiniteQuerySignal | undefined; + /** True when the `SHARED_PROJECTS` query is enabled on the grid. */ + sharedEnabled: boolean; +} + +/** Calls a zero-argument boolean method on `target` when present. */ +export function callBool(target: unknown, key: string): boolean { + const fn = readOwn(target, key); + if (typeof fn === "function") { + try { + return Boolean(fn.call(target)); + } catch { + return false; + } + } + return fn === true; +} + +/** Calls a zero-argument getter method on `target` when present. */ +export function callGetter(target: unknown, key: string): unknown { + const fn = readOwn(target, key); + if (typeof fn !== "function") return undefined; + try { + return fn.call(target); + } catch { + return undefined; + } +} + +/** Checks whether `candidate` exposes `QueryClient.queryCache.find`. */ +export function asQueryClient(candidate: unknown): QueryClient | undefined { + if (!candidate || typeof candidate !== "object") return undefined; + const client = candidate as QueryClient; + return typeof client.queryCache?.find === "function" ? client : undefined; +} + +/** Resolves a `QueryClient` from captured Angular views or page injectors. */ +export function findLiveQueryClient(): QueryClient | undefined { + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + if (!isLiveLView(view)) continue; + for (const slot of view) { + if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + const direct = asQueryClient(slot); + if (direct) return direct; + if (typeof (slot as AgentInjector).get === "function") { + const resolved = resolveQueryClient(slot as AgentInjector); + if (resolved) return resolved; + } + const viaPage = resolveQueryClient({}, slot as Record); + if (viaPage) return viaPage; + } + } + return undefined; +} + +/** Calls `getterName` on a protobuf message and returns a trimmed non-empty string, or `null`. */ +function readProtoString(msg: unknown, getterName: string | undefined): string | null { + if (!msg || typeof msg !== "object" || !getterName) return null; + const val = callGetter(msg, getterName); + return typeof val === "string" && val.trim() ? val.trim() : null; +} + +/** Extracts a project title from a cached `PROJECT` or `PROJECT_DETAILS` message. */ +export function extractProjectDetailTitle( + data: unknown, + format: ProjectMetadataFormat | undefined, +): string | null { + if (!data || typeof data !== "object") return null; + if (format) { + const fromInfo = readProtoString( + callGetter(data, format.projectInfoGetter), + format.projectTitleGetter, + ); + if (fromInfo !== null) return fromInfo; + const fromMeta = readProtoString( + callGetter(data, format.cardMetadataGetter), + format.cardTitleGetter, + ); + if (fromMeta !== null) return fromMeta; + } + const directTitle = readOwn(data, "title") ?? readOwn(data, "displayName"); + return typeof directTitle === "string" && directTitle.trim() ? directTitle.trim() : null; +} + +/** Extracts `{ id, title }` from one owned or shared project card protobuf entry. */ +function extractCardProtobuf( + rawEntry: unknown, + isShared: boolean, + format: ProjectMetadataFormat, +): { id: string; title: string | null } | null { + if (!rawEntry || typeof rawEntry !== "object") return null; + const unwrapped = isShared ? callGetter(rawEntry, format.sharedProjectGetter) : rawEntry; + if (!unwrapped || typeof unwrapped !== "object") return null; + + let id = readProtoString(unwrapped, format.cardIdGetter); + if (!id) { + const plain = readOwn(unwrapped, "projectId"); + if (typeof plain === "string" && UUID_EXACT_RE.test(plain.trim())) { + id = plain.trim(); + } + } + if (!id) return null; + + const meta = callGetter(unwrapped, format.cardMetadataGetter); + const title = + readProtoString(meta, format.cardTitleGetter) ?? + extractProjectDetailTitle(unwrapped, format); + return { id, title }; +} + +/** Reads cached project entries from an infinite-query `data` value (`{ pages: [...] }`). */ +function collectPagesEntries( + data: unknown, + itemsKey: string, + isShared: boolean, + format: ProjectMetadataFormat, + into: Map, +): void { + const pages = readOwn(data, "pages"); + if (!Array.isArray(pages)) return; + for (const page of pages) { + const items = readOwn(page, itemsKey); + if (!Array.isArray(items)) continue; + for (const rawItem of items) { + const parsed = extractCardProtobuf(rawItem, isShared, format); + if (!parsed || into.has(parsed.id)) continue; + into.set(parsed.id, { + id: parsed.id, + title: parsed.title, + url: buildProjectUrl(parsed.id), + }); + } + } +} + +/** Checks whether `candidate` is a `flow-projects-grid` component instance. */ +function isProjectsGridComponent( + candidate: unknown, + gridClass: unknown, + format: ProjectMetadataFormat, +): candidate is Record { + if (!candidate || typeof candidate !== "object" || candidate instanceof Node) return false; + if (typeof gridClass === "function" && candidate instanceof gridClass) return true; + const owned = readOwn(candidate, format.ownedQuery); + const shared = readOwn(candidate, format.sharedQuery); + return ( + typeof readOwn(owned, "fetchNextPage") === "function" && + typeof readOwn(shared, "fetchNextPage") === "function" + ); +} + +/** Locates a mounted `flow-projects-grid` component synchronously without DOM events. */ +function locateProjectsGridSync( + format: ProjectMetadataFormat, + extraMaps?: Iterable>, +): Record | null { + const namespace = readOwn(window, "default_AiSandboxAngularFrontend"); + const gridClass = readOwn(namespace, format.gridClass); + const host = document.querySelector("flow-projects-grid"); + if (host) { + const directHit = resolveLView(host)?.find((slot) => + isProjectsGridComponent(slot, gridClass, format), + ); + if (directHit) return directHit; + const ctx = (host as unknown as { __ngContext__?: unknown }).__ngContext__; + if (typeof ctx === "number" && extraMaps) { + for (const map of extraMaps) { + const view = map.get(ctx); + const mappedHit = Array.isArray(view) + ? view.find((slot) => isProjectsGridComponent(slot, gridClass, format)) + : undefined; + if (mappedHit) { + runtimeState.ngLViewMap = map as Map; + return mappedHit; + } + } + } + } + for (const view of runtimeState.ngLViewMap?.values() ?? []) { + if (!isLiveLView(view)) continue; + const hit = view.find((slot) => isProjectsGridComponent(slot, gridClass, format)); + if (hit) return hit; + } + return null; +} + +/** Checks whether `SHARED_PROJECTS` is enabled on `grid` via its feature-flag method or active query state. */ +function isSharedProjectsEnabled( + grid: Record, + sharedQuery: InfiniteQuerySignal | undefined, + format: ProjectMetadataFormat, +): boolean { + if (typeof readOwn(grid, format.sharedEnabled) === "function") { + return callBool(grid, format.sharedEnabled); + } + const flags = readOwn(grid, format.gridFlags); + if (typeof readOwn(flags, format.sharedEnabled) === "function") { + return callBool(flags, format.sharedEnabled); + } + return Boolean( + callGetter(sharedQuery, "data") !== undefined || + callBool(sharedQuery, "isFetching") || + callBool(sharedQuery, "hasNextPage"), + ); +} + +/** Resolves the mounted `flow-projects-grid` infinite queries on the Flow home page. */ +async function resolveProjectsGridQueries(waitMount: boolean): Promise { + const format = activeProjectMetadataFormat(); + if (!format) return null; + let grid = locateProjectsGridSync(format); + if (!grid && waitMount) { + for (let attempt = 0; attempt < 25 && !grid; attempt += 1) { + const host = document.querySelector("flow-projects-grid"); + if (host) { + const captured = new Set>(); + await withMapCapture( + (map, _key, _value, write) => { + if (!write) captured.add(map); + }, + async () => { + const card = host.querySelector("flow-project-card, button"); + if (card instanceof HTMLElement) { + card.dispatchEvent(new PointerEvent("pointerenter", { bubbles: false })); + card.dispatchEvent(new MouseEvent("mouseenter", { bubbles: false })); + } + await delay(40); + }, + ); + grid = locateProjectsGridSync(format, captured); + if (grid) break; + } + const loading = Boolean( + document.querySelector("flow-loading-page, .projects-loading-container"), + ); + if (!loading && !host && attempt >= 4) break; + await delay(120); + } + } + if (!grid) return null; + const ownedQuery = readOwn(grid, format.ownedQuery) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, format.sharedQuery) as InfiniteQuerySignal | undefined; + const sharedEnabled = isSharedProjectsEnabled(grid, sharedQuery, format); + return { format, ownedQuery, sharedQuery, sharedEnabled }; +} + +/** Returns the number of loaded pages in an infinite query signal. */ +function readPagesCount(query: InfiniteQuerySignal | undefined): number { + const pages = readOwn(callGetter(query, "data"), "pages"); + return Array.isArray(pages) ? pages.length : 0; +} + +/** Waits until an infinite query finishes its initial load or in-flight next-page fetch. */ +async function waitInfiniteQueryIdle( + query: InfiniteQuerySignal | undefined, + waitInitial: boolean, +): Promise { + if (!query) return; + const deadline = Date.now() + GRID_QUERY_SETTLE_TIMEOUT_MS; + while (Date.now() < deadline) { + if (callBool(query, "isError")) return; + const fetchingNext = callBool(query, "isFetchingNextPage"); + const initialBusy = + waitInitial && + readPagesCount(query) === 0 && + (callBool(query, "isFetching") || callBool(query, "isPlaceholderData")); + if (!fetchingNext && !initialBusy) return; + await delay(GRID_QUERY_POLL_MS); + } +} + +/** Fetches all remaining pages of `query` up to `MAX_GRID_PAGES` (`50`). */ +async function fetchAllInfinitePages( + query: InfiniteQuerySignal | undefined, + enabled: boolean, +): Promise { + if (!query || !enabled || typeof query.fetchNextPage !== "function") return; + await waitInfiniteQueryIdle(query, true); + for (let page = 0; page < MAX_GRID_PAGES; page += 1) { + await waitInfiniteQueryIdle(query, false); + if (!callBool(query, "hasNextPage") || callBool(query, "isFetchNextPageError")) break; + const beforePages = readPagesCount(query); + try { + await Promise.resolve(query.fetchNextPage()); + } catch { + break; + } + await waitInfiniteQueryIdle(query, false); + if (readPagesCount(query) <= beforePages && callBool(query, "hasNextPage")) break; + } +} + +/** Collects cached dashboard project cards from `QueryClient` without triggering fetches. */ +export function collectProjectsFromQueryCache( + client: QueryClient | undefined, + format: ProjectMetadataFormat, +): { sawProjectsQuery: boolean; items: Map } { + const items = new Map(); + let sawProjectsQuery = false; + const findAll = readOwn(client?.queryCache, "findAll"); + if (typeof findAll !== "function") return { sawProjectsQuery, items }; + const queries: unknown = findAll.call(client?.queryCache); + if (!Array.isArray(queries)) return { sawProjectsQuery, items }; + for (const query of queries) { + const key = readOwn(query, "queryKey"); + if (!Array.isArray(key) || typeof key[0] !== "string") continue; + const data = readOwn(readOwn(query, "state"), "data"); + if (key[0] === "PROJECTS") { + sawProjectsQuery = true; + collectPagesEntries(data, format.ownedQuery, false, format, items); + } else if (key[0] === "SHARED_PROJECTS") { + sawProjectsQuery = true; + collectPagesEntries(data, format.sharedQuery, true, format, items); + } + } + return { sawProjectsQuery, items }; +} + +/** Inspects `flow-projects-grid` (`PROJECTS` and `SHARED_PROJECTS`), fetches all pages, and reads cached card protobufs. */ +export async function listCachedProjects(): Promise { + const resolved = await resolveProjectsGridQueries(true); + if (resolved) { + const { format, ownedQuery, sharedQuery, sharedEnabled } = resolved; + await Promise.all([ + fetchAllInfinitePages(ownedQuery, true), + fetchAllInfinitePages(sharedQuery, sharedEnabled), + ]); + const items = new Map(); + collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); + if (sharedEnabled) { + collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); + } + return [...items.values()]; + } + const format = activeProjectMetadataFormat(); + if (!format) return null; + const cached = collectProjectsFromQueryCache(findLiveQueryClient(), format); + return cached.sawProjectsQuery ? [...cached.items.values()] : null; +} + +/** Reads currently loaded dashboard card protobufs without triggering additional pagination. */ +export function snapshotLoadedGridProjects(): Map { + const format = activeProjectMetadataFormat(); + if (!format) return new Map(); + const grid = locateProjectsGridSync(format); + if (grid) { + const items = new Map(); + const ownedQuery = readOwn(grid, format.ownedQuery) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, format.sharedQuery) as InfiniteQuerySignal | undefined; + collectPagesEntries(callGetter(ownedQuery, "data"), format.ownedQuery, false, format, items); + if (isSharedProjectsEnabled(grid, sharedQuery, format)) { + collectPagesEntries(callGetter(sharedQuery, "data"), format.sharedQuery, true, format, items); + } + return items; + } + return collectProjectsFromQueryCache(findLiveQueryClient(), format).items; +} + +/** Returns `true` when `flow-projects-grid` currently has an in-flight `PROJECTS` or `SHARED_PROJECTS` fetch. */ +export function isProjectsGridFetching(): boolean { + const format = activeProjectMetadataFormat(); + if (!format) return false; + const grid = locateProjectsGridSync(format); + if (!grid) return false; + const ownedQuery = readOwn(grid, format.ownedQuery) as InfiniteQuerySignal | undefined; + const sharedQuery = readOwn(grid, format.sharedQuery) as InfiniteQuerySignal | undefined; + const ownedBusy = callBool(ownedQuery, "isFetching"); + const sharedBusy = + isSharedProjectsEnabled(grid, sharedQuery, format) && callBool(sharedQuery, "isFetching"); + return ownedBusy || sharedBusy; +} + +/** Advances `flow-projects-grid` by one page when `hasNextPage()` is true, returning whether a page was fetched. */ +export async function advanceProjectsGridPage(): Promise { + const resolved = await resolveProjectsGridQueries(true); + if (!resolved) return false; + const { ownedQuery, sharedQuery, sharedEnabled } = resolved; + + await Promise.all([ + waitInfiniteQueryIdle(ownedQuery, true), + sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, true) : Promise.resolve(), + ]); + + const tasks: Array> = []; + const beforeOwned = readPagesCount(ownedQuery); + const beforeShared = readPagesCount(sharedQuery); + + if ( + ownedQuery && + typeof ownedQuery.fetchNextPage === "function" && + callBool(ownedQuery, "hasNextPage") && + !callBool(ownedQuery, "isFetchNextPageError") + ) { + tasks.push(Promise.resolve(ownedQuery.fetchNextPage()).catch(() => null)); + } + if ( + sharedEnabled && + sharedQuery && + typeof sharedQuery.fetchNextPage === "function" && + callBool(sharedQuery, "hasNextPage") && + !callBool(sharedQuery, "isFetchNextPageError") + ) { + tasks.push(Promise.resolve(sharedQuery.fetchNextPage()).catch(() => null)); + } + if (tasks.length === 0) return false; + + await Promise.all(tasks); + await Promise.all([ + waitInfiniteQueryIdle(ownedQuery, false), + sharedEnabled ? waitInfiniteQueryIdle(sharedQuery, false) : Promise.resolve(), + ]); + + return readPagesCount(ownedQuery) > beforeOwned || readPagesCount(sharedQuery) > beforeShared; +} diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index aea4dce..e2e2e3f 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -18,7 +18,7 @@ import { isProjectsGridFetching, listCachedProjects, snapshotLoadedGridProjects, -} from "./project_metadata"; +} from "./projects_grid_cache"; import type { ProjectsOpRequest } from "./types"; /** Internal card descriptor captured on the Flow projects grid. */ diff --git a/ts/types.ts b/ts/types.ts index 0ba1582..f6e82f9 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -623,7 +623,9 @@ export interface ProjectMetadataFormat { /** Infinite query and page items property for `SHARED_PROJECTS` on `flow-projects-grid`. */ sharedQuery: string; /** Feature-flag method on `flow-projects-grid` reporting whether `SHARED_PROJECTS` is enabled. */ - sharedEnabled?: string; + sharedEnabled: string; + /** Injected feature-flags service property on `flow-projects-grid`. */ + gridFlags: string; /** Getter method returning the project ID on a card or details protobuf message. */ cardIdGetter: string; /** Getter method returning the card metadata protobuf message. */