diff --git a/src/assets.rs b/src/assets.rs index c3c8975..2d06adf 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -166,11 +166,12 @@ async fn populate_missing_media_urls( ) { let mut missing: HashMap> = HashMap::new(); for (index, asset) in assets.iter().enumerate() { + let primary_succeeded = asset.media_status.as_deref() == Some("success"); if !matches!( asset.kind.as_str(), "video" | "image" | "character" | "audio" ) || asset.url.is_some() - || asset.media_error.is_some() + || (!primary_succeeded && asset.media_error.is_some()) || matches!( asset.media_status.as_deref(), Some("pending" | "scheduled" | "failed" | "canceled") diff --git a/src/cdp.rs b/src/cdp.rs index 8eadccd..547b5d0 100644 --- a/src/cdp.rs +++ b/src/cdp.rs @@ -404,7 +404,14 @@ fn handle_network_event( /// Returns `true` when `url` belongs to a Flow or Google auth host worth fetching on HTTP errors. fn is_error_body_candidate(url: &str) -> bool { - url.contains("aisandbox-pa.googleapis.com") + let flow_host = crate::config::FLOW_URL + .split("://") + .nth(1) + .and_then(|rest| rest.split(['/', '?', '#']).next()) + .filter(|host| !host.is_empty()) + .unwrap_or("flow.google.com"); + url.contains(flow_host) + || url.contains("aisandbox-pa.googleapis.com") || url.contains("labs.google") || url.contains("recaptcha") } diff --git a/src/generation.rs b/src/generation.rs index b9f3f55..1b89a5a 100644 --- a/src/generation.rs +++ b/src/generation.rs @@ -21,10 +21,10 @@ use crate::engine::{ChromeEngine, NetworkResponseEvent, validate_local_files}; use crate::project::{ensure_flow_store, ensure_project_workspace_root}; use crate::queue::{ProgressCallback, SceneParams}; -/// Batchexecute RPC IDs associated with Google Flow generation requests. +/// Batchexecute RPC IDs associated with Google Flow generation and upload requests. const BATCH_GENERATION_RPC_IDS: &[&str] = &[ "Z9cAtf", "ogiZ0b", "YhhmEf", "MZZa6b", "eb1hJf", "nprQif", "jIps6", "fZytfe", "p0UkFb", - "IJhj9c", "xNyCid", + "IJhj9c", "xNyCid", "LcEY2c", "SPrCad", "sAVZzc", "jeNy9c", "maseQ", ]; /// Parameters for `flow_generate`. @@ -77,8 +77,8 @@ pub(crate) struct EditParams { struct AssetWaitSpec<'a> { /// Asset IDs already present before submission. before_ids: &'a HashSet, - /// Optional existing tile `(asset_id, primary_media_id, url)` watched for replacement updates. - watch_updated: Option<(&'a str, Option<&'a str>, Option<&'a str>)>, + /// Optional baseline asset watched for replacement or appended failure updates. + watch_updated: Option<&'a FlowAsset>, /// Target number of generated outputs in the batch. expected_count: usize, /// Maximum wait time in seconds before failing with timeout. @@ -322,6 +322,37 @@ pub(crate) fn inspect_generation_network( Ok(accepted_status) } +/// Drains structured `batchexecute` RPC errors buffered inside `window.__flowMcp`. +async fn inspect_buffered_rpc_errors(engine: &ChromeEngine) -> Result<()> { + let Ok(drained) = engine + .call_flow_js("drainRpcErrors", json!([BATCH_GENERATION_RPC_IDS])) + .await + else { + return Ok(()); + }; + let Some(first) = drained.as_array().and_then(|items| items.first()) else { + return Ok(()); + }; + let rpc_id = first + .get("rpc_id") + .and_then(|v| v.as_str()) + .unwrap_or("batchexecute"); + let message = first + .get("message") + .and_then(|v| v.as_str()) + .unwrap_or("RPC failed"); + let code = first.get("code").and_then(|v| v.as_i64()); + if message.to_ascii_lowercase().contains("recaptcha") { + anyhow::bail!( + "Google Flow blocked generation in ChromeEngine due to a reCAPTCHA Enterprise error (RPC {rpc_id}: {message})" + ); + } + match code { + Some(c) => anyhow::bail!("Flow generation RPC {rpc_id} failed (code {c}): {message}"), + None => anyhow::bail!("Flow generation RPC {rpc_id} failed: {message}"), + } +} + /// Polls project snapshots until expected generated outputs resolve or fail. async fn wait_for_new_assets( engine: &ChromeEngine, @@ -341,6 +372,7 @@ async fn wait_for_new_assets( if let Some(code) = inspect_generation_network(net_rx, on_progress)? { accepted_status = Some(code); } + inspect_buffered_rpc_errors(engine).await?; let snap = match list_assets_with_project(engine).await { Ok(s) => { consecutive_errors = 0; @@ -363,15 +395,15 @@ async fn wait_for_new_assets( if !spec.before_ids.contains(&a.id) && a.url.is_some() { return true; } - if let Some((tid, prev_pmid, prev_url)) = spec.watch_updated - && a.id == tid + if let Some(prev) = spec.watch_updated + && a.id == prev.id && a.url.is_some() { let pmid_changed = a .primary_media_id .as_deref() - .is_some_and(|p| Some(p) != prev_pmid); - let url_changed = a.url.as_deref() != prev_url; + .is_some_and(|p| Some(p) != prev.primary_media_id.as_deref()); + let url_changed = a.url != prev.url; return pmid_changed || url_changed; } false @@ -387,10 +419,10 @@ async fn wait_for_new_assets( .collect(); last_pending_count = new_tiles.len(); last_pending_info = if new_tiles.is_empty() { - if let Some((tid, _, _)) = spec.watch_updated { + if let Some(prev) = spec.watch_updated { snap.assets .iter() - .find(|a| a.id == tid) + .find(|a| a.id == prev.id) .map(|a| { format!("{}:{}", a.id, a.media_status.as_deref().unwrap_or("none")) }) @@ -406,9 +438,10 @@ async fn wait_for_new_assets( .join(",") }; if !new_tiles.is_empty() - && new_tiles - .iter() - .all(|a| matches!(a.media_status.as_deref(), Some("failed" | "canceled"))) + && new_tiles.iter().all(|a| { + matches!(a.media_status.as_deref(), Some("failed" | "canceled")) + || (a.url.is_none() && a.media_error.is_some()) + }) { let first = new_tiles[0]; anyhow::bail!( @@ -420,15 +453,16 @@ async fn wait_for_new_assets( .unwrap_or(first.media_status.as_deref().unwrap_or("failed")) ); } - if let Some((tid, prev_pmid, _)) = spec.watch_updated - && let Some(watched) = snap.assets.iter().find(|a| a.id == tid) - && matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) - && (watched.primary_media_id.as_deref() != prev_pmid - || watched.media_error.is_some()) + if let Some(prev) = spec.watch_updated + && let Some(watched) = snap.assets.iter().find(|a| a.id == prev.id) + && ((matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) + && (watched.primary_media_id != prev.primary_media_id + || watched.media_error.is_some())) + || (watched.media_error.is_some() && watched.media_error != prev.media_error)) { anyhow::bail!( "Flow edit failed on {}: {}", - tid, + prev.id, watched .media_error .as_deref() @@ -700,11 +734,7 @@ pub(crate) async fn run_edit( engine, AssetWaitSpec { before_ids: &before, - watch_updated: Some(( - target.id.as_str(), - target.primary_media_id.as_deref(), - target.url.as_deref(), - )), + watch_updated: Some(&target), expected_count: 1, timeout_secs: 420, submit_summary: &submit_summary, diff --git a/src/scenes.rs b/src/scenes.rs index 4969fcc..bb39590 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -371,6 +371,26 @@ pub(crate) async fn run_video_extend( .call_flow_async("videoOp", json!([{ "action": "poll_extend" }])) .await .unwrap_or_default(); + if let Some(err_msg) = poll_res + .get("error") + .and_then(|v| v.as_str()) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + extend_err = Some( + match poll_res + .get("failed_workflow_id") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + Some(wf_id) => { + anyhow::anyhow!("Flow video extend failed on tile {wf_id}: {err_msg}") + } + None => anyhow::anyhow!("Flow video extend failed: {err_msg}"), + }, + ); + break; + } let extending = poll_res .get("extending") .and_then(|v| v.as_bool()) diff --git a/ts/character_media.ts b/ts/character_media.ts index 53d34d0..f476b2e 100644 --- a/ts/character_media.ts +++ b/ts/character_media.ts @@ -24,18 +24,11 @@ import { pickTileUrl, setNativeValue, } from "./dom"; -import { - characterPreviewFormat, - frontendBuild, - readBuildLabel, -} from "./frontend_builds"; +import { characterPreviewFormat, frontendBuild, readBuildLabel } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; +import { clearRpcErrors, drainTrackedRpcErrorMessage } from "./rpc_errors"; import { runtimeState } from "./state"; -import type { - CharacterMediaOpRequest, - FlowMediaPayload, - NgLView, -} from "./types"; +import type { CharacterMediaOpRequest, FlowMediaPayload, NgLView } from "./types"; /** Image slot in the character editor. */ type CharacterSlot = "portrait" | "body"; @@ -252,6 +245,7 @@ export async function characterMediaOp( const action = String(req?.action || "").toLowerCase(); if (action === "open_upload") { + clearRpcErrors(); const wantSlot = normSlot(req?.slot); const deadline = performance.now() + UPLOAD_SLOT_TIMEOUT_MS; for (const prev of document.querySelectorAll("[data-flow-mcp-upload]")) { @@ -377,6 +371,8 @@ export async function characterMediaOp( await delay(150); return { ok: true, done: false, accepted_consent: true }; } + const uploadRpcErr = drainTrackedRpcErrorMessage(); + if (uploadRpcErr) return { ok: false, error: "character_upload_failed", slot, detail: uploadRpcErr }; const prevSrc = String(req?.prev_src || "").trim(); const prevMediaId = String(req?.prev_media_id || "").trim(); const { slotMedia, slotMediaId, compSrc, imgSrc, isAreaBusy } = readPreviewSlotState(slot); @@ -401,6 +397,8 @@ export async function characterMediaOp( } if (action === "check_look") { + const lookRpcErr = drainTrackedRpcErrorMessage(); + if (lookRpcErr) return { ok: false, error: lookRpcErr }; const errSnack = findSnackbarMatch(/failed to generate|couldn't generate|unable to generate|policy|violat/i); if (errSnack) return { ok: false, error: errSnack.text }; const errTile = document.querySelector("flow-character-image-preview flow-error-tile"); @@ -846,15 +844,9 @@ export async function characterMediaOp( id: charId, }; } - lookSubmitPoint = { - x: r.left + r.width / 2, - y: r.top + r.height / 2, - }; - lookMeta = { - look_slot: lookSlot, - prev_look_media_id: prevLookMediaId, - prev_look_src: prevLookSrc, - }; + clearRpcErrors(); + lookSubmitPoint = { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + lookMeta = { look_slot: lookSlot, prev_look_media_id: prevLookMediaId, prev_look_src: prevLookSrc }; applied.push("look_prompt_prepared"); await delay(100); } diff --git a/ts/index.ts b/ts/index.ts index f28568a..5f34067 100644 --- a/ts/index.ts +++ b/ts/index.ts @@ -37,12 +37,14 @@ import { projectUpload, stageMediaFiles } from "./project_upload"; import { projectsOp } from "./projects_ops"; import { readStoreSnapshot } from "./read_store_snapshot"; import { resolveVideoUrl } from "./resolve_video_url"; +import { drainRpcErrors, installBatchRpcInterceptor } from "./rpc_errors"; import { sceneOp } from "./scene_ops"; import { setupGeneration } from "./setup_generation"; import { submitGeneration } from "./submit_generation"; import { videoOp } from "./video_ops"; if (!window.__flowMcp) { + installBatchRpcInterceptor(); window.__flowMcp = { checkAuth, buildLabel: readBuildLabel, @@ -83,5 +85,6 @@ if (!window.__flowMcp) { characterVoiceOp, characterMediaOp, characterExtraOp, + drainRpcErrors, }; } diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index 67e6de1..a510659 100644 --- a/ts/read_store_snapshot.ts +++ b/ts/read_store_snapshot.ts @@ -11,6 +11,7 @@ import { sceneContents } from "./scene_tiles"; import { asHttpOrDataUrl, characterLookMedia, + cleanMediaId, collectionIdOf, fifeEnv as getFifeEnv, isNonAssetTileType, @@ -229,6 +230,62 @@ export function readStoreSnapshot(): StoreSnapshotResult { return { ok: true, projectId, projectTitle, credits, assets, collections }; } +/** Summary of primary media and appended failure items in a workflow `history` array. */ +interface MediaHistorySummary { + /** Primary media entry matching `primaryId`, or `history[0]` when `primaryId` is absent. */ + primary: FlowMediaPayload | null; + /** Formatted error from the latest failed or canceled item in `history`, when present. */ + error: string | null; + /** Lowercase status (`failed` or `canceled`) of the latest failed item, when present. */ + failedStatus: string; +} + +/** Scans all entries in `rawHistory` to locate the primary media item and any appended failures. */ +function inspectMediaHistory( + rawHistory: unknown, + primaryId: string | null, + formatError: (errVal: unknown) => string | null, +): MediaHistorySummary { + if (!Array.isArray(rawHistory) || rawHistory.length === 0) { + return { primary: null, error: null, failedStatus: "" }; + } + const items: FlowMediaPayload[] = []; + for (const rawItem of rawHistory) { + if (rawItem && typeof rawItem === "object") { + items.push(legacyMedia(rawItem as FlowMediaPayload)); + } + } + if (items.length === 0) { + return { primary: null, error: null, failedStatus: "" }; + } + const wantedId = primaryId ? cleanMediaId(primaryId) : ""; + const primary = wantedId + ? items.find( + (item) => cleanMediaId(String(item.id ?? item.mediaId ?? "")) === wantedId, + ) ?? items[0] + : items[0]; + + let failedCount = 0; + let latestRawError: string | null = null; + let latestFailedStatus = ""; + for (const item of items) { + const status = String(item.Zc ?? "").toLowerCase(); + const err = formatError(item.nf); + if (status === "failed" || status === "canceled" || Boolean(err)) { + failedCount += 1; + latestFailedStatus = + status === "failed" || status === "canceled" ? status : "failed"; + latestRawError = err || latestFailedStatus; + } + } + const error = latestRawError + ? failedCount > 1 + ? `${latestRawError} (attempt ${failedCount})` + : latestRawError + : null; + return { primary, error, failedStatus: latestFailedStatus }; +} + /** Reads asset and collection details from the tile map. */ export function readStoreTiles(tileMap: Map): { assets: SnapshotAssetItem[]; @@ -317,22 +374,6 @@ export function readStoreTiles(tileMap: Map): { const charFallbackUrl = charMedia.url; const charLookPrimaryMediaId = charMedia.primaryMediaId; - const videoMediaUrl = - baseKind === "video" - ? readMediaUrl(t.Fb, true) || - readMediaUrl(t, true) || - readMediaUrl(t.fb, true) - : null; - - const mediaStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); - const mediaError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); - const mediaNotReady = - mediaStatus === "pending" || - mediaStatus === "scheduled" || - mediaStatus === "failed" || - mediaStatus === "canceled" || - Boolean(t.Fb?.nf || t.fb?.nf || t.nf); - const primaryMediaId = charLookPrimaryMediaId || t.primaryMediaId || @@ -342,6 +383,33 @@ export function readStoreTiles(tileMap: Map): { t.mediaId || null; + const histInfo = inspectMediaHistory( + readOwn(rawTile, "history") ?? t.history, + primaryMediaId ? String(primaryMediaId) : null, + formatMediaError, + ); + + const videoMediaUrl = + baseKind === "video" + ? readMediaUrl(t.Fb, true) || + readMediaUrl(histInfo.primary, true) || + readMediaUrl(t, true) || + readMediaUrl(t.fb, true) + : null; + + const primaryStatus = String( + t.Fb?.Zc ?? histInfo.primary?.Zc ?? t.fb?.Zc ?? t.Zc ?? "", + ).toLowerCase(); + const primaryError = formatMediaError( + t.Fb?.nf ?? histInfo.primary?.nf ?? t.fb?.nf ?? t.nf, + ); + const mediaNotReady = + primaryStatus === "pending" || + primaryStatus === "scheduled" || + primaryStatus === "failed" || + primaryStatus === "canceled" || + Boolean(primaryError); + const cachedEntry = primaryMediaId ? runtimeState.mediaInfoCache.get(String(primaryMediaId)) : undefined; @@ -355,6 +423,7 @@ export function readStoreTiles(tileMap: Map): { ? charFallbackUrl : videoMediaUrl || readMediaUrl(t.Fb) || + readMediaUrl(histInfo.primary) || readMediaUrl(t) || readMediaUrl(t.fb) || charFallbackUrl || @@ -365,6 +434,12 @@ export function readStoreTiles(tileMap: Map): { ? cachedMediaUrl : tileMediaUrl || cachedMediaUrl || null; const mediaUrl = mediaNotReady ? null : rawMediaUrl; + const hasReadyPrimary = !mediaNotReady && Boolean(primaryMediaId || rawMediaUrl); + const mediaStatus = + hasReadyPrimary && histInfo.error + ? primaryStatus || "success" + : primaryStatus || histInfo.failedStatus || ""; + const mediaError = primaryError ?? histInfo.error; const bio = (ttype === "CHARACTER" ? characterPersonalityNotes(t) : null) ?? @@ -461,56 +536,66 @@ export function readStoreTiles(tileMap: Map): { const sceneCid = collectionIdOf(st, isCollectionId); const { clips, history } = sceneContents(st); const candidates: Array< - [string, SceneClipItem | null, FlowMediaPayload | null] + [string, SceneClipItem | null, FlowMediaPayload[] | null] > = []; for (const clip of clips) { const wfId = clip?.workflowId ? String(clip.workflowId) : null; if (!wfId) continue; const hist = history.get(wfId); - const primaryId = clip?.primaryMediaId - ? String(clip.primaryMediaId) - : null; - const mObj = Array.isArray(hist) - ? hist.find((x) => x && String(x.id || "") === primaryId) || - hist[0] || - null - : null; - candidates.push([wfId, clip, mObj]); + candidates.push([wfId, clip, Array.isArray(hist) ? hist : null]); } for (const [wfId, hist] of history) { - const mObj = Array.isArray(hist) ? hist[0] || null : null; - candidates.push([wfId, null, mObj]); + candidates.push([wfId, null, Array.isArray(hist) ? hist : null]); } - for (const [wfId, clip, rawMedia] of candidates) { + for (const [wfId, clip, rawHist] of candidates) { if (!wfId) continue; - const mObj = legacyMedia(rawMedia); + const primaryId = clip?.primaryMediaId + ? String(clip.primaryMediaId) + : null; + const histInfo = inspectMediaHistory(rawHist, primaryId, formatMediaError); + const mObj = histInfo.primary; const cObj = legacyMedia(clip as FlowMediaPayload | null); - const mStatus = String( + const primaryStatus = String( mObj?.Zc ?? cObj?.Zc ?? clip?.Zc ?? "", ).toLowerCase(); - const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const primaryError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const mNotReady = + primaryStatus === "pending" || + primaryStatus === "scheduled" || + primaryStatus === "failed" || + primaryStatus === "canceled" || + Boolean(primaryError); + const mError = primaryError ?? histInfo.error; const existing = byId.get(wfId); if (existing) { - if (mStatus === "failed" || mStatus === "canceled" || mError) { + if ( + primaryStatus === "failed" || + primaryStatus === "canceled" || + Boolean(mError) + ) { + const existingReady = + existing.media_status === "success" || Boolean(existing.url); if ( + !existingReady && existing.media_status !== "failed" && existing.media_status !== "canceled" ) { - existing.media_status = mStatus || existing.media_status; + existing.media_status = + primaryStatus || histInfo.failedStatus || existing.media_status; + } else if (existingReady && !existing.media_status) { + existing.media_status = "success"; } - if (!existing.media_error && mError) { + if ( + mError && + (!existing.media_error || + mError.length > existing.media_error.length) + ) { existing.media_error = mError; } } continue; } - const mNotReady = - mStatus === "pending" || - mStatus === "scheduled" || - mStatus === "failed" || - mStatus === "canceled" || - Boolean(mObj?.nf || cObj?.nf || clip?.nf); const clipPrimaryMediaId = clip?.primaryMediaId ? String(clip.primaryMediaId) : mObj?.id @@ -530,9 +615,14 @@ export function readStoreTiles(tileMap: Map): { const rawClipUrl = isSignedUrlStr(tileClipUrl) ? tileClipUrl : isSignedUrlStr(cachedClipVideoUrl) - ? cachedClipVideoUrl + ? cachedClipVideoUrl : tileClipUrl || cachedClipVideoUrl || null; const clipUrl = mNotReady ? null : rawClipUrl; + const hasReadyClip = !mNotReady && Boolean(clipPrimaryMediaId || rawClipUrl); + const mStatus = + hasReadyClip && histInfo.error + ? primaryStatus || "success" + : primaryStatus || histInfo.failedStatus || ""; const trimStartVal = typeof clip?.Ji === "number" ? clip.Ji : typeof mObj?.Jc === "number" ? mObj.Jc : diff --git a/ts/rpc_errors.ts b/ts/rpc_errors.ts new file mode 100644 index 0000000..157f5ed --- /dev/null +++ b/ts/rpc_errors.ts @@ -0,0 +1,498 @@ +// Copyright 2026 ByteLand Technology Limited +// SPDX-License-Identifier: MIT + +// Observe in-page batchexecute responses and buffer structured wrb.fr and er errors. + +import type { BufferedRpcError } from "./types"; + +/** Maximum number of structured RPC error entries retained in the ring buffer. */ +const MAX_RPC_ERROR_ENTRIES = 64; + +/** Maximum character length of one buffered RPC error message. */ +const MAX_RPC_ERROR_MESSAGE_CHARS = 500; + +/** Read-only internal probe RPC identifiers excluded from the error ring buffer. */ +const IGNORED_PROBE_RPC_IDS = new Set(["cPZSdc", "as29s"]); + +/** Batchexecute RPC identifiers for Google Flow generation, transform, and upload actions. */ +export const TRACKED_GENERATION_RPC_IDS = [ + "Z9cAtf", + "ogiZ0b", + "YhhmEf", + "MZZa6b", + "eb1hJf", + "nprQif", + "jIps6", + "fZytfe", + "p0UkFb", + "IJhj9c", + "xNyCid", + "LcEY2c", + "SPrCad", + "sAVZzc", + "jeNy9c", + "maseQ", +] as const; + +/** Metadata recorded passively for an in-flight XMLHttpRequest to batchexecute. */ +interface BatchXhrMeta { + /** Request URL passed to `XMLHttpRequest.prototype.open`. */ + url: string; + /** Serialized text body passed to `XMLHttpRequest.prototype.send`, when available. */ + body: string | null; + /** True once the completed response for this `open` cycle has been inspected. */ + recorded: boolean; +} + +/** Bounded FIFO ring buffer of captured batchexecute error entries. */ +const rpcErrorRing: BufferedRpcError[] = []; + +/** Monotonic sequence counter assigned to buffered RPC error entries. */ +let nextRpcErrorSeq = 1; + +/** Guard that prevents duplicate transport hooks in the same document. */ +let interceptorInstalled = false; + +/** Truncates `raw` to at most `MAX_RPC_ERROR_MESSAGE_CHARS` Unicode code points. */ +function truncateErrorMessage(raw: string): string { + const trimmed = raw.trim(); + const chars = Array.from(trimmed); + return chars.length <= MAX_RPC_ERROR_MESSAGE_CHARS + ? trimmed + : chars.slice(0, MAX_RPC_ERROR_MESSAGE_CHARS).join(""); +} + +/** Appends one error entry to `rpcErrorRing` and evicts oldest entries past 64. */ +function pushRpcError(entry: Omit): void { + const message = truncateErrorMessage(entry.message); + if (!message) return; + rpcErrorRing.push({ + ...entry, + message, + seq: nextRpcErrorSeq++, + }); + while (rpcErrorRing.length > MAX_RPC_ERROR_ENTRIES) { + rpcErrorRing.shift(); + } +} + +/** Returns true when `url` targets a Google Boq `batchexecute` endpoint. */ +function isBatchExecuteUrl(url: string): boolean { + return url.includes("batchexecute"); +} + +/** Extracts text from a fetch or XHR request body without consuming streams. */ +function readBodyString(body: unknown): string | null { + if (typeof body === "string") return body; + if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) { + return body.toString(); + } + return null; +} + +/** Extracts candidate RPC identifiers from `url` query parameters and `f.req` form data. */ +function extractRequestRpcIds(url: string, bodyText: string | null): string[] { + const ids: string[] = []; + const addId = (candidate: string): void => { + const clean = candidate.trim(); + if (/^[A-Za-z0-9_]{4,12}$/.test(clean) && !ids.includes(clean)) { + ids.push(clean); + } + }; + + try { + const parsed = new URL(url, location.origin); + const rawParam = parsed.searchParams.get("rpcids") || ""; + for (const part of rawParam.split(",")) { + if (part) addId(part); + } + } catch { + const match = /[?&]rpcids=([^&#]+)/.exec(url); + if (match) { + for (const part of decodeURIComponent(match[1]).split(",")) { + if (part) addId(part); + } + } + } + + if (bodyText) { + let freq = bodyText; + if (bodyText.includes("f.req=")) { + try { + freq = new URLSearchParams(bodyText).get("f.req") || bodyText; + } catch { + // Keep raw body string when URLSearchParams decoding fails. + } + } + try { + const outer: unknown = JSON.parse(freq); + if (Array.isArray(outer) && Array.isArray(outer[0])) { + for (const call of outer[0]) { + if (Array.isArray(call) && typeof call[0] === "string") { + addId(call[0]); + } + } + } + } catch { + const re = /\[\s*"([A-Za-z0-9_]{4,12})"\s*,/g; + let hit = re.exec(freq); + while (hit) { + addId(hit[1]); + hit = re.exec(freq); + } + } + } + + return ids; +} + +/** Collects human-readable detail strings nested inside a JSPB error detail structure. */ +function collectNestedStrings(node: unknown, out: string[], depth: number): void { + if (depth <= 0 || out.length >= 6 || node == null) return; + if (typeof node === "string") { + const clean = node.trim(); + if ( + clean && + !clean.startsWith("type.googleapis.com/") && + !/^[a-z0-9_.-]+\.[A-Za-z0-9_]+$/.test(clean) && + !out.includes(clean) + ) { + out.push(clean); + } + return; + } + if (Array.isArray(node)) { + for (const child of node) { + collectNestedStrings(child, out, depth - 1); + } + return; + } + if (typeof node === "object") { + const msg = (node as { message?: unknown }).message; + if (typeof msg === "string") { + collectNestedStrings(msg, out, depth - 1); + } + } +} + +/** Formats code and message fields from a `wrb.fr` error payload at `entry[5]`. */ +function extractWrbError(rpcErr: unknown): { code: number | null; message: string } { + if (typeof rpcErr === "string") { + return { code: null, message: rpcErr.trim() || "RPC failed" }; + } + if (typeof rpcErr === "number") { + return { code: rpcErr, message: `RPC error code ${rpcErr}` }; + } + if (Array.isArray(rpcErr)) { + const code = typeof rpcErr[0] === "number" ? rpcErr[0] : null; + const primary = typeof rpcErr[1] === "string" ? rpcErr[1].trim() : ""; + const details: string[] = []; + if (rpcErr.length > 2) { + collectNestedStrings(rpcErr.slice(2), details, 5); + } + const detailSuffix = details.filter((d) => d !== primary).join("; "); + const combined = primary && detailSuffix + ? `${primary} (${detailSuffix})` + : primary || detailSuffix; + if (combined) { + return { code, message: combined }; + } + return { + code, + message: code !== null ? `RPC error code ${code}` : "RPC failed", + }; + } + if (rpcErr && typeof rpcErr === "object") { + const msg = (rpcErr as { message?: unknown }).message; + if (typeof msg === "string" && msg.trim()) { + return { code: null, message: msg.trim() }; + } + try { + return { code: null, message: JSON.stringify(rpcErr) }; + } catch { + return { code: null, message: "RPC failed" }; + } + } + return { code: null, message: "RPC failed" }; +} + +/** Formats code and message fields from an envelope-level `["er", ...]` frame. */ +function extractErFrame( + entry: unknown[], + requestRpcIds: string[], +): { rpcId: string; code: number | null; message: string } { + const code = + typeof entry[5] === "number" + ? entry[5] + : typeof entry[1] === "number" + ? entry[1] + : typeof entry[2] === "number" + ? entry[2] + : null; + const entryRpcId = + typeof entry[1] === "string" && /^[A-Za-z0-9_]{4,12}$/.test(entry[1].trim()) + ? entry[1].trim() + : null; + const rpcId = requestRpcIds[0] ?? entryRpcId ?? "er"; + const parts: string[] = []; + for (const field of [entry[2], entry[4], entry[3], entry[1]]) { + if (typeof field === "string" && field.trim() === rpcId) continue; + collectNestedStrings(field, parts, 4); + } + const message = + parts.join("; ") || + (code !== null ? `Batch RPC error code ${code}` : "Batch RPC error"); + return { rpcId, code, message }; +} + +/** Parses one `batchexecute` response payload and appends any `wrb.fr` or `er` errors. */ +export function recordBatchExecuteResponse( + url: string, + requestRpcIds: string[], + status: number, + bodyText: string, +): void { + if (!bodyText || (!bodyText.includes("wrb.fr") && !bodyText.includes('"er"'))) { + return; + } + const rpcIdsFromReq = + requestRpcIds.length > 0 ? requestRpcIds : extractRequestRpcIds(url, null); + for (const rawLine of bodyText.split(/\r?\n/)) { + const line = rawLine.replace(/^\)\]\}'\s*/, "").trim(); + if (!line.startsWith("[")) continue; + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + continue; + } + if (!Array.isArray(parsed) || parsed.length === 0) continue; + const frames: unknown[] = + parsed[0] === "wrb.fr" || parsed[0] === "er" ? [parsed] : parsed; + for (const frame of frames) { + if (!Array.isArray(frame) || frame.length === 0) continue; + const tag = frame[0]; + if (tag === "wrb.fr") { + const rpcId = + typeof frame[1] === "string" && frame[1].trim() + ? frame[1].trim() + : (rpcIdsFromReq[0] ?? "wrb.fr"); + if (IGNORED_PROBE_RPC_IDS.has(rpcId)) continue; + const hasData = + frame[2] != null || frame[9] != null || frame[10] != null; + if (hasData || frame[5] == null) continue; + const { code, message } = extractWrbError(frame[5]); + const rpcIds = Array.from(new Set([rpcId, ...rpcIdsFromReq])); + pushRpcError({ + kind: "wrb.fr", + rpc_id: rpcId, + rpc_ids: rpcIds, + code, + status, + message, + }); + } else if (tag === "er") { + if ( + rpcIdsFromReq.length > 0 && + rpcIdsFromReq.every((id) => IGNORED_PROBE_RPC_IDS.has(id)) + ) { + continue; + } + const { rpcId, code, message } = extractErFrame(frame, rpcIdsFromReq); + if (IGNORED_PROBE_RPC_IDS.has(rpcId)) continue; + const rpcIds = + rpcIdsFromReq.length > 0 + ? rpcIdsFromReq.slice() + : rpcId !== "er" + ? [rpcId] + : []; + pushRpcError({ + kind: "er", + rpc_id: rpcId, + rpc_ids: rpcIds, + code, + status, + message, + }); + } + } + } +} + +/** Clears all buffered RPC errors before starting a new user operation. */ +export function clearRpcErrors(): void { + rpcErrorRing.length = 0; +} + +/** Drains and returns buffered RPC errors matching `rpcIds` (or all errors when omitted). */ +export function drainRpcErrors( + rpcIds?: readonly string[] | null, +): BufferedRpcError[] { + if (!rpcIds || rpcIds.length === 0) { + return rpcErrorRing.splice(0, rpcErrorRing.length); + } + const wanted = new Set( + rpcIds.map((id) => String(id).trim()).filter(Boolean), + ); + if (wanted.size === 0) { + return rpcErrorRing.splice(0, rpcErrorRing.length); + } + const matched: BufferedRpcError[] = []; + let writeIdx = 0; + for (let i = 0; i < rpcErrorRing.length; i++) { + const item = rpcErrorRing[i]; + const hits = + wanted.has(item.rpc_id) || + item.rpc_ids.some((id) => wanted.has(id)) || + (item.kind === "er" && item.rpc_ids.length === 0); + if (hits) { + matched.push(item); + } else { + rpcErrorRing[writeIdx++] = item; + } + } + rpcErrorRing.length = writeIdx; + return matched; +} + +/** Drains matching tracked RPC errors and formats the first failure string, or returns null. */ +export function drainTrackedRpcErrorMessage( + rpcIds: readonly string[] = TRACKED_GENERATION_RPC_IDS, +): string | null { + const drained = drainRpcErrors(rpcIds); + if (drained.length === 0) return null; + const first = drained[0]; + const prefix = + first.code !== null + ? `${first.rpc_id} (code ${first.code})` + : first.rpc_id; + return truncateErrorMessage(`${prefix}: ${first.message}`); +} + +/** Installs passive `fetch` and `XMLHttpRequest` observers for `batchexecute` once per document. */ +export function installBatchRpcInterceptor(): void { + if (interceptorInstalled) return; + interceptorInstalled = true; + + if (typeof window.fetch === "function") { + const origFetch = window.fetch; + const wrappedFetch: typeof window.fetch = function ( + input: RequestInfo | URL, + init?: RequestInit, + ): Promise { + let url = ""; + try { + url = + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : typeof Request !== "undefined" && input instanceof Request + ? input.url + : ""; + } catch { + url = ""; + } + if (!url || !isBatchExecuteUrl(url)) { + return origFetch.call(window, input, init); + } + const reqIds = extractRequestRpcIds(url, readBodyString(init?.body)); + const responsePromise = origFetch.call(window, input, init); + responsePromise.then( + (resp) => { + try { + const cloned = resp.clone(); + void cloned.text().then( + (text) => { + try { + recordBatchExecuteResponse(url, reqIds, resp.status, text); + } catch { + // Ignore malformed batch payloads. + } + }, + () => { + // Ignore aborted response reads. + }, + ); + } catch { + // Ignore locked or opaque responses. + } + }, + () => { + // Ignore network rejections handled by caller. + }, + ); + return responsePromise; + }; + window.fetch = wrappedFetch; + } + + if (typeof XMLHttpRequest !== "undefined") { + const xhrMeta = new WeakMap(); + const observedXhrs = new WeakSet(); + const proto = XMLHttpRequest.prototype; + const origOpen = proto.open; + const origSend = proto.send; + + proto.open = function ( + this: XMLHttpRequest, + method: string, + url: string | URL, + async?: boolean, + username?: string | null, + password?: string | null, + ): void { + try { + const urlStr = typeof url === "string" ? url : String(url ?? ""); + if (isBatchExecuteUrl(urlStr)) { + xhrMeta.set(this, { url: urlStr, body: null, recorded: false }); + if (!observedXhrs.has(this)) { + observedXhrs.add(this); + this.addEventListener("readystatechange", () => { + if (this.readyState !== 4) return; + const cur = xhrMeta.get(this); + if (!cur || cur.recorded) return; + cur.recorded = true; + try { + if (this.responseType === "" || this.responseType === "text") { + const reqIds = extractRequestRpcIds(cur.url, cur.body); + recordBatchExecuteResponse( + cur.url, + reqIds, + this.status, + this.responseText || "", + ); + } + } catch { + // Ignore non-text XHR responses. + } + }); + } + } else { + xhrMeta.delete(this); + } + } catch { + // Ignore non-standard open arguments. + } + origOpen.call( + this, + method, + url, + async ?? true, + username ?? null, + password ?? null, + ); + }; + + proto.send = function ( + this: XMLHttpRequest, + body?: Document | XMLHttpRequestBodyInit | null, + ): void { + const meta = xhrMeta.get(this); + if (meta) { + meta.body = readBodyString(body); + } + origSend.call(this, body); + }; + } +} diff --git a/ts/setup_generation.ts b/ts/setup_generation.ts index af2018c..2ea0b9a 100644 --- a/ts/setup_generation.ts +++ b/ts/setup_generation.ts @@ -14,6 +14,7 @@ import { settingsOpen, } from "./composer"; import { delay, elText, hoverProbe, isVisibleEnabled } from "./dom"; +import { clearRpcErrors } from "./rpc_errors"; import { runtimeState } from "./state"; import type { GenerationConfig, NgLView } from "./types"; @@ -232,6 +233,7 @@ async function ensureLViewCapture(allowSettingsClick = false): Promise { export async function setupGeneration( cfg: GenerationConfig, ): Promise<{ ok: boolean; error?: string }> { + clearRpcErrors(); const onEditPage = /\/edit\//.test(location.pathname || ""); if (!onEditPage) { diff --git a/ts/types.ts b/ts/types.ts index 2e1369d..f389050 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -256,6 +256,8 @@ export interface FlowTile extends FlowMediaPayload { Oc?: SceneClipItem[]; /** Scene clip workflow history lookup. */ Yf?: Map | Record; + /** Media generation history array on workflow tiles. */ + history?: FlowMediaPayload[]; /** Tile width alias. */ width?: number; /** Tile height alias. */ @@ -785,6 +787,24 @@ export interface StoreProbeResult { operations: Record; } +/** One structured `batchexecute` RPC error stored in the runtime ring buffer. */ +export interface BufferedRpcError { + /** Envelope tag (`wrb.fr` or `er`). */ + kind: "wrb.fr" | "er"; + /** Primary RPC identifier associated with the error. */ + rpc_id: string; + /** All RPC identifiers associated with the request or frame. */ + rpc_ids: string[]; + /** Numeric gRPC or HTTP error code when present. */ + code: number | null; + /** HTTP status code of the transport response. */ + status: number; + /** Truncated error message (at most 500 characters). */ + message: string; + /** Monotonic sequence counter assigned on insertion. */ + seq: number; +} + /** Public browser runtime API exposed at `window.__flowMcp`. */ export interface FlowMcpRuntime { /** Returns the temporary input for a local media upload. */ @@ -877,6 +897,8 @@ export interface FlowMcpRuntime { locatePoint: (req: LocatePointRequest) => ViewportPoint | null; /** Locates a project tile in the page, reads its trash state, or closes an open menu. */ tileDomOp: (req: TileDomOpRequest) => Promise; + /** Drains buffered `batchexecute` `wrb.fr` and `er` errors matching optional RPC IDs. */ + drainRpcErrors: (rpcIds?: readonly string[] | null) => BufferedRpcError[]; } declare global { diff --git a/ts/video_ops.ts b/ts/video_ops.ts index 0cc0e8c..0d02abc 100644 --- a/ts/video_ops.ts +++ b/ts/video_ops.ts @@ -3,13 +3,157 @@ // Trim Flow videos and drive the scene builder extend workflow. -import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, withLViewMapCapture } from "./angular"; +import { buildProjectUrl, createScene, findRouter, navigateSpa, readAngularTooltip, readOwn, resolveLView, withLViewMapCapture } from "./angular"; import { findComposerWarning } from "./composer"; -import { delay, elText, hoverProbe, isDisabledProp, isVisibleEnabled, legacyTile, videoTrimBounds } from "./dom"; +import { discoverStore } from "./discover_store"; +import { cleanMediaId, delay, elText, hoverProbe, isDisabledProp, isTrashedTile, isVisibleEnabled, legacyMedia, legacyTile, videoTrimBounds } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { writePromptBox } from "./prompt_writer"; +import { clearRpcErrors, drainTrackedRpcErrorMessage } from "./rpc_errors"; +import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { FlowTile, VideoOpRequest } from "./types"; +import type { FlowMediaPayload, FlowTile, VideoOpRequest } from "./types"; + +/** Per-workflow status snapshot used to detect newly appended extend failures. */ +interface ExtendWorkflowSummary { + /** Number of pending or scheduled media entries on the workflow. */ + pendingCount: number; + /** Number of failed or canceled media entries on the workflow. */ + failedCount: number; + /** Identifiers of failed or canceled media entries on the workflow. */ + failedIds: Set; + /** Formatted message of the most recent failed entry on the workflow. */ + latestError: string | null; +} + +/** Baseline workflow state captured right before clicking Start generation in `prepare_extend`. */ +let extendBaseline: Map | null = null; + +/** Formats a media failure payload into a readable string, or returns null. */ +function formatExtendMediaError(errVal: unknown): string | null { + if (errVal == null || errVal === "") return null; + if (typeof errVal === "string") return errVal.trim() || null; + const msg = readOwn(errVal, "message"); + if (typeof msg === "string" && msg.trim()) return msg.trim(); + try { + return JSON.stringify(errVal); + } catch { + return String(errVal); + } +} + +/** Collects workflow media item lists from the project store and live scene builder view. */ +function collectExtendWorkflowItems(): Map { + const workflows = new Map(); + const appendItems = (wfId: string, items: readonly FlowMediaPayload[]): void => { + if (!wfId || items.length === 0) return; + const list = workflows.get(wfId) ?? []; + for (const raw of items) { + if (!raw || typeof raw !== "object") continue; + const norm = legacyMedia(raw); + const itemId = cleanMediaId(String(norm.id ?? norm.mediaId ?? "")); + if ( + itemId && + list.some((prev) => cleanMediaId(String(prev.id ?? prev.mediaId ?? "")) === itemId) + ) { + continue; + } + list.push(norm); + } + if (list.length > 0) workflows.set(wfId, list); + }; + + const activeSceneId = /\/scene\/([^/?#]+)/.exec(location.pathname || "")?.[1] ?? null; + const tileMap = runtimeState.store?.getTileMap?.(); + if (tileMap instanceof Map) { + for (const [id, rawTile] of tileMap.entries()) { + const tile = legacyTile(rawTile); + if (!tile || isTrashedTile(tile)) continue; + const tid = String(tile.id ?? id); + const ttype = String(tile.type ?? "").toUpperCase(); + if (ttype === "SCENE") { + if (activeSceneId && tid !== activeSceneId) continue; + const { history } = sceneContents(rawTile); + for (const [wfId, hist] of history.entries()) { + if (Array.isArray(hist)) appendItems(wfId, hist); + } + } else if (ttype === "VIDEO") { + const hist = readOwn(rawTile, "history"); + if (Array.isArray(hist)) { + appendItems(tid, hist as FlowMediaPayload[]); + } + if (tile.Fb) { + appendItems(tid, [tile.Fb]); + } + } + } + } + + const sb = document.querySelector("flow-scene-builder"); + const lv = sb ? resolveLView(sb) : null; + if (Array.isArray(lv)) { + for (const slot of lv) { + if (!slot || typeof slot !== "object" || slot instanceof Node || Array.isArray(slot)) { + continue; + } + for (const key of Object.keys(slot)) { + const val = readOwn(slot, key); + if (!(val instanceof Map) || val.size === 0) continue; + const sample = val.entries().next().value as [unknown, unknown] | undefined; + const firstItem = Array.isArray(sample?.[1]) ? sample[1][0] : undefined; + if ( + !sample || + typeof sample[0] !== "string" || + !Array.isArray(sample[1]) || + !firstItem || + typeof firstItem !== "object" || + firstItem instanceof Node || + !( + "id" in firstItem || + "od" in firstItem || + "Zc" in firstItem || + "Bf" in firstItem || + "nf" in firstItem + ) + ) { + continue; + } + for (const [wfId, hist] of val.entries()) { + if (typeof wfId === "string" && Array.isArray(hist)) { + appendItems(wfId, hist as FlowMediaPayload[]); + } + } + } + } + } + + return workflows; +} + +/** Summarizes pending and failed history counts per workflow for extend polling. */ +function captureExtendWorkflowSummary(): Map { + const summaries = new Map(); + for (const [wfId, items] of collectExtendWorkflowItems().entries()) { + let pendingCount = 0; + let failedCount = 0; + const failedIds = new Set(); + let latestError: string | null = null; + items.forEach((item, index) => { + const status = String(item.Zc ?? "").toLowerCase(); + const err = formatExtendMediaError(item.nf); + if (status === "pending" || status === "scheduled") { + pendingCount += 1; + } else if (status === "failed" || status === "canceled" || Boolean(err)) { + failedCount += 1; + const fid = cleanMediaId(String(item.id ?? item.mediaId ?? "")) || `#${index}`; + failedIds.add(fid); + latestError = err || status || "failed"; + } + }); + summaries.set(wfId, { pendingCount, failedCount, failedIds, latestError }); + } + return summaries; +} /** Checks whether an observed start trim bound matches the requested start time. */ function startBoundMatches( @@ -459,10 +603,49 @@ export async function videoOp(req: VideoOpRequest): Promise { if (!submitBtn.contains(document.elementFromPoint(x, y))) { return { ok: false, error: "extend_submit_button_obscured" }; } + if (activeProjectStoreFormat()) { + if (!runtimeState.store || !runtimeState.store.isCurrent()) { + await discoverStore(); + } + for (let i = 0; i < 20 && runtimeState.store && !runtimeState.store.isReady(); i++) { + await delay(100); + } + } + clearRpcErrors(); + extendBaseline = captureExtendWorkflowSummary(); return { ok: true, submit_point: { x, y } }; } if (action === "poll_extend") { + const rpcError = drainTrackedRpcErrorMessage(); + if (rpcError) { + return { ok: true, extending: false, error: rpcError }; + } + if ((!runtimeState.store || !runtimeState.store.isCurrent()) && activeProjectStoreFormat()) { + await discoverStore(); + } + const currentWorkflows = captureExtendWorkflowSummary(); + let busyHistory = false; + for (const [wfId, cur] of currentWorkflows.entries()) { + if (cur.pendingCount > 0) { + busyHistory = true; + } + if (cur.failedCount > 0) { + const prior = extendBaseline?.get(wfId); + const hasNewFailedId = prior + ? Array.from(cur.failedIds).some((fid) => !prior.failedIds.has(fid)) + : true; + if (!prior || cur.failedCount > prior.failedCount || hasNewFailedId) { + extendBaseline = currentWorkflows; + return { + ok: true, + extending: false, + error: cur.latestError || "failed", + failed_workflow_id: wfId, + }; + } + } + } const busyDom = Boolean( document.querySelector( "flow-scene-timeline .is-extend-generating, flow-scene-timeline .pending-placeholder, flow-scene-timeline [aria-busy='true']", @@ -478,7 +661,7 @@ export async function videoOp(req: VideoOpRequest): Promise { !el.closest('[contenteditable="true"], textarea, input') && /\bExtending\b|Extending…/i.test(elText(el)), ); - return { ok: true, extending: busyDom || extendingText }; + return { ok: true, extending: busyDom || extendingText || busyHistory }; } if (action === "done_scene") {