From 49846a2d4d1e7a6deded8fa8f6ce0bd6c2636752 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:34:38 +0000 Subject: [PATCH 1/8] fix(flow): detect store state and LContext by object shape - Check store format hints and boolean Va or Wa flags for disposal - Share isStoreDestroyed in snapshot reads and character operations - Check tileQuery hints and pending PROJECT_TILES queries on load - Prefer async TanStack mutators such as ld before queue polling - Subscribe to Da and oa error streams without wedging the queue - Scan component properties and flow-scene-builder for active stores - Unwrap LContext objects through lView, zp, Pn, or LView slots --- ts/angular.ts | 49 +++- ts/character_ops.ts | 10 +- ts/character_voices.ts | 5 +- ts/discover_store.ts | 459 ++++++++++++++++++++------------------ ts/frontend_builds.ts | 6 +- ts/project_store.ts | 9 +- ts/read_store_snapshot.ts | 6 +- ts/store_shape.ts | 392 ++++++++++++++++++++++++++++++++ ts/types.ts | 55 ++++- 9 files changed, 746 insertions(+), 245 deletions(-) create mode 100644 ts/store_shape.ts diff --git a/ts/angular.ts b/ts/angular.ts index 671b201..c8add62 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -10,12 +10,16 @@ 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. */ - __ngContext__?: number | NgLView; - /** Embedded view LView reference. */ + /** Angular Ivy LView array, registry slot index, or upgraded LContext wrapper. */ + __ngContext__?: number | NgLView | NgContextCarrier; + /** Embedded view or LContext LView reference. */ lView?: NgLView; + /** Minified LContext LView reference in Flow builds from 2026-11-20 on. */ + zp?: NgLView; /** Minified LView reference alias. */ Pn?: NgLView; + /** Optional LView registry slot identifier on LContext wrappers. */ + lViewId?: number; } /** Reads an own or prototype property safely without triggering exceptions. */ @@ -60,6 +64,17 @@ export function bindAngularViews(maps: unknown[], selector: string): boolean { return true; } +/** Checks whether `val` matches the header shape of an Angular Ivy `LView` array. */ +function isLViewArray(val: unknown): val is NgLView { + return ( + Array.isArray(val) && + val.length >= 20 && + (typeof val[19] === "number" || + typeof val[2] === "number" || + (Boolean(val[1]) && typeof val[1] === "object")) + ); +} + /** Resolves a DOM element, numeric slot index, or wrapper object to its Angular `NgLView`. */ export function resolveLView(elOrCtx: unknown): NgLView | null { const ctxObj = @@ -74,9 +89,33 @@ 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 carrier = raw as NgContextCarrier; - return carrier.lView || carrier.Pn || null; + for (const key of ["lView", "zp", "Pn"] as const) { + const candidate = readOwn(carrier, key); + if (Array.isArray(candidate)) return candidate; + } + const id = readOwn(carrier, "lViewId"); + if (typeof id === "number" && runtimeState.ngLViewMap instanceof Map) { + const mapped = runtimeState.ngLViewMap.get(id); + if (Array.isArray(mapped)) return mapped; + } + let fallback: NgLView | null = null; + let arrayCount = 0; + try { + for (const key of Object.getOwnPropertyNames(raw)) { + if (key === "directives") continue; + const desc = Object.getOwnPropertyDescriptor(raw, key); + const val = desc && "value" in desc ? desc.value : undefined; + if (!Array.isArray(val)) continue; + if (isLViewArray(val)) return val; + arrayCount += 1; + if (val.length > 0 && !fallback) fallback = val; + } + } catch { + return null; + } + return arrayCount === 1 ? fallback : null; } return null; } diff --git a/ts/character_ops.ts b/ts/character_ops.ts index 1e9f426..4ee95bf 100644 --- a/ts/character_ops.ts +++ b/ts/character_ops.ts @@ -6,10 +6,14 @@ import { findRouter } from "./angular"; import { clickButtonByRegex, delay, isVisibleEnabled, setNativeValue } from "./dom"; import { clearStore, runtimeState } from "./state"; +import { isStoreDestroyed } from "./store_shape"; import type { CharacterOpRequest } from "./types"; /** Creates, opens, updates, or finishes character entity editing in Google Flow. */ export async function characterOp(req: CharacterOpRequest): Promise { + if ((runtimeState.lService || runtimeState.store) && isStoreDestroyed(runtimeState.lService)) { + clearStore(); + } const helper = runtimeState.store; const getMap = () => helper?.getTileMap?.(); const action = String(req?.action || "").toLowerCase(); @@ -51,11 +55,11 @@ export async function characterOp(req: CharacterOpRequest): Promise { } if ( runtimeState.projectId === pid && - runtimeState.lService && - !runtimeState.lService.Ca?.Va && - !runtimeState.lService._ap?.Ca?.Va + !isStoreDestroyed(runtimeState.lService) ) { runtimeState.routePath = location.pathname; + } else if (runtimeState.lService || runtimeState.store) { + clearStore(); } return { ok: true, spa: true, path: location.pathname }; } diff --git a/ts/character_voices.ts b/ts/character_voices.ts index d3c1a53..7f5b7c8 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -11,6 +11,7 @@ import { elText, isVisibleEnabled, } from "./dom"; +import { isStoreDestroyed } from "./store_shape"; import type { AngularLifecycleHandle, CharacterVoiceOpRequest } from "./types"; /** Minified Angular character form component hosting voice signals. */ @@ -65,7 +66,7 @@ export async function characterVoiceOp( const form = document.querySelector("flow-character-form"); if (!form) return null; const cached = formComponents.get(form); - if (cached && !cached.Ca?.Va) { + if (cached && !isStoreDestroyed(cached)) { return cached; } const isBasicObj = (cand: unknown): cand is CharacterFormComponent => @@ -78,7 +79,7 @@ export async function characterVoiceOp( !(cand instanceof Set) && cand !== window && cand !== document && - !(cand as AngularLifecycleHandle).Ca?.Va, + !isStoreDestroyed(cand), ); const isExactComp = (cand: unknown): cand is CharacterFormComponent => isBasicObj(cand) && diff --git a/ts/discover_store.ts b/ts/discover_store.ts index d16f07b..db0d09e 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -12,148 +12,188 @@ import { import { delay, hoverProbe } from "./dom"; import { withMutationAliases } from "./frontend_compatibility"; import { clearStore, runtimeState } from "./state"; +import { + findMethodByMarker, + hasMethodString, + hasPendingProjectTilesQuery, + isInspectableObject, + isStoreDestroyed, + readOwnData, + resolveTileArrayFromUO, + resolveTileMapFrom, +} from "./store_shape"; import type { DiscoverStoreResult, FlowStoreService, FlowTile, + MutationErrorStream, MutationQueueObj, NgLView, } from "./types"; -/** Checks whether a candidate object defines a method whose source contains `marker`. */ -function findMethodByMarker( +export { isStoreDestroyed } from "./store_shape"; + +/** Returns the async mutate function of a TanStack mutation result (`oe`, `re` or `mutateAsync` by Flow build), or null. */ +function mutateAsyncOf( obj: unknown, - marker: string, -): ((...args: unknown[]) => unknown) | null { +): ((payload: Record) => Promise) | null { if (!obj || typeof obj !== "object") return null; - let cur: object | null = obj; - for (let depth = 0; cur && cur !== Object.prototype && depth < 3; depth++) { - for (const k of Object.getOwnPropertyNames(cur)) { - if (k === "constructor") continue; - const fn = readOwn(obj, k); - if (typeof fn === "function") { - try { - if (fn.toString().includes(marker)) { - return fn.bind(obj) as (...args: unknown[]) => unknown; - } - } catch { - // Ignore non-inspectable functions. - } + const rec = obj as Record; + const keys = Object.keys(rec); + const bind = (fn: unknown) => (payload: Record) => + Promise.resolve((fn as (p: unknown) => unknown).call(rec, payload)); + if (keys.includes("mutate") && keys.includes("reset")) { + for (const k of keys) { + if (k === "mutate" || k === "reset" || k.startsWith("is")) continue; + const fn = readOwn(rec, k); + if ( + typeof fn === "function" && + ((fn as () => unknown).length === 1 || (fn as () => unknown).length === 2) + ) { + return bind(fn); } } - cur = Object.getPrototypeOf(cur); + } + for (const name of ["mutateAsync", "oe", "re"]) { + const present = name === "mutateAsync" ? name in rec : keys.includes(name); + if (!present) continue; + const fn = readOwn(rec, name); + if (typeof fn === "function") return bind(fn); } return null; } -/** Returns true when `obj` has a method containing `marker`. */ -function hasMethodString(obj: unknown, marker: string): boolean { - return Boolean(findMethodByMarker(obj, marker)); +/** Escapes regex metacharacters in a property identifier. */ +function escapeIdent(key: string): string { + return key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -/** Checks whether `m` looks like a project tile map. */ -function isTileMap(m: unknown): m is Map { - if (!(m instanceof Map)) return false; - if (m.size === 0) return true; - for (const v of m.values()) { - if (v && typeof v === "object" && ("id" in v || "type" in v)) { - return true; +/** Locates the tile TanStack mutator on `obj` (such as `this.ld` or `this.lc`) through `mutateAsyncOf`. */ +function findAsyncMutator( + obj: FlowStoreService | MutationQueueObj | null | undefined, +): MutationQueueObj | null { + if (!isInspectableObject(obj)) return null; + let ownKeys: string[]; + try { + ownKeys = Object.getOwnPropertyNames(obj); + } catch { + return null; + } + const candidates: Array<[string, MutationQueueObj]> = []; + for (const key of ownKeys) { + if (key === "ha" || key === "_ap" || key === "_uo") continue; + const val = readOwnData(obj, key); + if (val && typeof val === "object" && mutateAsyncOf(val)) { + candidates.push([key, val as MutationQueueObj]); } - return false; } - return false; -} - -/** Extracts the tile `Map` from a candidate Angular store service. */ -function resolveTileMapFrom(svc: FlowStoreService | null): Map | null { - if (!svc || typeof svc !== "object") return null; - const apKa = svc._ap?.ka; - if (typeof apKa === "function") { - try { - const m = apKa.call(svc._ap); - if (m instanceof Map) return m; - } catch { - // Try next getter. + if (candidates.length > 1) { + const haObj = readOwnData(obj, "ha"); + const params = + (isInspectableObject(haObj) ? readOwnData(haObj, "parameters") : undefined) ?? + readOwnData(obj, "parameters"); + if (isInspectableObject(params)) { + for (const pk of Object.getOwnPropertyNames(params)) { + const pfn = readOwnData(params, pk); + if (typeof pfn !== "function") continue; + let src = ""; + try { + src = pfn.toString(); + } catch { + continue; + } + for (const [key, mut] of candidates) { + if (new RegExp(`\\.${escapeIdent(key)}\\b`).test(src)) { + return mut; + } + } + } } } - if (typeof svc.ka === "function") { - try { - const m = svc.ka(); - if (m instanceof Map) return m; - } catch { - // Try next getter. + for (const known of ["ld", "lc", "ka"]) { + const val = readOwnData(obj, known) ?? (known in obj ? readOwn(obj, known) : undefined); + if (val && typeof val === "object" && mutateAsyncOf(val)) { + return val as MutationQueueObj; } } - const haKa = svc.ha?.ka; - if (typeof haKa === "function") { + return candidates.length > 0 ? candidates[candidates.length - 1][1] : null; +} + +/** Converts an arbitrary error value into an `Error` instance. */ +function toMutationError(err: unknown): Error { + return err instanceof Error ? err : new Error(String(err)); +} + +/** Reads the current error signal on a mutation queue when available. */ +function readQueueError(mq: MutationQueueObj | null | undefined): unknown { + if (!mq || typeof mq !== "object" || !("error" in mq)) return null; + const errFn = readOwn(mq, "error"); + if (typeof errFn === "function") { try { - const m = haKa.call(svc.ha); - if (m instanceof Map) return m; + return errFn.call(mq) ?? null; } catch { - // Fall back to BFS scan. + return null; } } - const queue: object[] = [svc]; + return null; +} + +/** Collects distinct subscribable error streams (`Da`, `oa`, `Ha`, `ua`, or own observables) on `mq`. */ +function findErrorStreams(mq: MutationQueueObj | null | undefined): MutationErrorStream[] { + if (!isInspectableObject(mq)) return []; + const streams: MutationErrorStream[] = []; const seen = new Set(); - let emptyMapFallback: Map | null = null; - while (queue.length && seen.size < 40) { - const cur = queue.shift(); - if (!cur || typeof cur !== "object" || seen.has(cur)) continue; - seen.add(cur); - for (const k of Object.keys(cur)) { - const val = readOwn(cur, k); - if (isTileMap(val)) { - if (val.size > 0) return val; - emptyMapFallback = emptyMapFallback || val; - } else if (val && typeof val === "object" && seen.size < 40) { - let proto = Object.getPrototypeOf(val) as object | null; - while (proto && proto !== Object.prototype) { - for (const mk of Object.getOwnPropertyNames(proto)) { - if (mk === "constructor") continue; - try { - const fn = readOwn(val, mk); - if (typeof fn === "function" && fn.length === 0) { - const res = fn.call(val); - if (isTileMap(res)) { - if (res.size > 0) return res; - emptyMapFallback = emptyMapFallback || res; - } - } - } catch { - // Ignore unsafe getters. - } - } - proto = Object.getPrototypeOf(proto) as object | null; - } - queue.push(val); - } + const add = (cand: unknown): void => { + if (!cand || typeof cand !== "object" || seen.has(cand) || !("subscribe" in cand)) return; + const sub = readOwn(cand, "subscribe"); + if (typeof sub === "function") { + seen.add(cand); + streams.push(cand as MutationErrorStream); } + }; + for (const key of ["Da", "oa", "Ha", "ua"]) { + add(readOwnData(mq, key) ?? (key in mq ? readOwn(mq, key) : undefined)); + } + for (const key of Object.getOwnPropertyNames(mq)) { + add(readOwnData(mq, key)); } - return emptyMapFallback; + return streams; } -/** Returns the async mutate function of a TanStack mutation result (`oe`, `re` or `mutateAsync` by Flow build), or null. */ -function mutateAsyncOf( - obj: unknown, -): ((payload: Record) => Promise) | null { - if (!obj || typeof obj !== "object") return null; - const rec = obj as Record; - const keys = Object.keys(rec); - const bind = (fn: unknown) => (payload: Record) => - Promise.resolve((fn as (p: unknown) => unknown).call(rec, payload)); - if (keys.includes("mutate") && keys.includes("reset")) { - for (const k of keys) { - const fn = readOwn(rec, k); - if (k !== "mutate" && k !== "reset" && typeof fn === "function" && (fn as () => unknown).length === 2) { - return bind(fn); +/** Clears a wedged `_.EO` queue entry and error signal caused by `payload` so `_.CO` keeps running. */ +function unwedgeMutationQueue( + mq: MutationQueueObj | null | undefined, + payload: Record, + err: unknown, +): void { + if (!isInspectableObject(mq)) return; + for (const key of Object.getOwnPropertyNames(mq)) { + const sig = readOwnData(mq, key) as + | ((() => unknown) & { set?: (val: unknown) => void }) + | undefined; + if (typeof sig !== "function" || typeof sig.set !== "function") continue; + try { + const cur = sig(); + if (err != null && cur === err) { + sig.set(undefined); + continue; + } + if (cur && typeof cur === "object" && Array.isArray((cur as { items?: unknown }).items)) { + const items = (cur as { items: Array<{ mutation?: unknown }> }).items; + const filtered = items.filter((it) => !it || it.mutation !== payload); + if (filtered.length !== items.length) { + const ctor = (cur as { constructor?: new (a: unknown[]) => unknown }).constructor; + const next = + typeof ctor === "function" && ctor !== Object + ? new ctor(filtered) + : { ...(cur as Record), items: filtered }; + sig.set(next); + } } + } catch { + // Ignore read-only signals. } } - for (const name of ["mutateAsync", "oe", "re"]) { - const fn = readOwn(rec, name); - if (keys.includes(name) && typeof fn === "function") return bind(fn); - } - return null; } /** Dispatches a store mutation payload and waits for queue completion. */ @@ -164,20 +204,6 @@ async function invokeMutation( ): Promise { payload = withMutationAliases(payload); const mq = queueObj as MutationQueueObj | null | undefined; - const qKa = typeof mq?.ka === "function" ? mq.ka.bind(mq) : null; - const hasPendingQueueItems = (): boolean => { - if (!qKa) return false; - try { - const q = qKa(); - return Array.isArray(q?.items) && q.items.length > 0; - } catch { - return false; - } - }; - for (let i = 0; i < 200; i++) { - if (!hasPendingQueueItems()) break; - await delay(50); - } const lcAsync = mutateAsyncOf(lcObj); if (lcAsync) { const res = await lcAsync(payload); @@ -190,60 +216,79 @@ async function invokeMutation( await delay(0); return res; } - const qMutateAsync = mq?.mutateAsync; + const qMutateAsync = mq && "mutateAsync" in mq ? mq.mutateAsync : undefined; if (typeof qMutateAsync === "function") { const res = await qMutateAsync.call(mq, payload); await delay(0); return res; } + const qKa = mq && "ka" in mq && typeof mq.ka === "function" ? mq.ka.bind(mq) : null; + const hasPendingQueueItems = (): boolean => { + if (!qKa || readQueueError(mq)) return false; + try { + const q = qKa(); + return Array.isArray(q?.items) && q.items.length > 0; + } catch { + return false; + } + }; + for (let i = 0; i < 200; i++) { + if (!hasPendingQueueItems()) break; + await delay(50); + } if (typeof queueObj?.mutate === "function" && qKa) { + const priorError = readQueueError(mq); + if (priorError) { + throw toMutationError(priorError); + } let capturedError: unknown = null; - let sub: { unsubscribe?: () => void } | null = null; + const subs: Array<{ unsubscribe?: () => void }> = []; try { - const obs = mq?.Ha || mq?.ua; - if (obs && typeof obs.subscribe === "function") { - sub = obs.subscribe((ev) => { - if (ev && (!ev.mutation || ev.mutation === payload) && ev.error) { + for (const obs of findErrorStreams(mq)) { + if (typeof obs.subscribe !== "function") continue; + const sub = obs.subscribe((ev) => { + if (ev && typeof ev === "object" && (!ev.mutation || ev.mutation === payload) && ev.error) { capturedError = ev.error; } }); + if (sub) subs.push(sub); } queueObj.mutate(payload); for (let i = 0; i < 1200; i++) { await delay(25); - if (capturedError) break; + const activeErr = capturedError ?? readQueueError(mq); + if (activeErr) { + unwedgeMutationQueue(mq, payload, activeErr); + throw toMutationError(activeErr); + } const snapshot = qKa(); const items = snapshot?.items; const stillQueued = Array.isArray(items) && items.some((it) => it && it.mutation === payload); if (!stillQueued) { - let errState: unknown = null; - if (typeof mq?.error === "function") { - try { - errState = mq.error(); - } catch { - errState = null; - } - } - if (errState) { - throw errState instanceof Error ? errState : new Error(String(errState)); + const settledErr = capturedError ?? readQueueError(mq); + if (settledErr) { + unwedgeMutationQueue(mq, payload, settledErr); + throw toMutationError(settledErr); } await delay(0); return undefined; } } - if (capturedError) { - throw capturedError instanceof Error - ? capturedError - : new Error(String(capturedError)); + const timeoutErr = capturedError ?? readQueueError(mq); + if (timeoutErr) { + unwedgeMutationQueue(mq, payload, timeoutErr); + throw toMutationError(timeoutErr); } throw new Error("mutation_timeout"); } finally { - try { - sub?.unsubscribe?.(); - } catch { - // Ignore unsubscribe error. + for (const sub of subs) { + try { + sub.unsubscribe?.(); + } catch { + // Ignore unsubscribe error. + } } } } @@ -261,27 +306,16 @@ function resolveMutatorFrom( projectId: string | null, ): ((payload: Record) => Promise) | null { if (!svc || typeof svc !== "object") return null; - const lcFallback = (obj: FlowStoreService): MutationQueueObj | null => { - if (mutateAsyncOf(obj.lc)) return obj.lc ?? null; - if (typeof obj.ka === "object" && obj.ka && mutateAsyncOf(obj.ka)) { - return obj.ka; - } - return null; - }; + const apMutator = findAsyncMutator(svc._ap); + const directLc = apMutator || findAsyncMutator(svc); const haInner = svc.ha?.ha as MutationQueueObj | null | undefined; if (haInner && typeof haInner.mutate === "function") { - const haLc = - svc.ha && mutateAsyncOf(svc.ha.lc) - ? (svc.ha.lc ?? null) - : typeof svc.ka === "object" && svc.ka && mutateAsyncOf(svc.ka) - ? svc.ka - : null; + const haLc = findAsyncMutator(svc.ha) || directLc; return (payload) => invokeMutation(haInner, payload, haLc); } if (svc.ha && typeof svc.ha.mutate === "function") { - return (payload) => invokeMutation(svc.ha, payload, lcFallback(svc)); + return (payload) => invokeMutation(svc.ha, payload, findAsyncMutator(svc.ha) || directLc); } - const directLc = lcFallback(svc); if (directLc && mutateAsyncOf(directLc)) { return (payload) => invokeMutation(svc, payload, directLc); } @@ -289,17 +323,22 @@ function resolveMutatorFrom( return (payload) => invokeMutation(svc, payload, directLc); } for (const k of Object.keys(svc)) { - const child = readOwn(svc, k); + const child = readOwnData(svc, k); if (child && typeof child === "object") { const childObj = child as FlowStoreService; - const childLc = childObj.lc || directLc || null; - if (typeof childObj.mutate === "function") { + const childLc = findAsyncMutator(childObj) || directLc; + if (childLc && mutateAsyncOf(childLc)) { + return (payload) => invokeMutation(childObj, payload, childLc); + } + if ("mutate" in childObj && typeof childObj.mutate === "function") { return (payload) => invokeMutation(childObj, payload, childLc); } - for (const ck of Object.keys(childObj)) { - const sub = readOwn(childObj, ck) as MutationQueueObj | undefined; - if (sub && typeof sub.mutate === "function") { - return (payload) => invokeMutation(sub, payload, childLc); + if (isInspectableObject(childObj)) { + for (const ck of Object.keys(childObj)) { + const sub = readOwnData(childObj, ck) as MutationQueueObj | undefined; + if (sub && typeof sub === "object" && "mutate" in sub && typeof sub.mutate === "function") { + return (payload) => invokeMutation(sub, payload, childLc); + } } } } @@ -313,18 +352,12 @@ function resolveMutatorFrom( return null; } -/** Returns true when `svc` or its nested wrapper has been destroyed by Angular. */ -function isDestroyed(svc: FlowStoreService | null | undefined): boolean { - if (!svc || typeof svc !== "object") return true; - return Boolean(svc.Ca?.Va || svc._ap?.Ca?.Va || svc.ha?.Ca?.Va); -} - /** Returns true while bound store queries are ready and not pending initial load. */ function isStoreDataReady(svc: FlowStoreService | null): boolean { - if (!svc || isDestroyed(svc)) return false; - const ap = svc._ap || svc.ha || svc; - const rc = readOwn(ap, "RC") as { isPending?: () => boolean } | undefined; - if (typeof rc?.isPending === "function" && rc.isPending()) { + if (!svc || isStoreDestroyed(svc)) return false; + const routeMatch = /\/project\/([^/?#]+)/.exec(location.pathname || ""); + const activeProjectId = runtimeState.projectId || (routeMatch ? routeMatch[1] : null); + if (hasPendingProjectTilesQuery(svc, activeProjectId)) { return false; } if (svc._uo) { @@ -337,36 +370,43 @@ function isStoreDataReady(svc: FlowStoreService | null): boolean { /** Checks whether `v` is the primary `lService` facade. */ function isLService(v: unknown): boolean { - if (!v || typeof v !== "object" || isDestroyed(v as FlowStoreService)) return false; + if (!v || typeof v !== "object" || v instanceof Node) return false; const svc = v as FlowStoreService; if ( + "RK" in svc && typeof svc.RK === "function" && typeof svc.ZA === "function" && typeof svc.ha?.ka === "function" ) { - return true; + return !isStoreDestroyed(svc); } if ( (hasMethodString(svc, "create_collection") || hasMethodString(svc, "PROJECT_TILES") || - hasMethodString(svc.na, "PROJECT_TILES")) && + hasMethodString(readOwnData(svc, "na"), "PROJECT_TILES")) && hasMethodString(svc, "set_display_name") && resolveTileMapFrom(svc) instanceof Map ) { - return true; + return !isStoreDestroyed(svc); } return false; } /** Checks whether `v` is the `_ap` signal-store variant. */ function isAPService(v: unknown): v is FlowStoreService { - if (!v || typeof v !== "object" || v instanceof Node || isDestroyed(v as FlowStoreService)) { + if (!v || typeof v !== "object" || v instanceof Node) { return false; } const svc = v as FlowStoreService; + if (!("ka" in svc) || !("ha" in svc)) { + return false; + } if (typeof svc.ka !== "function" || typeof svc.ha?.mutate !== "function") { return false; } + if (isStoreDestroyed(svc)) { + return false; + } try { return svc.ka() instanceof Map; } catch { @@ -391,27 +431,6 @@ function isUOService(v: unknown): v is FlowStoreService { ); } -/** Resolves cached tile rows from a `_uo` store service. */ -function resolveTileArrayFromUO( - uo: FlowStoreService, - projectId: string | null, -): FlowTile[] | null { - if (!uo || typeof uo !== "object" || typeof uo.ob?.ha !== "function") { - return null; - } - try { - const qk = - typeof uo.queryKey === "function" - ? uo.queryKey(projectId) - : ["PROJECT_TILES", projectId]; - const data = uo.ob.ha(qk); - if (data && Array.isArray(data.Cb)) return data.Cb; - } catch { - return null; - } - return null; -} - /** Scans the DOM, Ivy contexts, and transient Map activity to bind the project store. */ export async function discoverStore(): Promise { const match = /\/project\/([^/?#]+)/.exec(location.pathname || ""); @@ -431,7 +450,7 @@ export async function discoverStore(): Promise { projectId, getTileMap: () => apKa.call(ap), isReady: () => isStoreDataReady(runtimeState.lService), - mutate: (payload) => invokeMutation(ap.ha, payload, ap.lc), + mutate: (payload) => invokeMutation(ap.ha, payload, findAsyncMutator(ap)), rename: async (id, displayName) => await invokeMutation( ap.ha, @@ -441,7 +460,7 @@ export async function discoverStore(): Promise { Uc: id, Ve: { type: "set_display_name", displayName }, }, - ap.lc, + findAsyncMutator(ap), ), }; return; @@ -526,7 +545,7 @@ export async function discoverStore(): Promise { runtimeState.projectId === projectId && runtimeState.routePath === location.pathname && runtimeState.lService && - !isDestroyed(runtimeState.lService) && + !isStoreDestroyed(runtimeState.lService) && !runtimeState.lService._uo && resolveTileMapFrom(runtimeState.lService) instanceof Map ) { @@ -549,9 +568,12 @@ export async function discoverStore(): Promise { for (let i = 0; i < lv.length; i++) { const cand = lv[i]; if (isAPService(cand)) return cand; - if (cand && typeof cand === "object" && !(cand instanceof Node)) { - for (const prop of ["Eu", "oa", "ka"]) { - const nested = readOwn(cand, prop); + if (isInspectableObject(cand)) { + const seenProps = new Set(); + for (const prop of ["fh", "ha", "Ew", "la", "Xg", "Eu", "oa", "ka", ...Object.keys(cand)]) { + if (seenProps.has(prop)) continue; + seenProps.add(prop); + const nested = readOwnData(cand, prop); if (isAPService(nested)) return nested; } } @@ -564,9 +586,9 @@ export async function discoverStore(): Promise { for (let i = 0; i < lv.length; i++) { const cand = lv[i]; if (isUOService(cand)) return cand; - if (cand && typeof cand === "object" && !(cand instanceof Node)) { - for (const prop of ["ma", "ya", "Hoa", "oa"]) { - const nested = readOwn(cand, prop); + if (isInspectableObject(cand)) { + for (const prop of ["ma", "ya", "Hoa", "oa", "ld", "wa", "Ua", "Vd"]) { + const nested = readOwnData(cand, prop); if (isUOService(nested)) return nested; } } @@ -590,7 +612,7 @@ export async function discoverStore(): Promise { return null; }; const roots = document.querySelectorAll( - 'flow-project-page, flow-project-shell, flow-character-edit-page, flow-character-edit-header, flow-character-page, flow-character-form, flow-character-preview-panel, flow-character-image-preview, flow-edit-character-footer, flow-character-header, flow-scene-page, flow-grid-tile-container, aisandbox-root, button[aria-label="Settings trigger"], button[aria-label], [mattooltip], button.library-expand-button, app-root, main, [class*="project"], [class*="character"]', + 'flow-project-page, flow-project-shell, flow-editor-dispatcher, flow-editor-page, flow-character-edit-page, flow-character-edit-header, flow-character-page, flow-character-form, flow-character-preview-panel, flow-character-image-preview, flow-edit-character-footer, flow-character-header, flow-scene-builder, flow-grid-tile-container, aisandbox-root, button[aria-label="Settings trigger"], button[aria-label], [mattooltip], button.library-expand-button, app-root, main, [class*="project"], [class*="character"]', ); for (const el of roots) { let cur: Element | null = el; @@ -619,7 +641,7 @@ export async function discoverStore(): Promise { await withLViewMapCapture(async () => { const all = Array.from( document.querySelectorAll( - "[mattooltip], [cdkoverlayorigin], button[aria-label], flow-agent-mode-toggle-chip button, flow-prompt-box, flow-project-page", + "[mattooltip], [cdkoverlayorigin], button[aria-label], flow-agent-mode-toggle-chip button, flow-prompt-box, flow-project-page, flow-scene-builder, flow-editor-page, flow-character-edit-page", ), ); const visible = all.filter((el) => el.getClientRects().length > 0); @@ -719,10 +741,11 @@ export async function discoverStore(): Promise { }; const probeSelectors = [ - "flow-project-page", "flow-project-shell", "flow-character-edit-page", - "flow-character-edit-header", "flow-character-form", "flow-character-preview-panel", - "flow-character-image-preview", "flow-edit-character-footer", "flow-character-page", - "flow-character-header", "flow-scene-page", "flow-grid-tile-container", + "flow-project-page", "flow-project-shell", "flow-editor-dispatcher", + "flow-editor-page", "flow-character-edit-page", "flow-character-edit-header", + "flow-character-form", "flow-character-preview-panel", "flow-character-image-preview", + "flow-edit-character-footer", "flow-character-page", "flow-character-header", + "flow-scene-builder", "flow-grid-tile-container", 'button[aria-label="Settings trigger"]', "[mattooltip]", "button[aria-label]", "aisandbox-root", "header", "main", ]; diff --git a/ts/frontend_builds.ts b/ts/frontend_builds.ts index 0307d4a..53e85c0 100644 --- a/ts/frontend_builds.ts +++ b/ts/frontend_builds.ts @@ -214,6 +214,8 @@ export interface ProjectStoreFormat { destroyed: string; /** Project ID signal. */ projectId: string; + /** Query signal on the store that loads project tiles. */ + tileQuery?: string; /** Service that owns the tile query and writes. */ tilesService: string; /** Query client on the tile service. */ @@ -275,6 +277,7 @@ const NOVEMBER_18_STORE: ProjectStoreFormat = { lifecycle: "Ba", destroyed: "Va", projectId: "ua", + tileQuery: "Ir", tilesService: "ma", queryClient: "Wa", dispatcher: "sJ", @@ -287,6 +290,7 @@ const NOVEMBER_20_STORE: ProjectStoreFormat = { lifecycle: "Ba", destroyed: "Va", projectId: "ua", + tileQuery: "rs", tilesService: "ma", queryClient: "Wa", dispatcher: "YJ", @@ -643,5 +647,5 @@ export function frontendBuild(label: string | null): FrontendBuild | undefined { /** Returns the layouts to check when the runtime binds the active project store. */ export function projectStoreFormats(): readonly ProjectStoreFormat[] { const format = frontendBuild(readBuildLabel())?.projectStore; - return format ? [format] : [NOVEMBER_17_STORE, NOVEMBER_18_STORE]; + return format ? [format] : [NOVEMBER_17_STORE, NOVEMBER_18_STORE, NOVEMBER_20_STORE]; } diff --git a/ts/project_store.ts b/ts/project_store.ts index 215ec6f..b668fb7 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -137,10 +137,11 @@ export function bindProjectStore(maps: unknown[], projectId: string): ReturnType if (!Array.isArray(view)) continue; for (const slot of view) { consider(slot, map); - // The project shell holds the store in its component instance. - if (!slot || typeof slot !== "object") continue; - for (const key of ["ha", "Eu", "oa", "ka", "fh"]) { - consider(Object.getOwnPropertyDescriptor(slot, key)?.value, map); + // Components across project, editor, character, and scene views hold the store on own properties. + if (!slot || typeof slot !== "object" || Array.isArray(slot) || slot instanceof Node) continue; + for (const key of ["ha", "fh", "Ew", "la", "Eu", "oa", "ka", ...Object.keys(slot)]) { + const desc = Object.getOwnPropertyDescriptor(slot, key); + if (desc && "value" in desc) consider(desc.value, map); } } } diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 9247fa5..27a9647 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -15,6 +15,7 @@ import { legacyTile, } from "./dom"; import { clearStore, runtimeState } from "./state"; +import { isStoreDestroyed } from "./store_shape"; import type { FlowMediaPayload, FlowTile, @@ -53,10 +54,7 @@ export function readStoreSnapshot(): StoreSnapshotResult { const l = runtimeState.lService; if ( (helper || l) && - (runtimeState.routePath !== location.pathname || - l?.Ca?.Va || - l?._ap?.Ca?.Va || - l?.ha?.Ca?.Va) + (runtimeState.routePath !== location.pathname || isStoreDestroyed(l)) ) { clearStore(); return { ok: false, error: "route_changed" }; diff --git a/ts/store_shape.ts b/ts/store_shape.ts new file mode 100644 index 0000000..7273be2 --- /dev/null +++ b/ts/store_shape.ts @@ -0,0 +1,392 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Structural lifecycle, tile query readiness, and tile map helpers for Flow stores. + +import { readOwn } from "./angular"; +import { frontendBuild, projectStoreFormats, readBuildLabel } from "./frontend_builds"; +import type { FlowStoreService, FlowTile } from "./types"; + +/** Lifecycle flag names on Closure-compiled Angular `DestroyRef` handles. */ +const LIFECYCLE_FLAGS = ["Va", "Wa"] as const; + +/** Reads an own data property value without invoking getters or Proxy `get` traps. */ +export function readOwnData(obj: unknown, key: string): unknown { + if (!obj || typeof obj !== "object") return undefined; + try { + const desc = Object.getOwnPropertyDescriptor(obj, key); + return desc && "value" in desc ? desc.value : undefined; + } catch { + return undefined; + } +} + +/** Returns true when `val` is a plain or class instance object suitable for structural scanning. */ +export function isInspectableObject(val: unknown): val is Record { + return Boolean( + val && + typeof val === "object" && + !Array.isArray(val) && + !(val instanceof Node) && + !(val instanceof Map) && + !(val instanceof Set) && + !(val instanceof Date) && + !(val instanceof RegExp) && + !(val instanceof Promise) && + !(val instanceof WeakMap) && + !(val instanceof WeakSet) && + val !== window && + val !== document, + ); +} + +/** Reads a boolean lifecycle flag from an own data property or prototype `DestroyRef` getter. */ +function readDestroyedFlag(handle: object, flag: string): boolean { + try { + const ownDesc = Object.getOwnPropertyDescriptor(handle, flag); + if (ownDesc) { + if ("value" in ownDesc) return ownDesc.value === true; + if (typeof ownDesc.get === "function") { + return ownDesc.get.call(handle) === true; + } + return false; + } + let proto: object | null = Object.getPrototypeOf(handle); + for (let depth = 0; proto && proto !== Object.prototype && depth < 4; depth++) { + const protoDesc = Object.getOwnPropertyDescriptor(proto, flag); + if (protoDesc) { + if ("value" in protoDesc) return protoDesc.value === true; + if (typeof protoDesc.get === "function") { + return protoDesc.get.call(handle) === true; + } + return false; + } + proto = Object.getPrototypeOf(proto); + } + } catch { + return false; + } + return false; +} + +/** Checks whether one store or component object carries a disposed lifecycle handle. */ +function isObjectDestroyed(target: object): boolean { + if (!isInspectableObject(target)) return false; + const formats = projectStoreFormats(); + for (const format of formats) { + const handle = readOwnData(target, format.lifecycle); + if (isInspectableObject(handle) && readDestroyedFlag(handle, format.destroyed)) { + return true; + } + } + for (const flag of LIFECYCLE_FLAGS) { + if (readDestroyedFlag(target, flag)) return true; + } + let keys: string[]; + try { + keys = Object.getOwnPropertyNames(target); + } catch { + return false; + } + for (const key of keys) { + const child = readOwnData(target, key); + if (!isInspectableObject(child)) continue; + for (const flag of LIFECYCLE_FLAGS) { + if (readDestroyedFlag(child, flag)) return true; + } + } + return false; +} + +/** Returns true when Angular disposes `svc` or its nested store handle. */ +export function isStoreDestroyed(svc: unknown): boolean { + if (!svc || typeof svc !== "object") return true; + const candidates = [ + svc, + readOwnData(svc, "_ap"), + readOwnData(svc, "_uo"), + readOwnData(svc, "ha"), + ]; + for (const cand of candidates) { + if (cand && typeof cand === "object" && isObjectDestroyed(cand)) { + return true; + } + } + return false; +} + +/** Checks whether `qk` identifies an active `PROJECT_TILES` query rather than a disabled query. */ +function isProjectTilesQueryKey(qk: unknown, projectId: string | null): boolean { + if (!Array.isArray(qk) || qk[0] !== "PROJECT_TILES") return false; + if (qk.length === 1) return true; + return ( + typeof qk[1] === "string" && + qk[1].length > 0 && + (!projectId || qk[1] === projectId) + ); +} + +/** Checks whether a TanStack query signal or cache entry is still pending its initial data. */ +function isQueryPending(query: unknown): boolean { + if (!query || typeof query !== "object") return false; + try { + if ("isPending" in query) { + const fn = readOwn(query, "isPending"); + if (typeof fn === "function" && fn.call(query) === true) return true; + if (fn === true) return true; + } + if ("state" in query) { + const state = readOwn(query, "state"); + if (isInspectableObject(state) && "status" in state && readOwn(state, "status") === "pending") { + return true; + } + } + if ("status" in query) { + const status = readOwn(query, "status"); + const val = typeof status === "function" ? status.call(query) : status; + if (val === "pending") return true; + } + } catch { + return false; + } + return false; +} + +/** Checks whether a `QueryCache` holds a pending `PROJECT_TILES` query for `projectId`. */ +function hasPendingInQueryCache(cache: unknown, projectId: string | null): boolean { + if (!isInspectableObject(cache)) return false; + try { + const getAll = readOwn(cache, "getAll"); + const list: Iterable | null = + typeof getAll === "function" + ? (getAll.call(cache) as Iterable) + : readOwnData(cache, "queries") instanceof Map + ? (readOwnData(cache, "queries") as Map).values() + : null; + if (!list) return false; + for (const q of list) { + if (!q || typeof q !== "object") continue; + const qk = readOwnData(q, "queryKey") ?? readOwn(q, "queryKey"); + if (isProjectTilesQueryKey(qk, projectId) && isQueryPending(q)) { + return true; + } + } + } catch { + return false; + } + return false; +} + +/** Returns true when `svc` has a pending `tileQuery` or `PROJECT_TILES` query. */ +export function hasPendingProjectTilesQuery( + svc: FlowStoreService | null | undefined, + projectId: string | null, +): boolean { + if (!svc || typeof svc !== "object") return false; + const ap = (readOwnData(svc, "_ap") as FlowStoreService | undefined) || + (readOwnData(svc, "ha") as FlowStoreService | undefined) || + svc; + const build = frontendBuild(readBuildLabel()); + const hintSet = new Set(); + if (build?.projectStore.tileQuery) hintSet.add(build.projectStore.tileQuery); + if (build?.operations.agent_attachments?.tileQuery) { + hintSet.add(build.operations.agent_attachments.tileQuery); + } + for (const fmt of projectStoreFormats()) { + if (fmt.tileQuery) hintSet.add(fmt.tileQuery); + } + hintSet.add("RC"); + + const roots = ap === svc ? [ap] : [ap, svc]; + for (const root of roots) { + if (!isInspectableObject(root)) continue; + for (const key of hintSet) { + let cand = readOwnData(root, key); + if (cand === undefined && key in root) cand = readOwn(root, key); + if (isQueryPending(cand)) return true; + } + } + + const visited = new Set(); + const queue: Array<[object, number]> = roots + .filter((r): r is Record => isInspectableObject(r)) + .map((r) => [r, 0]); + + while (queue.length > 0 && visited.size < 40) { + const next = queue.shift(); + if (!next) break; + const [cur, depth] = next; + if (visited.has(cur)) continue; + visited.add(cur); + + let keys: string[]; + try { + keys = Object.getOwnPropertyNames(cur); + } catch { + continue; + } + for (const key of keys) { + const val = readOwnData(cur, key); + if (!isInspectableObject(val)) continue; + if (key === "queryCache" && hasPendingInQueryCache(val, projectId)) { + return true; + } + const cache = readOwnData(val, "queryCache"); + if (cache && hasPendingInQueryCache(cache, projectId)) { + return true; + } + let qk: unknown = readOwnData(val, "queryKey"); + if (qk === undefined && "queryKey" in val) { + const qkProp = readOwn(val, "queryKey"); + if (Array.isArray(qkProp)) { + qk = qkProp; + } else if (typeof qkProp === "function" && qkProp.length === 0) { + try { + qk = qkProp.call(val); + } catch { + qk = undefined; + } + } + } + if (isProjectTilesQueryKey(qk, projectId) && isQueryPending(val)) { + return true; + } + if (depth < 2) { + queue.push([val, depth + 1]); + } + } + } + return false; +} + +/** Finds a method on `obj` or its prototype chain whose source contains `marker`. */ +export function findMethodByMarker( + obj: unknown, + marker: string, +): ((...args: unknown[]) => unknown) | null { + if (!obj || typeof obj !== "object") return null; + let cur: object | null = obj; + for (let depth = 0; cur && cur !== Object.prototype && depth < 3; depth++) { + for (const k of Object.getOwnPropertyNames(cur)) { + if (k === "constructor") continue; + const desc = Object.getOwnPropertyDescriptor(cur, k); + const fn = desc && "value" in desc ? desc.value : readOwn(obj, k); + if (typeof fn === "function") { + try { + if (fn.toString().includes(marker)) { + return fn.bind(obj) as (...args: unknown[]) => unknown; + } + } catch { + // Ignore functions without readable source text. + } + } + } + cur = Object.getPrototypeOf(cur); + } + return null; +} + +/** Returns true when `obj` defines a method whose source contains `marker`. */ +export function hasMethodString(obj: unknown, marker: string): boolean { + return Boolean(findMethodByMarker(obj, marker)); +} + +/** Checks whether `m` matches the shape of a project tile `Map`. */ +function isTileMap(m: unknown): m is Map { + if (!(m instanceof Map)) return false; + if (m.size === 0) return true; + for (const v of m.values()) { + return Boolean(v && typeof v === "object" && ("id" in v || "type" in v)); + } + return false; +} + +/** Extracts the project tile `Map` from a bound Angular store service. */ +export function resolveTileMapFrom(svc: FlowStoreService | null): Map | null { + if (!svc || typeof svc !== "object") return null; + const apKa = svc._ap?.ka; + if (typeof apKa === "function") { + try { + const m = apKa.call(svc._ap); + if (m instanceof Map) return m; + } catch { + // Try the next map accessor. + } + } + if (typeof svc.ka === "function") { + try { + const m = svc.ka(); + if (m instanceof Map) return m; + } catch { + // Try the next map accessor. + } + } + const haKa = svc.ha?.ka; + if (typeof haKa === "function") { + try { + const m = haKa.call(svc.ha); + if (m instanceof Map) return m; + } catch { + // Fall back to breadth-first property scan. + } + } + const queue: object[] = [svc]; + const seen = new Set(); + let emptyMapFallback: Map | null = null; + while (queue.length && seen.size < 40) { + const cur = queue.shift(); + if (!cur || typeof cur !== "object" || seen.has(cur)) continue; + seen.add(cur); + for (const k of Object.keys(cur)) { + const val = readOwnData(cur, k); + if (isTileMap(val)) { + if (val.size > 0) return val; + emptyMapFallback = emptyMapFallback || val; + } else if (isInspectableObject(val) && seen.size < 40) { + let proto = Object.getPrototypeOf(val) as object | null; + while (proto && proto !== Object.prototype) { + for (const mk of Object.getOwnPropertyNames(proto)) { + if (mk === "constructor") continue; + try { + const desc = Object.getOwnPropertyDescriptor(proto, mk); + const fn = desc && "value" in desc ? desc.value : undefined; + if (typeof fn === "function" && fn.length === 0) { + const res = fn.call(val); + if (isTileMap(res)) { + if (res.size > 0) return res; + emptyMapFallback = emptyMapFallback || res; + } + } + } catch { + // Ignore methods that require runtime arguments or context. + } + } + proto = Object.getPrototypeOf(proto) as object | null; + } + queue.push(val); + } + } + } + return emptyMapFallback; +} + +/** Resolves cached tile rows from a `_uo` query-cache service. */ +export function resolveTileArrayFromUO( + uo: FlowStoreService, + projectId: string | null, +): FlowTile[] | null { + if (!uo || typeof uo !== "object" || typeof uo.ob?.ha !== "function") { + return null; + } + try { + const qk = + typeof uo.queryKey === "function" + ? uo.queryKey(projectId) + : ["PROJECT_TILES", projectId]; + const data = uo.ob.ha(qk); + if (data && Array.isArray(data.Cb)) return data.Cb; + } catch { + return null; + } + return null; +} diff --git a/ts/types.ts b/ts/types.ts index 918312d..04f2c8d 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -30,8 +30,10 @@ export interface AngularRouter { /** Destroyable Angular component or service lifecycle handle. */ export interface AngularLifecycleHandle { - /** Ivy destroy marker containing the disposed flag `Va`. */ - Ca?: { Va?: boolean }; + /** Ivy destroy marker containing the disposed flag `Va` or `Wa`. */ + Ca?: { Va?: boolean; Wa?: boolean }; + /** Ivy destroy marker in Flow builds from 2026-11-18 on. */ + Ba?: { Va?: boolean; Wa?: boolean }; } /** Minified nested media metadata stored on a Flow tile. */ @@ -238,36 +240,71 @@ export interface FlowTile extends FlowMediaPayload { createDate?: string; } +/** Observable error event payload from a store mutation queue. */ +export interface MutationErrorEvent { + /** Dispatched mutation payload for the error. */ + mutation?: unknown; + /** Backend or validation failure value. */ + error?: unknown; +} + +/** Subscribable error stream exposed on a store mutation queue. */ +export interface MutationErrorStream { + /** Registers an observer for mutation error events. */ + subscribe?: (cb: (ev: MutationErrorEvent) => void) => { unsubscribe?: () => void }; +} + /** Mutation signal or queue object inside Angular store services. */ export interface MutationQueueObj { /** Pending item reader. */ ka?: () => { items?: Array<{ mutation?: unknown }> } | null | undefined; /** Async promise mutation runner. */ oe?: (payload: Record) => Promise; + /** Alternate async promise mutation runner. */ + re?: (payload: Record) => Promise; /** Async mutation helper. */ mutateAsync?: (payload: Record) => Promise; /** Queue mutation dispatcher. */ mutate?: (payload: Record) => unknown; + /** Reset method on TanStack mutation results. */ + reset?: () => void; /** Signal error accessor. */ error?: () => unknown; - /** Status stream with `subscribe`. */ - Ha?: { subscribe?: (cb: (ev: { mutation?: unknown; error?: unknown }) => void) => { unsubscribe?: () => void } }; - /** Alternate status stream with `subscribe`. */ - ua?: { subscribe?: (cb: (ev: { mutation?: unknown; error?: unknown }) => void) => { unsubscribe?: () => void } }; + /** Queue configuration callbacks for `_.EO`. */ + parameters?: Record; + /** Observable error stream in Flow builds from 2026-11-20 on. */ + Da?: MutationErrorStream; + /** Subject error stream in Flow builds from 2026-11-20 on. */ + oa?: MutationErrorStream; + /** Legacy status stream with `subscribe`. */ + Ha?: MutationErrorStream; + /** Alternate legacy status stream with `subscribe`. */ + ua?: MutationErrorStream; } /** Resolved Angular project store service instance or wrapper. */ export interface FlowStoreService extends AngularLifecycleHandle { /** Underlying `_ap` store variant. */ - _ap?: FlowStoreService & { RC?: { isPending?: () => boolean }; lc?: MutationQueueObj }; + _ap?: FlowStoreService & { + RC?: { isPending?: () => boolean }; + rs?: { isPending?: () => boolean }; + lc?: MutationQueueObj; + ld?: MutationQueueObj; + }; /** Underlying `_uo` store variant. */ _uo?: FlowStoreService; /** Tile map getter or inner signal container. */ ka?: (() => Map | null | undefined) | MutationQueueObj; /** Nested signal container or mutator. */ ha?: (FlowStoreService & MutationQueueObj) | null; - /** Lifecycle controller or mutation runner. */ + /** Legacy TanStack mutation runner. */ lc?: MutationQueueObj; + /** TanStack tile mutation runner in Flow builds from 2026-11-20 on. */ + ld?: MutationQueueObj; + /** Tile query signal in Flow builds from 2026-11-20 on. */ + rs?: { isPending?: () => boolean }; + /** Legacy tile query signal. */ + RC?: { isPending?: () => boolean }; /** Nested mutation runner. */ mutate?: (payload: Record) => unknown; /** Direct rename method on legacy store services. */ @@ -276,6 +313,8 @@ export interface FlowStoreService extends AngularLifecycleHandle { ZA?: (...args: unknown[]) => unknown; /** Optional nested query metadata. */ na?: unknown; + /** Optional tile service in Flow builds from 2026-11-18 on. */ + ma?: unknown; /** Optional tile fetcher signal. */ PG?: (projectId: string | null, payload: Record) => Promise; /** Query key builder on UO stores. */ From 4f05abce8bad0f5fe460d4dd54acbe605ae6da6b Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:27:46 +0000 Subject: [PATCH 2/8] fix(flow): check Angular views and project loading states - Unwrap upgraded LContext views in resolveLView and bindAngularViews - Read character form, grid tile, and project card LViews safely - Find verified ProjectStore instances on own component fields - Catch NG0950 errors before required project page inputs bind - Report and retry store_loading while project routes load --- src/project.rs | 15 ++++-- src/project_store.rs | 19 ++++---- ts/agent_chat.ts | 8 +++- ts/angular.ts | 80 ++++++++++++++++++++++++++----- ts/character_voices.ts | 7 +-- ts/discover_store.ts | 2 + ts/open_edit_asset.ts | 4 +- ts/project_store.ts | 104 +++++++++++++++++++++++++++++++++++------ ts/project_upload.ts | 9 +++- ts/projects_ops.ts | 29 ++++++------ 10 files changed, 220 insertions(+), 57 deletions(-) diff --git a/src/project.rs b/src/project.rs index e11643e..e992a04 100644 --- a/src/project.rs +++ b/src/project.rs @@ -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)] @@ -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) @@ -387,10 +388,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { return Ok(()); } if status_err == Some("store_loading") { + store_loading = true; tokio::time::sleep(Duration::from_millis(250)).await; continue; } input_pending = status_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); + store_loading = false; let discovery = store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?; @@ -425,6 +428,12 @@ 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 @@ -432,7 +441,7 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { } /// Treats an unset Angular input as a loading result for a project store read. -fn store_loading_result(result: Result) -> Result { +pub(crate) fn store_loading_result(result: Result) -> Result { match result { Err(error) if error.to_string().lines().next().is_some_and(|line| { diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..775167e 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -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> { @@ -36,20 +36,23 @@ 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?; + let mut status = store_loading_result(bind_current_store(engine, &project_id).await)?; for _ in 0..25 { let err = status.get("error").and_then(Value::as_str); if err == Some("collection_store_not_bound") && !dom_probed { dom_probed = true; - let _ = engine.call_flow_async("discoverStore", json!([])).await; - status = engine - .call_flow_js("projectStoreStatus", json!([project_id])) - .await?; + let _ = + store_loading_result(engine.call_flow_async("discoverStore", json!([])).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; diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 169a09f..63d9cec 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -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. */ diff --git a/ts/angular.ts b/ts/angular.ts index 8b0bbf0..b01942d 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -17,10 +17,16 @@ 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. */ - __ngContext__?: number | NgLView | Record; - /** Embedded view LView reference. */ + /** Angular Ivy LView array, registry slot index, or upgraded LContext wrapper. */ + __ngContext__?: number | NgLView | NgContextCarrier | Record; + /** Embedded view or LContext LView reference. */ lView?: NgLView; + /** Minified LContext LView reference in Flow builds from 2026-11-20 on. */ + zp?: NgLView; + /** Minified LContext LView reference in earlier Flow builds. */ + Pn?: NgLView; + /** Optional LView registry slot identifier on LContext wrappers. */ + lViewId?: number; } /** Reads an own or prototype property safely without triggering exceptions. */ @@ -38,6 +44,46 @@ export function isLiveLView(lv: unknown): lv is NgLView { return Array.isArray(lv) && (!(lv[0] instanceof Node) || lv[0].isConnected); } +/** Returns true when `val` matches the header layout of an Angular Ivy `LView` array. */ +function isLViewArray(val: unknown): val is NgLView { + return ( + Array.isArray(val) && + val.length >= 20 && + Boolean(val[1]) && + typeof val[1] === "object" && + !Array.isArray(val[1]) && + (typeof val[19] === "number" || typeof val[2] === "number") + ); +} + +/** Extracts an `NgLView` array from an upgraded Angular `LContext` wrapper object. */ +function unwrapContextView(raw: object): NgLView | null { + const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView; + const keys = contextField + ? ["lView", contextField, "zp", "Pn"] + : ["lView", "zp", "Pn"]; + for (const key of keys) { + const candidate = readOwn(raw, key); + if (Array.isArray(candidate)) return candidate; + } + const id = readOwn(raw, "lViewId"); + if (typeof id === "number" && runtimeState.ngLViewMap instanceof Map) { + const mapped = runtimeState.ngLViewMap.get(id); + if (Array.isArray(mapped)) return mapped; + } + try { + for (const key of Object.getOwnPropertyNames(raw)) { + if (key === "directives") continue; + const desc = Object.getOwnPropertyDescriptor(raw, key); + const val: unknown = desc && "value" in desc ? desc.value : undefined; + if (isLViewArray(val)) return val; + } + } catch { + return null; + } + return null; +} + /** Returns true when `m` matches Angular's integer-keyed LView registry map. */ export function isNgLViewMap(m: unknown): m is Map { // Runtime.queryObjects(Map.prototype) also returns objects that only inherit from @@ -57,9 +103,25 @@ export function isNgLViewMap(m: unknown): m is Map { 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; + let slotId: number | null = typeof context === "number" ? context : null; + let directView: NgLView | null = Array.isArray(context) ? context : null; + if ( + slotId === null && + !directView && + context && + typeof context === "object" && + !(context instanceof Node) + ) { + const rawId = readOwn(context, "lViewId"); + if (typeof rawId === "number") slotId = rawId; + directView = unwrapContextView(context); + } + if (slotId === null && typeof directView?.[19] === "number") { + slotId = directView[19]; + } + if (slotId === null) continue; const views = maps.find((map): map is Map => - isNgLViewMap(map) && isLiveLView(map.get(context)), + isNgLViewMap(map) && isLiveLView(map.get(slotId)), ); if (views) { runtimeState.ngLViewMap = views; @@ -83,12 +145,8 @@ export function resolveLView(elOrCtx: unknown): NgLView | null { ? runtimeState.ngLViewMap.get(raw) || null : null; } - if (raw && typeof raw === "object") { - 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 (raw && typeof raw === "object" && !(raw instanceof Node)) { + return unwrapContextView(raw); } return null; } diff --git a/ts/character_voices.ts b/ts/character_voices.ts index a434d37..89d3746 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -3,7 +3,7 @@ // List and assign Google Flow character voices inside the character editor. -import { readOwn, startMapCapture, type NgContextCarrier } from "./angular"; +import { readOwn, resolveLView, startMapCapture, type NgContextCarrier } from "./angular"; import { VOICE_ICON_WORDS, voicePane } from "./character_extra"; import { clickButtonByRegex, @@ -118,13 +118,14 @@ 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; } + const formNg = (form as NgContextCarrier).__ngContext__; if (typeof formNg !== "number" || probedForms.has(form)) { return null; } diff --git a/ts/discover_store.ts b/ts/discover_store.ts index a6b793e..392b5b9 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -23,11 +23,13 @@ import type { DiscoverStoreResult, NgLView } from "./types"; const STORE_HOST_SELECTORS = [ "flow-project-shell", "flow-project-page", + "flow-character-page", "flow-character-edit-page", "flow-character-edit-header", "flow-character-form", "flow-character-preview-panel", "flow-character-image-preview", + "flow-create-character-footer", "flow-edit-character-footer", "flow-character-header", "flow-editor-dispatcher", diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..7779fab 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,7 +8,7 @@ import { findRouter, navigateSpa, readOwn, - type NgContextCarrier, + resolveLView, } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; import { clearStore } from "./state"; @@ -119,7 +119,7 @@ export async function openEditAsset( } } } - const ng = (el as NgContextCarrier).__ngContext__; + const ng = resolveLView(el); if (Array.isArray(ng)) { for (let i = 0; i < ng.length; i++) { const item = ng[i]; diff --git a/ts/project_store.ts b/ts/project_store.ts index a161906..dbfd8ae 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -53,18 +53,40 @@ let boundHandle: FlowStoreHandle | null = null; /** Promise chain that serializes general store mutations in this document. */ let mutationChain: Promise = Promise.resolve(); +/** Route host elements that mount once the active `/project/` view bundle initializes. */ +const PROJECT_ROUTE_HOST_SELECTOR = [ + "flow-project-shell", + "flow-project-page", + "flow-character-page", + "flow-character-edit-page", + "flow-scene-builder", + "flow-editor-dispatcher", + "flow-editor-page", +].join(", "); + /** Returns the project ID in the current route. */ export function projectInRoute(): string | null { return /\/project\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; } +/** Invokes a zero-argument getter or Angular signal on `owner` without throwing. */ +function callStoreGetter(owner: object, key: string): unknown { + const getter = readOwn(owner, key); + if (typeof getter !== "function") return undefined; + try { + return getter.call(owner); + } catch { + return undefined; + } +} + /** Checks the active route, lifecycle flag, and project signal of `store`. */ export function isCurrent({ projectId, service, format }: ProjectStore): boolean { - const currentProject = readOwn(service, format.projectId); const lifecycle = readOwn(service, format.lifecycle); - return projectInRoute() === projectId && + return Boolean(projectId) && + projectInRoute() === projectId && Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed) && - typeof currentProject === "function" && currentProject.call(service) === projectId; + callStoreGetter(service, format.projectId) === projectId; } /** Clears both the direct store binding and `runtimeState.store`. */ @@ -94,7 +116,7 @@ export function currentProjectStore(projectId: string): ProjectStore | null { return active?.projectId === projectId ? active : null; } -/** Finds the query by its full project key. */ +/** Finds the query by its full project key, priming the lazy signal query when needed. */ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTileQuery | undefined { const tiles = readOwn(service, format.tilesService); const queryKey = readOwn(tiles, "queryKey"); @@ -103,7 +125,18 @@ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTile if (typeof queryKey !== "function" || typeof find !== "function") return undefined; const key: unknown = queryKey.call(tiles, projectId); if (!isProjectKey(key, projectId)) return undefined; - const query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + let query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + if (!query) { + const signalQuery = readOwn(service, format.tileQuery); + if (signalQuery && typeof signalQuery === "object") { + try { + void ("status" in signalQuery); + } catch { + // Ignore transient signal evaluation errors while inputs settle. + } + query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + } + } return isProjectKey(query?.queryKey, projectId) ? query : undefined; } @@ -112,13 +145,27 @@ function isProjectKey(key: unknown, projectId: string): boolean { return Array.isArray(key) && key.length === 2 && key[0] === "PROJECT_TILES" && key[1] === projectId; } +/** Reads a boolean or status field from a TanStack signal query proxy without throwing. */ +function readQueryField(signalQuery: object, key: string): unknown { + try { + if (!(key in signalQuery)) return undefined; + const prop = readOwn(signalQuery, key); + return typeof prop === "function" ? prop.call(signalQuery) : prop; + } catch { + return undefined; + } +} + /** Returns true while the verified tile query of `store` loads initial rows. */ export function isProjectStorePending(store: ProjectStore): boolean { if (!isCurrent(store)) return false; const signalQuery = readOwn(store.service, store.format.tileQuery); - if (signalQuery && typeof signalQuery === "object" && "isPending" in signalQuery) { - const isPending = readOwn(signalQuery, "isPending"); - if (typeof isPending === "function" ? Boolean(isPending.call(signalQuery)) : isPending === true) { + if (signalQuery && typeof signalQuery === "object") { + if ( + readQueryField(signalQuery, "isPending") === true || + readQueryField(signalQuery, "isLoading") === true || + readQueryField(signalQuery, "status") === "pending" + ) { return true; } } @@ -342,14 +389,36 @@ export function findProjectStoreInView( for (const slot of view) { consider(slot); - if (!slot || typeof slot !== "object" || slot instanceof Node) continue; + if ( + !slot || + typeof slot !== "object" || + Array.isArray(slot) || + slot instanceof Node || + slot instanceof Map || + slot instanceof Set + ) { + continue; + } + const checked = new Set(); for (const key of format.componentSlots) { + checked.add(key); + consider(Object.getOwnPropertyDescriptor(slot, key)?.value); + } + for (const key of Object.keys(slot)) { + if (checked.has(key)) continue; consider(Object.getOwnPropertyDescriptor(slot, key)?.value); } } return matches; } +/** Returns true while the `/project/` route bundle or shell host has not mounted yet. */ +function isProjectRouteLoading(): boolean { + if (document.querySelector(PROJECT_ROUTE_HOST_SELECTOR)) return false; + if (document.readyState !== "complete") return true; + return Boolean(document.querySelector("aisandbox-root, app-root")); +} + /** Reports whether the current runtime has a bound and ready store for `projectId`. */ export function projectStoreStatus(projectId: string): ProjectStoreStatus { const build = readBuildLabel(); @@ -359,7 +428,11 @@ export function projectStoreStatus(projectId: string): ProjectStoreStatus { } if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; const store = currentProjectStore(projectId); - if (!store) return { ok: false, error: "collection_store_not_bound" }; + if (!store) { + return isProjectRouteLoading() + ? { ok: false, error: "store_loading" } + : { ok: false, error: "collection_store_not_bound" }; + } if (isProjectStorePending(store)) { return { ok: false, bound: true, error: "store_loading" }; } @@ -387,7 +460,9 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; if (!verifiedStoreLayout()) { clearProjectStore(); - return { ok: false, error: "collection_store_not_bound" }; + return isProjectRouteLoading() + ? { ok: false, error: "store_loading" } + : { ok: false, error: "collection_store_not_bound" }; } const seen = new Set(); @@ -405,8 +480,11 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto const selected = candidates.find(({ store }) => store === selectedStore); if (!selected) { clearProjectStore(); - return candidates.length > 1 - ? { ok: false, error: "ambiguous_collection_store" } + if (candidates.length > 1) { + return { ok: false, error: "ambiguous_collection_store" }; + } + return isProjectRouteLoading() + ? { ok: false, error: "store_loading" } : { ok: false, error: "collection_store_not_bound" }; } installProjectStore(selected.store, selected.views); diff --git a/ts/project_upload.ts b/ts/project_upload.ts index c0e15c4..62d2185 100644 --- a/ts/project_upload.ts +++ b/ts/project_upload.ts @@ -428,9 +428,14 @@ function projectWorkspaceRoute(pathname: string): { projectId: string; collectio /** Checks the route and lifecycle of a project workspace component. */ function isCurrentPage(page: object, format: ProjectUploadFormat["page"], projectId: string): boolean { if (projectWorkspaceRoute(location.pathname)?.projectId !== projectId) return false; + if (readOwn(readOwn(page, format.lifecycle), format.destroyed) !== false) return false; const project = readOwn(page, format.project); - return readOwn(readOwn(page, format.lifecycle), format.destroyed) === false && - typeof project === "function" && project.call(page) === projectId; + if (typeof project !== "function") return false; + try { + return project.call(page) === projectId; + } catch { + return false; + } } /** Finds the live project page that owns the upload services. */ diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..efb4eee 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -48,7 +48,7 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } if (Array.isArray(obj)) { - for (let i = 0; i < Math.min(obj.length, 25); i++) { + for (let i = 0; i < Math.min(obj.length, 80); i++) { const hit = extractIdFromObject(obj[i], depth + 1, seen); if (hit) return hit; } @@ -137,19 +137,22 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } if (!pid) { - const ng = (card as NgContextCarrier).__ngContext__; - if (Array.isArray(ng)) { - pid = extractIdFromObject(ng, 0, new Set()); - } else if (typeof ng === "number") { - for (const sm of seenMaps) { - try { - const lv = sm.get(ng); - if (Array.isArray(lv)) { - pid = extractIdFromObject(lv, 0, new Set()); - if (pid) break; + const resolved = resolveLView(card); + if (resolved) { + pid = extractIdFromObject(resolved, 0, new Set()); + } else { + const ng = (card as NgContextCarrier).__ngContext__; + if (typeof ng === "number") { + for (const sm of seenMaps) { + try { + const lv = sm.get(ng); + if (Array.isArray(lv)) { + pid = extractIdFromObject(lv, 0, new Set()); + if (pid) break; + } + } catch { + // Ignore map read error. } - } catch { - // Ignore map read error. } } } From 0562f0f989f974e394c2a081b44eb1dd2511fdcd Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:51:54 +0000 Subject: [PATCH 3/8] fix(flow): bind stores during unbound route loading - Probe Map instances when projectStoreStatus reports unbound loading - Check sub-route and landing hosts in isProjectRouteLoading - Read lViewId from upgraded LContext wrappers during map capture --- src/project_store.rs | 4 +++- ts/character_voices.ts | 10 ++++++++-- ts/project_store.ts | 14 ++++++++++---- ts/projects_ops.ts | 10 ++++++++-- 4 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/project_store.rs b/src/project_store.rs index 775167e..b58e778 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -111,7 +111,9 @@ pub(crate) async fn bind_current_store(engine: &ChromeEngine, project_id: &str) let status = engine .call_flow_js("projectStoreStatus", json!([project_id])) .await?; - if status.get("error").and_then(Value::as_str) == Some("collection_store_not_bound") { + let err = status.get("error").and_then(Value::as_str); + let bound = status.get("bound").and_then(Value::as_bool) == Some(true); + if err == Some("collection_store_not_bound") || (err == Some("store_loading") && !bound) { return engine.bind_project_store(project_id).await; } Ok(status) diff --git a/ts/character_voices.ts b/ts/character_voices.ts index 89d3746..fe67a82 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -126,7 +126,13 @@ export async function characterVoiceOp( return direct; } const formNg = (form as NgContextCarrier).__ngContext__; - if (typeof formNg !== "number" || probedForms.has(form)) { + const formSlotId = + typeof formNg === "number" + ? formNg + : typeof readOwn(formNg, "lViewId") === "number" + ? (readOwn(formNg, "lViewId") as number) + : null; + if (formSlotId === null || probedForms.has(form)) { return null; } probedForms.add(form); @@ -182,7 +188,7 @@ export async function characterVoiceOp( } finally { stop(); } - const idx = formNg; + const idx = formSlotId; const findAcrossCaptured = ( predicate: (c: unknown) => c is CharacterFormComponent, ): CharacterFormComponent | null => { diff --git a/ts/project_store.ts b/ts/project_store.ts index dbfd8ae..cdb20c4 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -53,15 +53,20 @@ let boundHandle: FlowStoreHandle | null = null; /** Promise chain that serializes general store mutations in this document. */ let mutationChain: Promise = Promise.resolve(); -/** Route host elements that mount once the active `/project/` view bundle initializes. */ +/** Route host elements that appear when the active `/project/` view bundle initializes. */ const PROJECT_ROUTE_HOST_SELECTOR = [ "flow-project-shell", "flow-project-page", "flow-character-page", "flow-character-edit-page", + "flow-character-preview-panel", + "flow-create-character-footer", + "flow-edit-character-footer", "flow-scene-builder", "flow-editor-dispatcher", "flow-editor-page", + "flow-applet-view-header", + "flow-agent-panel", ].join(", "); /** Returns the project ID in the current route. */ @@ -116,7 +121,7 @@ export function currentProjectStore(projectId: string): ProjectStore | null { return active?.projectId === projectId ? active : null; } -/** Finds the query by its full project key, priming the lazy signal query when needed. */ +/** Finds the query by its full project key and initializes the signal query when needed. */ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTileQuery | undefined { const tiles = readOwn(service, format.tilesService); const queryKey = readOwn(tiles, "queryKey"); @@ -132,7 +137,7 @@ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTile try { void ("status" in signalQuery); } catch { - // Ignore transient signal evaluation errors while inputs settle. + // Ignore signal read errors before inputs are ready. } query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; } @@ -412,9 +417,10 @@ export function findProjectStoreInView( return matches; } -/** Returns true while the `/project/` route bundle or shell host has not mounted yet. */ +/** Returns true while the `/project/` route view is not in the document yet. */ function isProjectRouteLoading(): boolean { if (document.querySelector(PROJECT_ROUTE_HOST_SELECTOR)) return false; + if (document.querySelector("flow-landing-page")) return false; if (document.readyState !== "complete") return true; return Boolean(document.querySelector("aisandbox-root, app-root")); } diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index efb4eee..34d48f0 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -142,10 +142,16 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { pid = extractIdFromObject(resolved, 0, new Set()); } else { const ng = (card as NgContextCarrier).__ngContext__; - if (typeof ng === "number") { + const slotId = + typeof ng === "number" + ? ng + : typeof readOwn(ng, "lViewId") === "number" + ? (readOwn(ng, "lViewId") as number) + : null; + if (slotId !== null) { for (const sm of seenMaps) { try { - const lv = sm.get(ng); + const lv = sm.get(slotId); if (Array.isArray(lv)) { pid = extractIdFromObject(lv, 0, new Set()); if (pid) break; From 079db7bfdb4c12c74702667f21664dee9ca29ee8 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:25:09 +0000 Subject: [PATCH 4/8] fix(flow): report store_loading for unset store project inputs - Report store_loading when a live verified store throws NG0950 - Keep exact project ID checks so other project stores do not bind - Bind ngLViewMap from mounted route hosts in bindProjectStore - Retry ProjectStoreSession::open when discovery sees store_loading --- src/project.rs | 3 +- src/project_store.rs | 13 ++- ts/discover_store.ts | 78 +++++++++++++---- ts/project_store.ts | 200 ++++++++++++++++++++++++++++++++++--------- 4 files changed, 235 insertions(+), 59 deletions(-) diff --git a/src/project.rs b/src/project.rs index e992a04..bfe26f2 100644 --- a/src/project.rs +++ b/src/project.rs @@ -405,7 +405,8 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { ); } input_pending |= discovery_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); - if discovery["bound"].as_bool() == Some(true) { + store_loading |= discovery_err == Some("store_loading"); + if discovery["bound"].as_bool() == Some(true) || store_loading { tokio::time::sleep(Duration::from_millis(250)).await; continue; } diff --git a/src/project_store.rs b/src/project_store.rs index b58e778..e313024 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -37,20 +37,29 @@ impl<'a> ProjectStoreSession<'a> { let guard = engine.lock_project_store().await; let mut dom_probed = false; let mut status = store_loading_result(bind_current_store(engine, &project_id).await)?; - for _ in 0..25 { + for _ in 0..30 { let err = status.get("error").and_then(Value::as_str); if err == Some("collection_store_not_bound") && !dom_probed { dom_probed = true; - let _ = + let discovery = store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?; status = store_loading_result( engine .call_flow_js("projectStoreStatus", json!([project_id])) .await, )?; + if status.get("error").and_then(Value::as_str) == Some("collection_store_not_bound") + && matches!( + discovery.get("error").and_then(Value::as_str), + Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR) + ) + { + status = json!({ "ok": false, "error": "store_loading" }); + } continue; } if matches!(err, Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR)) { + dom_probed = false; tokio::time::sleep(Duration::from_millis(200)).await; status = store_loading_result(bind_current_store(engine, &project_id).await)?; continue; diff --git a/ts/discover_store.ts b/ts/discover_store.ts index 392b5b9..efc9537 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -9,9 +9,10 @@ import { activeProjectStoreFormat } from "./frontend_builds"; import { clearProjectStore, currentProjectStore, - findProjectStoreInView, + inspectProjectStoreInView, installProjectStore, isCurrent, + isProjectRouteLoading, projectInRoute, selectProjectStoreCandidate, } from "./project_store"; @@ -46,14 +47,25 @@ const STORE_HOST_SELECTORS = [ "main", ] as const; +/** Result of a DOM or map-capture store scan. */ +interface StoreDiscoveryScan { + /** Selected verified store for the active project, if ready to bind. */ + readonly store: ProjectStore | null; + /** True when a live verified store throws `NG0950` for an unset project input. */ + readonly inputPending: boolean; +} + /** Walks connected DOM elements and parent LViews to find a verified `ProjectStore`. */ -function scanDomStore(projectId: string): ProjectStore | null { +function scanDomStore(projectId: string): StoreDiscoveryScan { const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; const collectFromElement = (el: Element): void => { let view: NgLView | null = resolveLView(el); for (let depth = 0; depth < 6 && Array.isArray(view); depth += 1) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + candidates.push(...scan.matches); + inputPending ||= scan.inputPending; view = Array.isArray(view[3]) ? view[3] : Array.isArray(view[15]) ? view[15] : null; } }; @@ -65,14 +77,17 @@ function scanDomStore(projectId: string): ProjectStore | null { cur = cur.parentElement; } } - if (!candidates.length) { + if (!candidates.length && !inputPending) { const allElements = document.querySelectorAll("*"); const limit = Math.min(allElements.length, 600); for (let i = 0; i < limit; i += 1) { collectFromElement(allElements[i]); } } - return selectProjectStoreCandidate(candidates) ?? null; + return { + store: selectProjectStoreCandidate(candidates) ?? null, + inputPending, + }; } /** Captures Angular's LView map via hover probing when not yet recorded in `runtimeState`. */ @@ -94,7 +109,7 @@ async function captureStoreDuring( projectId: string, allMaps: Set>, probe: () => Promise, -): Promise { +): Promise { const seenViews = new Set(); await withLViewMapCapture(probe, (map, value) => { allMaps.add(map); @@ -103,8 +118,11 @@ async function captureStoreDuring( const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; for (const view of seenViews) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + candidates.push(...scan.matches); + inputPending ||= scan.inputPending; } for (const map of allMaps) { if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(map)) { @@ -112,13 +130,18 @@ async function captureStoreDuring( } try { for (const value of map.values()) { - candidates.push(...findProjectStoreInView(value, projectId, seen)); + const scan = inspectProjectStoreInView(value, projectId, seen); + candidates.push(...scan.matches); + inputPending ||= scan.inputPending; } } catch { // Skip non-Map prototypes or concurrent map mutations. } } - return selectProjectStoreCandidate(candidates) ?? null; + return { + store: selectProjectStoreCandidate(candidates) ?? null, + inputPending, + }; } /** Binds the verified project store from DOM contexts or transient Angular view activity. */ @@ -141,10 +164,16 @@ export async function discoverStore(): Promise { clearProjectStore(); - let found = scanDomStore(projectId); + const initial = scanDomStore(projectId); + let found = initial.store; + let inputPending = initial.inputPending; if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const rescan = scanDomStore(projectId); + found = rescan.store; + inputPending ||= rescan.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; @@ -157,20 +186,26 @@ export async function discoverStore(): Promise { } for (const selector of STORE_HOST_SELECTORS) { - if (found) break; + if (found || inputPending) break; const targets = document.querySelectorAll(selector); if (targets.length === 0) continue; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { await hoverProbe(Array.from(targets).slice(0, 6), 25); }); - if (!found) found = scanDomStore(projectId); + found = captured.store; + inputPending ||= captured.inputPending; + if (!found && !inputPending) { + const domScan = scanDomStore(projectId); + found = domScan.store; + inputPending ||= domScan.inputPending; + } } - if (!found) { + if (!found && !inputPending) { const scroller = document.querySelector(".page-container, cdk-virtual-scroll-viewport"); if (scroller) { const prev = scroller.scrollTop; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { scroller.scrollTop = Math.min(scroller.scrollHeight, prev + 200); scroller.dispatchEvent(new Event("scroll")); await delay(50); @@ -178,16 +213,25 @@ export async function discoverStore(): Promise { scroller.dispatchEvent(new Event("scroll")); await delay(50); }); + found = captured.store; + inputPending ||= captured.inputPending; } } if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const rescan = scanDomStore(projectId); + found = rescan.store; + inputPending ||= rescan.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; } } + if (inputPending || isProjectRouteLoading()) { + return { bound: false, newlyDiscovered: false, error: "store_loading" }; + } return { bound: false, newlyDiscovered: false }; } diff --git a/ts/project_store.ts b/ts/project_store.ts index cdb20c4..99e1dab 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -3,7 +3,7 @@ // Bind, validate, read, and mutate the active project store from verified build formats. -import { isNgLViewMap, readOwn } from "./angular"; +import { bindAngularViews, isNgLViewMap, readOwn, resolveLView } from "./angular"; import { delay } from "./dom"; import { activeProjectStoreFormat, readBuildLabel, withMutationAliases } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; @@ -69,29 +69,70 @@ const PROJECT_ROUTE_HOST_SELECTOR = [ "flow-agent-panel", ].join(", "); +/** Angular error code for a required input that has no value yet. */ +const ANGULAR_REQUIRED_INPUT_ERROR = "NG0950"; + +/** Result of reading the project signal on a verified store instance. */ +type StoreProjectState = + | { readonly state: "ready"; readonly projectId: string } + | { readonly state: "loading" } + | { readonly state: "invalid" }; + +/** Result of scanning one Angular view for verified `ProjectStore` instances. */ +export interface StoreViewScan { + /** Live verified stores whose project signal matches the requested project ID. */ + readonly matches: ProjectStore[]; + /** True when a live verified store throws `NG0950` for an unset project input. */ + readonly inputPending: boolean; +} + /** Returns the project ID in the current route. */ export function projectInRoute(): string | null { return /\/project\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; } -/** Invokes a zero-argument getter or Angular signal on `owner` without throwing. */ -function callStoreGetter(owner: object, key: string): unknown { - const getter = readOwn(owner, key); - if (typeof getter !== "function") return undefined; +/** Returns true when `error` reports an unset Angular required input (`NG0950`). */ +function isRequiredInputError(error: unknown): boolean { + const code = readOwn(error, "code"); + if (code === 950 || code === -950) return true; + const rawMessage = error instanceof Error + ? error.message + : typeof error === "string" + ? error + : readOwn(error, "message"); + if (typeof rawMessage !== "string") return false; + return rawMessage + .split(/[^A-Za-z0-9]+/) + .includes(ANGULAR_REQUIRED_INPUT_ERROR); +} + +/** Returns true while the lifecycle controller of `service` exists and is not destroyed. */ +function isStoreLifecycleLive(service: object, format: ProjectStoreFormat): boolean { + const lifecycle = readOwn(service, format.lifecycle); + return Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed); +} + +/** Reads the project ID signal of `service` and reports unset required inputs (`NG0950`). */ +function readStoreProjectId(service: object, format: ProjectStoreFormat): StoreProjectState { + const getter = readOwn(service, format.projectId); + if (typeof getter !== "function") return { state: "invalid" }; try { - return getter.call(owner); - } catch { - return undefined; + const value: unknown = getter.call(service); + return typeof value === "string" && value + ? { state: "ready", projectId: value } + : { state: "invalid" }; + } catch (error) { + return isRequiredInputError(error) ? { state: "loading" } : { state: "invalid" }; } } /** Checks the active route, lifecycle flag, and project signal of `store`. */ export function isCurrent({ projectId, service, format }: ProjectStore): boolean { - const lifecycle = readOwn(service, format.lifecycle); - return Boolean(projectId) && - projectInRoute() === projectId && - Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed) && - callStoreGetter(service, format.projectId) === projectId; + if (!projectId || projectInRoute() !== projectId || !isStoreLifecycleLive(service, format)) { + return false; + } + const project = readStoreProjectId(service, format); + return project.state === "ready" && project.projectId === projectId; } /** Clears both the direct store binding and `runtimeState.store`. */ @@ -134,11 +175,7 @@ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTile if (!query) { const signalQuery = readOwn(service, format.tileQuery); if (signalQuery && typeof signalQuery === "object") { - try { - void ("status" in signalQuery); - } catch { - // Ignore signal read errors before inputs are ready. - } + void readQueryField(signalQuery, "status"); query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; } } @@ -156,8 +193,8 @@ function readQueryField(signalQuery: object, key: string): unknown { if (!(key in signalQuery)) return undefined; const prop = readOwn(signalQuery, key); return typeof prop === "function" ? prop.call(signalQuery) : prop; - } catch { - return undefined; + } catch (error) { + return isRequiredInputError(error) ? ANGULAR_REQUIRED_INPUT_ERROR : undefined; } } @@ -166,10 +203,16 @@ export function isProjectStorePending(store: ProjectStore): boolean { if (!isCurrent(store)) return false; const signalQuery = readOwn(store.service, store.format.tileQuery); if (signalQuery && typeof signalQuery === "object") { + const pending = readQueryField(signalQuery, "isPending"); + const loading = readQueryField(signalQuery, "isLoading"); + const status = readQueryField(signalQuery, "status"); if ( - readQueryField(signalQuery, "isPending") === true || - readQueryField(signalQuery, "isLoading") === true || - readQueryField(signalQuery, "status") === "pending" + pending === true || + loading === true || + status === "pending" || + pending === ANGULAR_REQUIRED_INPUT_ERROR || + loading === ANGULAR_REQUIRED_INPUT_ERROR || + status === ANGULAR_REQUIRED_INPUT_ERROR ) { return true; } @@ -206,8 +249,13 @@ export function readProjectStore(store: ProjectStore): Map | n } const signalQuery = readOwn(store.service, store.format.tileQuery); if (!signalQuery || typeof signalQuery !== "object" || !("data" in signalQuery)) return null; - const readData = readOwn(signalQuery, "data"); - const signalData: unknown = typeof readData === "function" ? readData.call(signalQuery) : readData; + let signalData: unknown; + try { + const readData = readOwn(signalQuery, "data"); + signalData = typeof readData === "function" ? readData.call(signalQuery) : readData; + } catch { + return null; + } return indexTileRows(signalData) ?? tileMap(signalData, store.format.rows); } @@ -373,23 +421,30 @@ function verifiedStoreLayout(): { format: ProjectStoreFormat; storeClass: Functi return typeof storeClass === "function" ? { format, storeClass } : null; } -/** Collects live `ProjectStore` candidates from one Angular `LView` array. */ -export function findProjectStoreInView( +/** Scans one Angular `LView` array for matching or input-pending verified `ProjectStore` instances. */ +export function inspectProjectStoreInView( view: unknown, projectId: string, seen = new Set(), -): ProjectStore[] { - if (!Array.isArray(view)) return []; +): StoreViewScan { + if (!Array.isArray(view)) return { matches: [], inputPending: false }; const layout = verifiedStoreLayout(); - if (!layout) return []; + if (!layout) return { matches: [], inputPending: false }; const { format, storeClass } = layout; const matches: ProjectStore[] = []; + let inputPending = false; const consider = (value: unknown): void => { if (!value || typeof value !== "object" || seen.has(value)) return; seen.add(value); - if (!(value instanceof storeClass)) return; - const candidate: ProjectStore = { projectId, service: value, format }; - if (isCurrent(candidate)) matches.push(candidate); + if (!(value instanceof storeClass) || !isStoreLifecycleLive(value, format)) return; + const project = readStoreProjectId(value, format); + if (project.state === "loading") { + inputPending = true; + return; + } + if (project.state === "ready" && project.projectId === projectId && projectInRoute() === projectId) { + matches.push({ projectId, service: value, format }); + } }; for (const slot of view) { @@ -414,11 +469,60 @@ export function findProjectStoreInView( consider(Object.getOwnPropertyDescriptor(slot, key)?.value); } } - return matches; + return { matches, inputPending }; +} + +/** Collects live `ProjectStore` candidates from one Angular `LView` array. */ +export function findProjectStoreInView( + view: unknown, + projectId: string, + seen = new Set(), +): ProjectStore[] { + return inspectProjectStoreInView(view, projectId, seen).matches; +} + +/** Scans connected project route hosts and parent `LView` chains for verified stores. */ +function scanConnectedRouteViews( + projectId: string, + seen = new Set(), +): { matches: Array<{ store: ProjectStore; view: NgLView }>; inputPending: boolean } { + const matches: Array<{ store: ProjectStore; view: NgLView }> = []; + let inputPending = false; + const seenViews = new Set(); + for (const host of document.querySelectorAll(PROJECT_ROUTE_HOST_SELECTOR)) { + let cur: Element | null = host; + for (let steps = 0; cur && steps < 6; steps += 1) { + let view: NgLView | null = resolveLView(cur); + for (let depth = 0; depth < 6 && Array.isArray(view); depth += 1) { + if (!seenViews.has(view)) { + seenViews.add(view); + const scan = inspectProjectStoreInView(view, projectId, seen); + for (const store of scan.matches) { + matches.push({ store, view }); + } + inputPending ||= scan.inputPending; + } + view = Array.isArray(view[3]) ? view[3] : Array.isArray(view[15]) ? view[15] : null; + } + cur = cur.parentElement; + } + } + return { matches, inputPending }; +} + +/** Returns true when registered or connected views hold a verified store with an unset input. */ +function hasPendingProjectStoreInput(projectId: string): boolean { + const seen = new Set(); + if (runtimeState.ngLViewMap instanceof Map) { + for (const view of runtimeState.ngLViewMap.values()) { + if (inspectProjectStoreInView(view, projectId, seen).inputPending) return true; + } + } + return scanConnectedRouteViews(projectId, seen).inputPending; } /** Returns true while the `/project/` route view is not in the document yet. */ -function isProjectRouteLoading(): boolean { +export function isProjectRouteLoading(): boolean { if (document.querySelector(PROJECT_ROUTE_HOST_SELECTOR)) return false; if (document.querySelector("flow-landing-page")) return false; if (document.readyState !== "complete") return true; @@ -435,7 +539,7 @@ export function projectStoreStatus(projectId: string): ProjectStoreStatus { if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; const store = currentProjectStore(projectId); if (!store) { - return isProjectRouteLoading() + return isProjectRouteLoading() || hasPendingProjectStoreInput(projectId) ? { ok: false, error: "store_loading" } : { ok: false, error: "collection_store_not_bound" }; } @@ -471,16 +575,34 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto : { ok: false, error: "collection_store_not_bound" }; } + if (!(runtimeState.ngLViewMap instanceof Map)) { + bindAngularViews(maps, PROJECT_ROUTE_HOST_SELECTOR); + } + const seen = new Set(); - const candidates: Array<{ store: ProjectStore; views: Map }> = []; + const candidates: Array<{ store: ProjectStore; views?: Map }> = []; + const viewMaps: Array> = []; + let inputPending = false; for (const map of maps) { if (!isNgLViewMap(map)) continue; + viewMaps.push(map); for (const view of map.values()) { - for (const store of findProjectStoreInView(view, projectId, seen)) { + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + for (const store of scan.matches) { candidates.push({ store, views: map }); } } } + const connected = scanConnectedRouteViews(projectId, seen); + inputPending ||= connected.inputPending; + for (const { store, view } of connected.matches) { + const slotId = view[19]; + const views = typeof slotId === "number" + ? viewMaps.find((map) => map.get(slotId) === view) + : undefined; + candidates.push({ store, views }); + } const selectedStore = selectProjectStoreCandidate(candidates.map(({ store }) => store)); const selected = candidates.find(({ store }) => store === selectedStore); @@ -489,7 +611,7 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto if (candidates.length > 1) { return { ok: false, error: "ambiguous_collection_store" }; } - return isProjectRouteLoading() + return inputPending || isProjectRouteLoading() ? { ok: false, error: "store_loading" } : { ok: false, error: "collection_store_not_bound" }; } From b74582f7506ed37d41456b53475806ed94e72367 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 03:05:11 +0000 Subject: [PATCH 5/8] fix(flow): tighten project loading and context view checks - Limit route loading checks to empty roots and inactive outlets. - Run the DOM store probe at most once per project store session. - Read context views only from lView, build fields, or lViewId. - Check active query fetches so disabled queries do not block. - Share LView slot ID lookup and remove findProjectStoreInView. --- src/project_store.rs | 1 - ts/angular.ts | 74 +++++++++++++++--------------------------- ts/character_voices.ts | 10 ++---- ts/project_store.ts | 59 +++++++++++++++++++++------------ ts/projects_ops.ts | 10 ++---- 5 files changed, 69 insertions(+), 85 deletions(-) diff --git a/src/project_store.rs b/src/project_store.rs index e313024..a724b98 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -59,7 +59,6 @@ impl<'a> ProjectStoreSession<'a> { continue; } if matches!(err, Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR)) { - dom_probed = false; tokio::time::sleep(Duration::from_millis(200)).await; status = store_loading_result(bind_current_store(engine, &project_id).await)?; continue; diff --git a/ts/angular.ts b/ts/angular.ts index b01942d..75b02a7 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -21,10 +21,6 @@ export interface NgContextCarrier { __ngContext__?: number | NgLView | NgContextCarrier | Record; /** Embedded view or LContext LView reference. */ lView?: NgLView; - /** Minified LContext LView reference in Flow builds from 2026-11-20 on. */ - zp?: NgLView; - /** Minified LContext LView reference in earlier Flow builds. */ - Pn?: NgLView; /** Optional LView registry slot identifier on LContext wrappers. */ lViewId?: number; } @@ -44,42 +40,40 @@ export function isLiveLView(lv: unknown): lv is NgLView { return Array.isArray(lv) && (!(lv[0] instanceof Node) || lv[0].isConnected); } -/** Returns true when `val` matches the header layout of an Angular Ivy `LView` array. */ -function isLViewArray(val: unknown): val is NgLView { - return ( - Array.isArray(val) && - val.length >= 20 && - Boolean(val[1]) && - typeof val[1] === "object" && - !Array.isArray(val[1]) && - (typeof val[19] === "number" || typeof val[2] === "number") - ); -} - /** Extracts an `NgLView` array from an upgraded Angular `LContext` wrapper object. */ function unwrapContextView(raw: object): NgLView | null { + const direct = readOwn(raw, "lView"); + if (Array.isArray(direct)) return direct; const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView; - const keys = contextField - ? ["lView", contextField, "zp", "Pn"] - : ["lView", "zp", "Pn"]; - for (const key of keys) { - const candidate = readOwn(raw, key); - if (Array.isArray(candidate)) return candidate; + if (contextField) { + const verified = readOwn(raw, contextField); + if (Array.isArray(verified)) return verified; } const id = readOwn(raw, "lViewId"); if (typeof id === "number" && runtimeState.ngLViewMap instanceof Map) { const mapped = runtimeState.ngLViewMap.get(id); if (Array.isArray(mapped)) return mapped; } - try { - for (const key of Object.getOwnPropertyNames(raw)) { - if (key === "directives") continue; - const desc = Object.getOwnPropertyDescriptor(raw, key); - const val: unknown = desc && "value" in desc ? desc.value : undefined; - if (isLViewArray(val)) return val; - } - } catch { - return null; + return null; +} + +/** 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 (Array.isArray(raw)) { + return typeof raw[19] === "number" ? raw[19] : null; + } + if (raw && typeof raw === "object" && !(raw instanceof Node)) { + const id = readOwn(raw, "lViewId"); + if (typeof id === "number") return id; + const view = unwrapContextView(raw); + return typeof view?.[19] === "number" ? view[19] : null; } return null; } @@ -102,23 +96,7 @@ export function isNgLViewMap(m: unknown): m is Map { /** 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__"); - let slotId: number | null = typeof context === "number" ? context : null; - let directView: NgLView | null = Array.isArray(context) ? context : null; - if ( - slotId === null && - !directView && - context && - typeof context === "object" && - !(context instanceof Node) - ) { - const rawId = readOwn(context, "lViewId"); - if (typeof rawId === "number") slotId = rawId; - directView = unwrapContextView(context); - } - if (slotId === null && typeof directView?.[19] === "number") { - slotId = directView[19]; - } + const slotId = readLViewSlotId(host); if (slotId === null) continue; const views = maps.find((map): map is Map => isNgLViewMap(map) && isLiveLView(map.get(slotId)), diff --git a/ts/character_voices.ts b/ts/character_voices.ts index fe67a82..fdeec70 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -3,7 +3,7 @@ // List and assign Google Flow character voices inside the character editor. -import { readOwn, resolveLView, startMapCapture, type NgContextCarrier } from "./angular"; +import { readLViewSlotId, readOwn, resolveLView, startMapCapture } from "./angular"; import { VOICE_ICON_WORDS, voicePane } from "./character_extra"; import { clickButtonByRegex, @@ -125,13 +125,7 @@ export async function characterVoiceOp( formComponents.set(form, direct); return direct; } - const formNg = (form as NgContextCarrier).__ngContext__; - const formSlotId = - typeof formNg === "number" - ? formNg - : typeof readOwn(formNg, "lViewId") === "number" - ? (readOwn(formNg, "lViewId") as number) - : null; + const formSlotId = readLViewSlotId(form); if (formSlotId === null || probedForms.has(form)) { return null; } diff --git a/ts/project_store.ts b/ts/project_store.ts index 99e1dab..c1098ba 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -14,8 +14,8 @@ import type { FlowStoreHandle, FlowTile, NgLView, StoreProbeCheck } from "./type interface ProjectTileQuery { /** Key that includes the project ID. */ queryKey: unknown; - /** Most recent query status and result. */ - state: { status: string; data: unknown }; + /** Most recent query status, fetch state, and result. */ + state: { status: string; fetchStatus?: string; data: unknown }; /** Runs the query and returns the fetched result. */ fetch: (options: undefined, settings: { cancelRefetch: boolean }) => Promise; } @@ -69,6 +69,10 @@ const PROJECT_ROUTE_HOST_SELECTOR = [ "flow-agent-panel", ].join(", "); +/** Shell banner hosts inside `aisandbox-root` before the primary route outlet activates. */ +const SHELL_BANNER_SELECTOR = + "flow-banner, flow-g1-promotional-banner, flow-retention-optin-banner"; + /** Angular error code for a required input that has no value yet. */ const ANGULAR_REQUIRED_INPUT_ERROR = "NG0950"; @@ -203,21 +207,23 @@ export function isProjectStorePending(store: ProjectStore): boolean { if (!isCurrent(store)) return false; const signalQuery = readOwn(store.service, store.format.tileQuery); if (signalQuery && typeof signalQuery === "object") { - const pending = readQueryField(signalQuery, "isPending"); const loading = readQueryField(signalQuery, "isLoading"); + const fetchStatus = readQueryField(signalQuery, "fetchStatus"); const status = readQueryField(signalQuery, "status"); if ( - pending === true || - loading === true || - status === "pending" || - pending === ANGULAR_REQUIRED_INPUT_ERROR || loading === ANGULAR_REQUIRED_INPUT_ERROR || + fetchStatus === ANGULAR_REQUIRED_INPUT_ERROR || status === ANGULAR_REQUIRED_INPUT_ERROR ) { return true; } + if (typeof loading === "boolean") return loading; + if (typeof fetchStatus === "string") { + return status === "pending" && fetchStatus === "fetching"; + } } - return projectQuery(store)?.state.status === "pending"; + const state = projectQuery(store)?.state; + return state?.status === "pending" && state.fetchStatus === "fetching"; } /** Indexes a validated tile row array by tile ID. */ @@ -472,15 +478,6 @@ export function inspectProjectStoreInView( return { matches, inputPending }; } -/** Collects live `ProjectStore` candidates from one Angular `LView` array. */ -export function findProjectStoreInView( - view: unknown, - projectId: string, - seen = new Set(), -): ProjectStore[] { - return inspectProjectStoreInView(view, projectId, seen).matches; -} - /** Scans connected project route hosts and parent `LView` chains for verified stores. */ function scanConnectedRouteViews( projectId: string, @@ -489,7 +486,13 @@ function scanConnectedRouteViews( const matches: Array<{ store: ProjectStore; view: NgLView }> = []; let inputPending = false; const seenViews = new Set(); - for (const host of document.querySelectorAll(PROJECT_ROUTE_HOST_SELECTOR)) { + const listedHosts = Array.from(document.querySelectorAll(PROJECT_ROUTE_HOST_SELECTOR)); + const fallbackHost = listedHosts.length === 0 + ? document.querySelector("aisandbox-root router-outlet:not([name]), app-root router-outlet:not([name])") + ?.nextElementSibling ?? null + : null; + const hosts = fallbackHost ? [fallbackHost] : listedHosts; + for (const host of hosts) { let cur: Element | null = host; for (let steps = 0; cur && steps < 6; steps += 1) { let view: NgLView | null = resolveLView(cur); @@ -525,8 +528,24 @@ function hasPendingProjectStoreInput(projectId: string): boolean { export function isProjectRouteLoading(): boolean { if (document.querySelector(PROJECT_ROUTE_HOST_SELECTOR)) return false; if (document.querySelector("flow-landing-page")) return false; + if (document.querySelector("flow-loading-page, .projects-loading-container")) return true; if (document.readyState !== "complete") return true; - return Boolean(document.querySelector("aisandbox-root, app-root")); + const root = document.querySelector("aisandbox-root, app-root"); + if (!root) return false; + if (root.childElementCount === 0) return true; + const outlet = root.querySelector("router-outlet:not([name])"); + if (!outlet || outlet.nextElementSibling) return false; + for (const el of root.querySelectorAll("*")) { + if ( + el !== outlet && + el.tagName.includes("-") && + !el.matches(SHELL_BANNER_SELECTOR) && + !el.closest(SHELL_BANNER_SELECTOR) + ) { + return false; + } + } + return true; } /** Reports whether the current runtime has a bound and ready store for `projectId`. */ @@ -576,7 +595,7 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto } if (!(runtimeState.ngLViewMap instanceof Map)) { - bindAngularViews(maps, PROJECT_ROUTE_HOST_SELECTOR); + bindAngularViews(maps, `${PROJECT_ROUTE_HOST_SELECTOR}, aisandbox-root, app-root`); } const seen = new Set(); diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 34d48f0..c8a9fe8 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -5,10 +5,10 @@ import { buildProjectUrl, + readLViewSlotId, readOwn, resolveLView, withMapCapture, - type NgContextCarrier, } from "./angular"; import { delay, elText, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; @@ -141,13 +141,7 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { if (resolved) { pid = extractIdFromObject(resolved, 0, new Set()); } else { - const ng = (card as NgContextCarrier).__ngContext__; - const slotId = - typeof ng === "number" - ? ng - : typeof readOwn(ng, "lViewId") === "number" - ? (readOwn(ng, "lViewId") as number) - : null; + const slotId = readLViewSlotId(card); if (slotId !== null) { for (const sm of seenMaps) { try { From d53c6c641fd8151a1d9e783dd8190bf1500a6c89 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 05:30:37 +0000 Subject: [PATCH 6/8] fix(flow): resolve Angular views and slot IDs in UI helpers - Add readLViewSlotId and check lViewId in resolveLView - Read character form views with resolveLView and readLViewSlotId - Read grid tile views with resolveLView in openEditAsset - Read project card views with resolveLView and readLViewSlotId --- ts/angular.ts | 35 +++++++++++++++++++++++++++++------ ts/character_voices.ts | 11 ++++++----- ts/open_edit_asset.ts | 4 ++-- ts/projects_ops.ts | 29 ++++++++++++++++------------- 4 files changed, 53 insertions(+), 26 deletions(-) diff --git a/ts/angular.ts b/ts/angular.ts index 6c948c0..b0507c2 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -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; /** 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. */ @@ -53,13 +55,30 @@ export function isNgLViewMap(m: unknown): m is Map { 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 => - isNgLViewMap(map) && isLiveLView(map.get(context)), + isNgLViewMap(map) && isLiveLView(map.get(slotId)), ); if (views) { runtimeState.ngLViewMap = views; @@ -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; } diff --git a/ts/character_voices.ts b/ts/character_voices.ts index 8134f6b..0ede6b2 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -3,7 +3,7 @@ // List and assign Google Flow character voices inside the character editor. -import { readOwn, startMapCapture, type NgContextCarrier } from "./angular"; +import { readLViewSlotId, readOwn, resolveLView, startMapCapture } from "./angular"; import { VOICE_ICON_WORDS, voicePane } from "./character_extra"; import { clickButtonByRegex, @@ -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); @@ -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 => { diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..7779fab 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,7 +8,7 @@ import { findRouter, navigateSpa, readOwn, - type NgContextCarrier, + resolveLView, } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; import { clearStore } from "./state"; @@ -119,7 +119,7 @@ export async function openEditAsset( } } } - const ng = (el as NgContextCarrier).__ngContext__; + const ng = resolveLView(el); if (Array.isArray(ng)) { for (let i = 0; i < ng.length; i++) { const item = ng[i]; diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..540237a 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -5,10 +5,10 @@ import { buildProjectUrl, + readLViewSlotId, readOwn, resolveLView, withMapCapture, - type NgContextCarrier, } from "./angular"; import { delay, elText, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; @@ -137,19 +137,22 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } if (!pid) { - const ng = (card as NgContextCarrier).__ngContext__; - if (Array.isArray(ng)) { - pid = extractIdFromObject(ng, 0, new Set()); - } else if (typeof ng === "number") { - for (const sm of seenMaps) { - try { - const lv = sm.get(ng); - if (Array.isArray(lv)) { - pid = extractIdFromObject(lv, 0, new Set()); - if (pid) break; + const resolved = resolveLView(card); + if (resolved) { + pid = extractIdFromObject(resolved, 0, new Set()); + } else { + const slotId = readLViewSlotId(card); + if (slotId !== null) { + for (const sm of seenMaps) { + try { + const lv = sm.get(slotId); + if (Array.isArray(lv)) { + pid = extractIdFromObject(lv, 0, new Set()); + if (pid) break; + } + } catch { + // Ignore map read error. } - } catch { - // Ignore map read error. } } } From c5fcc6468376b3dd076793b4610f9c6b8cf21126 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 05:34:04 +0000 Subject: [PATCH 7/8] fix(flow): catch NG0950 when project page inputs are unset - Catch unset project signal errors in projectUpload page checks - Catch unset project signal errors in liveBinding for Agent chat --- ts/agent_chat.ts | 8 ++++++-- ts/project_upload.ts | 9 +++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 13f7e57..b74d73a 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -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. */ diff --git a/ts/project_upload.ts b/ts/project_upload.ts index 348b770..ea1a973 100644 --- a/ts/project_upload.ts +++ b/ts/project_upload.ts @@ -428,9 +428,14 @@ function projectWorkspaceRoute(pathname: string): { projectId: string; collectio /** Checks the route and lifecycle of a project workspace component. */ function isCurrentPage(page: object, format: ProjectUploadFormat["page"], projectId: string): boolean { if (projectWorkspaceRoute(location.pathname)?.projectId !== projectId) return false; + if (readOwn(readOwn(page, format.lifecycle), format.destroyed) !== false) return false; const project = readOwn(page, format.project); - return readOwn(readOwn(page, format.lifecycle), format.destroyed) === false && - typeof project === "function" && project.call(page) === projectId; + if (typeof project !== "function") return false; + try { + return project.call(page) === projectId; + } catch { + return false; + } } /** Finds the live project page that owns the upload services. */ From 7edc43dd68f4776b4b8910c9ff84eb034e197fb8 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 05:42:03 +0000 Subject: [PATCH 8/8] fix(flow): report store_loading while project store loads - Share STORE_HOST_SELECTORS between store bind and DOM discovery - Keep idle and paused pending tile queries marked as pending - Check router URL and loading nodes instead of banner tag lists - Retry DOM discovery when an early probe hits store_loading --- src/project.rs | 21 ++++- src/project_store.rs | 28 ++++--- ts/discover_store.ts | 97 +++++++++++++---------- ts/project_store.ts | 185 ++++++++++++++++++++++++++++++++++++++----- 4 files changed, 257 insertions(+), 74 deletions(-) diff --git a/src/project.rs b/src/project.rs index e11643e..7c1fd57 100644 --- a/src/project.rs +++ b/src/project.rs @@ -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)] @@ -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) @@ -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 = @@ -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; @@ -425,6 +434,12 @@ 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 @@ -432,7 +447,7 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { } /// Treats an unset Angular input as a loading result for a project store read. -fn store_loading_result(result: Result) -> Result { +pub(crate) fn store_loading_result(result: Result) -> Result { match result { Err(error) if error.to_string().lines().next().is_some_and(|line| { diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..a335136 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -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> { @@ -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; diff --git a/ts/discover_store.ts b/ts/discover_store.ts index a6b793e..ef26bb7 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -7,11 +7,13 @@ import { isNgLViewMap, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { + STORE_HOST_SELECTORS, clearProjectStore, currentProjectStore, - findProjectStoreInView, + inspectProjectStoreInView, installProjectStore, isCurrent, + isProjectRouteLoading, projectInRoute, selectProjectStoreCandidate, } from "./project_store"; @@ -19,39 +21,25 @@ import type { ProjectStore } from "./project_store"; import { runtimeState } from "./state"; import type { DiscoverStoreResult, NgLView } from "./types"; -/** Component hosts and shell selectors that carry Angular contexts in Google Flow. */ -const STORE_HOST_SELECTORS = [ - "flow-project-shell", - "flow-project-page", - "flow-character-edit-page", - "flow-character-edit-header", - "flow-character-form", - "flow-character-preview-panel", - "flow-character-image-preview", - "flow-edit-character-footer", - "flow-character-header", - "flow-editor-dispatcher", - "flow-editor-page", - "flow-scene-builder", - "flow-scene-timeline", - "flow-grid-tile-container", - 'button[aria-label="Settings trigger"]', - "[mattooltip]", - "button[aria-label]", - "aisandbox-root", - "app-root", - "header", - "main", -] as const; +/** Result of scanning DOM nodes or captured maps for a verified `ProjectStore`. */ +interface StoreProbeOutcome { + /** Selected `ProjectStore` instance when one live candidate matches `projectId`. */ + store: ProjectStore | null; + /** True when a live verified store still waits for its route project input or parameter. */ + inputPending: boolean; +} /** Walks connected DOM elements and parent LViews to find a verified `ProjectStore`. */ -function scanDomStore(projectId: string): ProjectStore | null { +function scanDomStore(projectId: string): StoreProbeOutcome { const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; const collectFromElement = (el: Element): void => { let view: NgLView | null = resolveLView(el); for (let depth = 0; depth < 6 && Array.isArray(view); depth += 1) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); view = Array.isArray(view[3]) ? view[3] : Array.isArray(view[15]) ? view[15] : null; } }; @@ -63,14 +51,14 @@ function scanDomStore(projectId: string): ProjectStore | null { cur = cur.parentElement; } } - if (!candidates.length) { + if (!candidates.length && !inputPending) { const allElements = document.querySelectorAll("*"); const limit = Math.min(allElements.length, 600); for (let i = 0; i < limit; i += 1) { collectFromElement(allElements[i]); } } - return selectProjectStoreCandidate(candidates) ?? null; + return { store: selectProjectStoreCandidate(candidates) ?? null, inputPending }; } /** Captures Angular's LView map via hover probing when not yet recorded in `runtimeState`. */ @@ -92,7 +80,7 @@ async function captureStoreDuring( projectId: string, allMaps: Set>, probe: () => Promise, -): Promise { +): Promise { const seenViews = new Set(); await withLViewMapCapture(probe, (map, value) => { allMaps.add(map); @@ -101,8 +89,11 @@ async function captureStoreDuring( const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; for (const view of seenViews) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); } for (const map of allMaps) { if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(map)) { @@ -110,13 +101,15 @@ async function captureStoreDuring( } try { for (const value of map.values()) { - candidates.push(...findProjectStoreInView(value, projectId, seen)); + const scan = inspectProjectStoreInView(value, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); } } catch { // Skip non-Map prototypes or concurrent map mutations. } } - return selectProjectStoreCandidate(candidates) ?? null; + return { store: selectProjectStoreCandidate(candidates) ?? null, inputPending }; } /** Binds the verified project store from DOM contexts or transient Angular view activity. */ @@ -139,15 +132,24 @@ export async function discoverStore(): Promise { clearProjectStore(); - let found = scanDomStore(projectId); + const initial = scanDomStore(projectId); + let found = initial.store; + let inputPending = initial.inputPending; if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const recheck = scanDomStore(projectId); + found = recheck.store; + inputPending ||= recheck.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; } } + if (inputPending || isProjectRouteLoading(projectId)) { + return { bound: false, newlyDiscovered: false, error: "store_loading" }; + } const allMaps = new Set>(); if (runtimeState.ngLViewMap instanceof Map) { @@ -158,17 +160,23 @@ export async function discoverStore(): Promise { if (found) break; const targets = document.querySelectorAll(selector); if (targets.length === 0) continue; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { await hoverProbe(Array.from(targets).slice(0, 6), 25); }); - if (!found) found = scanDomStore(projectId); + found = captured.store; + inputPending ||= captured.inputPending; + if (!found) { + const domScan = scanDomStore(projectId); + found = domScan.store; + inputPending ||= domScan.inputPending; + } } - if (!found) { + if (!found && !inputPending) { const scroller = document.querySelector(".page-container, cdk-virtual-scroll-viewport"); if (scroller) { const prev = scroller.scrollTop; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { scroller.scrollTop = Math.min(scroller.scrollHeight, prev + 200); scroller.dispatchEvent(new Event("scroll")); await delay(50); @@ -176,16 +184,25 @@ export async function discoverStore(): Promise { scroller.dispatchEvent(new Event("scroll")); await delay(50); }); + found = captured.store; + inputPending ||= captured.inputPending; } } if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const recheck = scanDomStore(projectId); + found = recheck.store; + inputPending ||= recheck.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; } } + if (inputPending || isProjectRouteLoading(projectId)) { + return { bound: false, newlyDiscovered: false, error: "store_loading" }; + } return { bound: false, newlyDiscovered: false }; } diff --git a/ts/project_store.ts b/ts/project_store.ts index 983195b..9a0b4c3 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -3,13 +3,43 @@ // Bind, validate, read, and mutate the active project store from verified build formats. -import { isNgLViewMap, readOwn } from "./angular"; +import { bindAngularViews, findRouter, isNgLViewMap, readOwn } from "./angular"; import { delay } from "./dom"; import { activeProjectStoreFormat, readBuildLabel, withMutationAliases } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { FlowStoreHandle, FlowTile, NgLView, StoreProbeCheck } from "./types"; +/** Angular error code for a required input that has no value yet. */ +const ANGULAR_REQUIRED_INPUT_ERROR = "NG0950"; + +/** Component hosts and shell selectors that carry Angular contexts in Google Flow. */ +export const STORE_HOST_SELECTORS = [ + "flow-project-shell", + "flow-project-page", + "flow-character-page", + "flow-character-edit-page", + "flow-character-edit-header", + "flow-character-form", + "flow-character-preview-panel", + "flow-character-image-preview", + "flow-create-character-footer", + "flow-edit-character-footer", + "flow-character-header", + "flow-editor-dispatcher", + "flow-editor-page", + "flow-scene-builder", + "flow-scene-timeline", + "flow-grid-tile-container", + 'button[aria-label="Settings trigger"]', + "[mattooltip]", + "button[aria-label]", + "aisandbox-root", + "app-root", + "header", + "main", +] as const; + /** A Flow query for the tiles of one project. */ interface ProjectTileQuery { /** Key that includes the project ID. */ @@ -60,13 +90,52 @@ export function projectInRoute(): string | null { return /\/project\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; } +/** State of the route project signal on a verified `ProjectStore` instance. */ +type StoreProjectState = + | { state: "ready"; projectId: string } + | { state: "loading" } + | { state: "invalid" }; + +/** Result of scanning one Angular `LView` for verified `ProjectStore` instances. */ +export interface StoreViewScan { + /** Verified stores whose route project signal matches the active project. */ + matches: ProjectStore[]; + /** True when a live verified store still waits for its route project input or parameter. */ + inputPending: boolean; +} + +/** Returns true when `error` reports an unset Angular required input (`NG0950`). */ +function isRequiredInputError(error: unknown): boolean { + const text = error instanceof Error ? error.message : String(error ?? ""); + return text.includes(ANGULAR_REQUIRED_INPUT_ERROR); +} + +/** Returns true when `service` has a live Angular `DestroyRef` lifecycle object. */ +function isStoreLifecycleLive(service: object, format: ProjectStoreFormat): boolean { + const lifecycle = readOwn(service, format.lifecycle); + return Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed); +} + +/** Reads the route project signal of `service` and reports whether it is ready or still loading. */ +function readStoreProjectId(service: object, format: ProjectStoreFormat): StoreProjectState { + const currentProject = readOwn(service, format.projectId); + if (typeof currentProject !== "function") return { state: "invalid" }; + try { + const value: unknown = currentProject.call(service); + if (typeof value === "string" && value.length > 0) { + return { state: "ready", projectId: value }; + } + return value === undefined ? { state: "loading" } : { state: "invalid" }; + } catch (error) { + return isRequiredInputError(error) ? { state: "loading" } : { state: "invalid" }; + } +} + /** Checks the active route, lifecycle flag, and project signal of `store`. */ export function isCurrent({ projectId, service, format }: ProjectStore): boolean { - const currentProject = readOwn(service, format.projectId); - const lifecycle = readOwn(service, format.lifecycle); - return projectInRoute() === projectId && - Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed) && - typeof currentProject === "function" && currentProject.call(service) === projectId; + if (projectInRoute() !== projectId || !isStoreLifecycleLive(service, format)) return false; + const current = readStoreProjectId(service, format); + return current.state === "ready" && current.projectId === projectId; } /** Clears both the direct store binding and `runtimeState.store`. */ @@ -105,7 +174,19 @@ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTile if (typeof queryKey !== "function" || typeof find !== "function") return undefined; const key: unknown = queryKey.call(tiles, projectId); if (!isProjectKey(key, projectId)) return undefined; - const query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + let query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + if (!query) { + const signalQuery = readOwn(service, format.tileQuery); + const readStatus = readOwn(signalQuery, "status"); + if (typeof readStatus === "function") { + try { + readStatus.call(signalQuery); + } catch (error) { + if (!isRequiredInputError(error)) throw error; + } + query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + } + } return isProjectKey(query?.queryKey, projectId) ? query : undefined; } @@ -120,7 +201,14 @@ export function isProjectStorePending(store: ProjectStore): boolean { const signalQuery = readOwn(store.service, store.format.tileQuery); if (signalQuery && typeof signalQuery === "object" && "isPending" in signalQuery) { const isPending = readOwn(signalQuery, "isPending"); - if (typeof isPending === "function" ? Boolean(isPending.call(signalQuery)) : isPending === true) { + if (typeof isPending === "function") { + try { + if (Boolean(isPending.call(signalQuery))) return true; + } catch (error) { + if (isRequiredInputError(error)) return true; + throw error; + } + } else if (isPending === true) { return true; } } @@ -157,7 +245,17 @@ export function readProjectStore(store: ProjectStore): Map | n const signalQuery = readOwn(store.service, store.format.tileQuery); if (!signalQuery || typeof signalQuery !== "object" || !("data" in signalQuery)) return null; const readData = readOwn(signalQuery, "data"); - const signalData: unknown = typeof readData === "function" ? readData.call(signalQuery) : readData; + let signalData: unknown; + if (typeof readData === "function") { + try { + signalData = readData.call(signalQuery); + } catch (error) { + if (isRequiredInputError(error)) return null; + throw error; + } + } else { + signalData = readData; + } return indexTileRows(signalData) ?? tileMap(signalData, store.format.rows); } @@ -327,23 +425,30 @@ function verifiedStoreLayout(): { format: ProjectStoreFormat; storeClass: Functi return typeof storeClass === "function" ? { format, storeClass } : null; } -/** Collects live `ProjectStore` candidates from one Angular `LView` array. */ -export function findProjectStoreInView( +/** Scans one Angular `LView` array for live verified `ProjectStore` candidates. */ +export function inspectProjectStoreInView( view: unknown, projectId: string, seen = new Set(), -): ProjectStore[] { - if (!Array.isArray(view)) return []; +): StoreViewScan { + if (!Array.isArray(view)) return { matches: [], inputPending: false }; const layout = verifiedStoreLayout(); - if (!layout) return []; + if (!layout) return { matches: [], inputPending: false }; const { format, storeClass } = layout; const matches: ProjectStore[] = []; + let inputPending = false; const consider = (value: unknown): void => { if (!value || typeof value !== "object" || seen.has(value)) return; seen.add(value); - if (!(value instanceof storeClass)) return; - const candidate: ProjectStore = { projectId, service: value, format }; - if (isCurrent(candidate)) matches.push(candidate); + if (!(value instanceof storeClass) || !isStoreLifecycleLive(value, format)) return; + const projectState = readStoreProjectId(value, format); + if (projectState.state === "loading") { + inputPending = true; + return; + } + if (projectState.state === "ready" && projectState.projectId === projectId) { + matches.push({ projectId, service: value, format }); + } }; for (const slot of view) { @@ -353,7 +458,32 @@ export function findProjectStoreInView( consider(Object.getOwnPropertyDescriptor(slot, key)?.value); } } - return matches; + return { matches, inputPending }; +} + +/** Extracts the normalized `/project/` route suffix from a URL or pathname. */ +function projectRoutePath(urlOrPath: string): string | null { + const pathname = urlOrPath.split(/[?#]/, 1)[0] ?? ""; + const idx = pathname.indexOf("/project/"); + if (idx < 0) return null; + return pathname.slice(idx).replace(/\/+$/, ""); +} + +/** Returns true while the browser document or Angular router still loads `/project/`. */ +export function isProjectRouteLoading(projectId: string): boolean { + if (projectInRoute() !== projectId) return false; + const targetPath = projectRoutePath(location.pathname); + if (!targetPath) return false; + if (document.readyState !== "complete") return true; + if (document.querySelector("flow-loading-page, .projects-loading-container")) return true; + const root = document.querySelector("aisandbox-root, app-root"); + if (root && root.childElementCount === 0 && readOwn(root, "__ngContext__") === undefined) { + return true; + } + const router = findRouter(); + if (!router) return false; + const routerUrl = readOwn(router, "url"); + return typeof routerUrl === "string" && projectRoutePath(routerUrl) !== targetPath; } /** Reports whether the current runtime has a bound and ready store for `projectId`. */ @@ -391,17 +521,25 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto return { ok: false, error: "unsupported_front_end", build }; } if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; + if (!(runtimeState.ngLViewMap instanceof Map)) { + bindAngularViews(maps, STORE_HOST_SELECTORS.join(", ")); + } if (!verifiedStoreLayout()) { clearProjectStore(); - return { ok: false, error: "collection_store_not_bound" }; + return isProjectRouteLoading(projectId) + ? { ok: false, error: "store_loading" } + : { ok: false, error: "collection_store_not_bound" }; } const seen = new Set(); const candidates: Array<{ store: ProjectStore; views: Map }> = []; + let inputPending = false; for (const map of maps) { if (!isNgLViewMap(map)) continue; for (const view of map.values()) { - for (const store of findProjectStoreInView(view, projectId, seen)) { + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + for (const store of scan.matches) { candidates.push({ store, views: map }); } } @@ -411,8 +549,11 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto const selected = candidates.find(({ store }) => store === selectedStore); if (!selected) { clearProjectStore(); - return candidates.length > 1 - ? { ok: false, error: "ambiguous_collection_store" } + if (candidates.length > 1) { + return { ok: false, error: "ambiguous_collection_store" }; + } + return inputPending || isProjectRouteLoading(projectId) + ? { ok: false, error: "store_loading" } : { ok: false, error: "collection_store_not_bound" }; } installProjectStore(selected.store, selected.views);