Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub(crate) use crate::project_route::{
use crate::project_store::{bind_current_store, prepare_project_store_status};

/// Angular error code for a required input that has no value yet.
const ANGULAR_REQUIRED_INPUT_ERROR: &str = "NG0950";
pub(crate) const ANGULAR_REQUIRED_INPUT_ERROR: &str = "NG0950";

/// Parameters for `flow_status`.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
Expand Down Expand Up @@ -367,7 +367,8 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> {

let workspace = project_workspace_url(&url, &project_id);
let mut input_pending = false;
for attempt in 0..10 {
let mut store_loading = false;
for attempt in 0..24 {
let active_url = engine.current_url().await?;
anyhow::ensure!(
is_flow_host_url(&active_url)
Expand All @@ -387,9 +388,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> {
return Ok(());
}
if status_err == Some("store_loading") {
store_loading = true;
input_pending = false;
tokio::time::sleep(Duration::from_millis(250)).await;
continue;
}
store_loading = false;
input_pending = status_err == Some(ANGULAR_REQUIRED_INPUT_ERROR);

let discovery =
Expand All @@ -401,6 +405,11 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> {
build_suffix(engine).await
);
}
if discovery_err == Some("store_loading") {
store_loading = true;
tokio::time::sleep(Duration::from_millis(250)).await;
continue;
}
input_pending |= discovery_err == Some(ANGULAR_REQUIRED_INPUT_ERROR);
if discovery["bound"].as_bool() == Some(true) {
tokio::time::sleep(Duration::from_millis(250)).await;
Expand All @@ -425,14 +434,20 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> {
build_suffix(engine).await
);
}
if store_loading {
anyhow::bail!(
"The Flow project store is still loading.{}",
build_suffix(engine).await
);
}
anyhow::bail!(
"Failed to bind the Flow project store. Open a Flow project first.{}",
build_suffix(engine).await
)
}

/// Treats an unset Angular input as a loading result for a project store read.
fn store_loading_result(result: Result<Value>) -> Result<Value> {
pub(crate) fn store_loading_result(result: Result<Value>) -> Result<Value> {
match result {
Err(error)
if error.to_string().lines().next().is_some_and(|line| {
Expand Down
28 changes: 19 additions & 9 deletions src/project_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use tokio::sync::MutexGuard;

use crate::auth::is_signed_in_flow_url;
use crate::engine::{ChromeEngine, checked_runtime_result};
use crate::project::project_id_from_url;
use crate::project::{ANGULAR_REQUIRED_INPUT_ERROR, project_id_from_url, store_loading_result};

/// Holds the browser project store lock and pins the project and runtime session.
pub(crate) struct ProjectStoreSession<'a> {
Expand All @@ -36,20 +36,30 @@ impl<'a> ProjectStoreSession<'a> {
.context("Open a Google Flow project before you use this tool")?;
let guard = engine.lock_project_store().await;
let mut dom_probed = false;
let mut status = bind_current_store(engine, &project_id).await?;
for _ in 0..25 {
let mut status = store_loading_result(bind_current_store(engine, &project_id).await)?;
for _ in 0..30 {
let err = status.get("error").and_then(Value::as_str);
if err == Some("collection_store_not_bound") && !dom_probed {
let discovery =
store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?;
if matches!(
discovery.get("error").and_then(Value::as_str),
Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR)
) {
status = json!({ "ok": false, "error": "store_loading" });
continue;
}
dom_probed = true;
let _ = engine.call_flow_async("discoverStore", json!([])).await;
status = engine
.call_flow_js("projectStoreStatus", json!([project_id]))
.await?;
status = store_loading_result(
engine
.call_flow_js("projectStoreStatus", json!([project_id]))
.await,
)?;
continue;
}
if err == Some("store_loading") {
if matches!(err, Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR)) {
tokio::time::sleep(Duration::from_millis(200)).await;
status = bind_current_store(engine, &project_id).await?;
status = store_loading_result(bind_current_store(engine, &project_id).await)?;
continue;
}
break;
Expand Down
8 changes: 6 additions & 2 deletions ts/agent_chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,12 @@ function liveBinding(projectId: string): Binding | undefined {
| undefined;
if (life?.[format.destroyed] !== false) return;
const project = Reflect.get(page, format.project);
if (typeof project === "function" && project.call(page) === projectId)
return binding;
if (typeof project !== "function") return;
try {
if (project.call(page) === projectId) return binding;
} catch {
return;
}
}

/** Returns true if the active document has a binding for this project. */
Expand Down
35 changes: 29 additions & 6 deletions ts/angular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types"

/** Object with optional Angular Ivy `__ngContext__` or internal `lView` links. */
export interface NgContextCarrier {
/** Angular Ivy LView array or registry slot index. */
/** Angular Ivy LView array, registry slot index, or upgraded LContext wrapper. */
__ngContext__?: number | NgLView | Record<string, unknown>;
/** Embedded view LView reference. */
lView?: NgLView;
/** Registry slot ID on an upgraded LContext wrapper. */
lViewId?: number;
}

/** Reads an own or prototype property safely without triggering exceptions. */
Expand Down Expand Up @@ -53,13 +55,30 @@ export function isNgLViewMap(m: unknown): m is Map<number, NgLView> {
return false;
}

/** Reads the Angular `LView` registry slot ID from a host node or context value. */
export function readLViewSlotId(elOrCtx: unknown): number | null {
const ctxObj =
elOrCtx && typeof elOrCtx === "object"
? (elOrCtx as NgContextCarrier)
: null;
const raw: unknown =
ctxObj && "__ngContext__" in ctxObj ? ctxObj.__ngContext__ : elOrCtx;
if (typeof raw === "number") return raw;
if (raw && typeof raw === "object" && !(raw instanceof Node)) {
const id = readOwn(raw, "lViewId");
if (typeof id === "number") return id;
}
const view = resolveLView(elOrCtx);
return typeof view?.[19] === "number" ? view[19] : null;
}

/** Binds the live Angular view registry that contains the selected host context. */
export function bindAngularViews(maps: unknown[], selector: string): boolean {
for (const host of document.querySelectorAll(selector)) {
const context = readOwn(host, "__ngContext__");
if (typeof context !== "number") continue;
const slotId = readLViewSlotId(host);
if (slotId === null) continue;
const views = maps.find((map): map is Map<number, NgLView> =>
isNgLViewMap(map) && isLiveLView(map.get(context)),
isNgLViewMap(map) && isLiveLView(map.get(slotId)),
);
if (views) {
runtimeState.ngLViewMap = views;
Expand All @@ -83,12 +102,16 @@ export function resolveLView(elOrCtx: unknown): NgLView | null {
? runtimeState.ngLViewMap.get(raw) || null
: null;
}
if (raw && typeof raw === "object") {
if (raw && typeof raw === "object" && !(raw instanceof Node)) {
const lView = readOwn(raw, "lView");
if (Array.isArray(lView)) return lView;
const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView;
const verifiedView = contextField ? readOwn(raw, contextField) : undefined;
return Array.isArray(verifiedView) ? verifiedView : null;
if (Array.isArray(verifiedView)) return verifiedView;
const id = readOwn(raw, "lViewId");
if (typeof id === "number" && runtimeState.ngLViewMap instanceof Map) {
return runtimeState.ngLViewMap.get(id) || null;
}
}
return null;
}
Expand Down
11 changes: 6 additions & 5 deletions ts/character_voices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

// List and assign Google Flow character voices inside the character editor.

import { readOwn, startMapCapture, type NgContextCarrier } from "./angular";
import { readLViewSlotId, readOwn, resolveLView, startMapCapture } from "./angular";
import { VOICE_ICON_WORDS, voicePane } from "./character_extra";
import {
clickButtonByRegex,
Expand Down Expand Up @@ -118,14 +118,15 @@ export async function characterVoiceOp(
};
return walk(rootLv, 0);
};
const formNg = (form as NgContextCarrier).__ngContext__;
const resolvedLv = resolveLView(form);
const direct =
scanLView(formNg, isExactComp) || scanLView(formNg, isFormComp);
scanLView(resolvedLv, isExactComp) || scanLView(resolvedLv, isFormComp);
if (direct) {
formComponents.set(form, direct);
return direct;
}
if (typeof formNg !== "number" || probedForms.has(form)) {
const formSlotId = readLViewSlotId(form);
if (formSlotId === null || probedForms.has(form)) {
return null;
}
probedForms.add(form);
Expand Down Expand Up @@ -181,7 +182,7 @@ export async function characterVoiceOp(
} finally {
stop();
}
const idx = formNg;
const idx = formSlotId;
const findAcrossCaptured = (
predicate: (c: unknown) => c is CharacterFormComponent,
): CharacterFormComponent | null => {
Expand Down
Loading
Loading