diff --git a/src/assets.rs b/src/assets.rs index c3c8975..ee0bc1a 100644 --- a/src/assets.rs +++ b/src/assets.rs @@ -28,7 +28,7 @@ const MEDIA_URL_LOOKUPS: usize = 4; const ASSET_LIST_URL_BUDGET: Duration = Duration::from_secs(10); /// Media asset or scene item inside a Google Flow project. -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub(crate) struct FlowAsset { /// Flow asset or tile ID. pub(crate) id: String, @@ -78,11 +78,74 @@ pub(crate) struct FlowAsset { /// Internal media error payload used for generation failure detection. #[serde(default, skip_serializing)] pub(crate) media_error: Option, + /// True when the primary media item succeeded and can resolve a direct media URL. + #[serde(default, skip_serializing)] + pub(crate) primary_ready: Option, + /// Ordered markers of failed or canceled workflow history items. + #[serde(default, skip_serializing)] + pub(crate) failed_history: Vec, /// Creation timestamp (`createTime`) string. #[serde(skip_serializing_if = "Option::is_none")] pub(crate) created_at: Option, } +/// Splits one `||` history failure marker into key, payload, and display text. +fn parse_failure_marker(entry: &str) -> (&str, &str, &str) { + let (key, payload) = entry.split_once('|').unwrap_or((entry, "")); + let (status, error) = payload.split_once('|').unwrap_or((payload, "")); + let detail = if !error.is_empty() { + error + } else if !status.is_empty() { + status + } else { + "failed" + }; + (key, payload, detail) +} + +impl FlowAsset { + /// Returns the error or status text of a history failure added after `baseline`. + pub(crate) fn new_failure<'a>(&'a self, baseline: &[String]) -> Option<&'a str> { + let has_new_key = self.failed_history.iter().any(|entry| { + let (key, _, _) = parse_failure_marker(entry); + !baseline.iter().any(|b| parse_failure_marker(b).0 == key) + }); + if !has_new_key && self.failed_history.len() <= baseline.len() { + return None; + } + self.failed_history + .iter() + .rev() + .find(|entry| { + let (_, payload, _) = parse_failure_marker(entry); + let cur_count = self + .failed_history + .iter() + .filter(|x| parse_failure_marker(x).1 == payload) + .count(); + let base_count = baseline + .iter() + .filter(|x| parse_failure_marker(x).1 == payload) + .count(); + cur_count > base_count + }) + .or_else(|| { + self.failed_history.iter().rev().find(|entry| { + let (key, _, _) = parse_failure_marker(entry); + !baseline.iter().any(|b| parse_failure_marker(b).0 == key) + }) + }) + .map(|entry| parse_failure_marker(entry).2) + } + + /// Returns the display text of the last recorded entry in `failed_history`. + pub(crate) fn latest_failure_detail(&self) -> Option<&str> { + self.failed_history + .last() + .map(|entry| parse_failure_marker(entry).2) + } +} + /// Snapshot of active project metadata and asset tiles. #[derive(Debug, Clone)] pub(crate) struct ProjectAssetsSnapshot { @@ -166,15 +229,17 @@ async fn populate_missing_media_urls( ) { let mut missing: HashMap> = HashMap::new(); for (index, asset) in assets.iter().enumerate() { + let primary_not_ready = asset.primary_ready != Some(true) + && (asset.media_error.is_some() + || matches!( + asset.media_status.as_deref(), + Some("pending" | "scheduled" | "failed" | "canceled") + )); if !matches!( asset.kind.as_str(), "video" | "image" | "character" | "audio" ) || asset.url.is_some() - || asset.media_error.is_some() - || matches!( - asset.media_status.as_deref(), - Some("pending" | "scheduled" | "failed" | "canceled") - ) + || primary_not_ready { continue; } diff --git a/src/cdp.rs b/src/cdp.rs index 8eadccd..dd3e8a8 100644 --- a/src/cdp.rs +++ b/src/cdp.rs @@ -15,7 +15,11 @@ use std::time::Duration; use tokio::sync::{Mutex, broadcast, oneshot}; use tokio_tungstenite::tungstenite::Message; +use crate::config::FLOW_URL; use crate::engine::NetworkResponseEvent; +use crate::generation::{ + has_generation_batchexecute_rpc, is_generation_rpc_id, is_generation_rpc_url, +}; /// Error object returned inside a CDP JSON-RPC response frame. #[derive(Debug, Deserialize)] @@ -348,7 +352,9 @@ fn handle_network_event( .remove(req_id) .unwrap_or_else(|| "GET".to_string()); - if status >= 400 && is_error_body_candidate(&url) { + let inspect_body = network_tx.receiver_count() > 0 + && should_inspect_response_body(&req_method, status, &url); + if inspect_body { if pending_bodies.len() > 256 { pending_bodies.clear(); } @@ -378,7 +384,7 @@ fn handle_network_event( return; }; tokio::spawn(async move { - let excerpt = fetch_error_excerpt(&t, &req_id_owned).await; + let excerpt = fetch_error_excerpt(&t, &req_id_owned, status).await; let _ = tx.send(NetworkResponseEvent { url, method: req_method, @@ -402,15 +408,261 @@ 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") - || url.contains("labs.google") - || url.contains("recaptcha") +/// Extracts the primary Google Flow host name from [`FLOW_URL`]. +fn flow_host() -> &'static str { + FLOW_URL + .split("://") + .nth(1) + .and_then(|rest| rest.split(['/', '?', '#', ':']).next()) + .filter(|host| !host.is_empty()) + .unwrap_or("flow.google.com") } -/// Fetches and truncates the response body of a failed CDP HTTP request to 500 characters. -async fn fetch_error_excerpt(transport: &CdpTransport, request_id: &str) -> Option { +/// Returns `true` when `url` belongs to a Google Flow host. +fn is_flow_api_host(url: &str) -> bool { + let lower = url.to_ascii_lowercase(); + lower.contains(&flow_host().to_ascii_lowercase()) + || lower.contains("aisandbox-pa.googleapis.com") + || lower.contains("labs.google") +} + +/// Returns `true` when an active subscriber needs the body of this CDP HTTP response. +fn should_inspect_response_body(method: &str, status: u16, url: &str) -> bool { + method.eq_ignore_ascii_case("POST") + && is_flow_api_host(url) + && ((status >= 400 && is_generation_rpc_url(url)) + || (status == 200 && has_generation_batchexecute_rpc(url))) +} + +/// Truncates non-empty error text to at most 500 characters. +fn truncate_excerpt(text: &str) -> Option { + let excerpt: String = text.trim().chars().take(500).collect(); + let trimmed = excerpt.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_string()) +} + +/// Reads 1-based protobuf `field` from a JSPB array with a message ID at index `0` (`Wa` offset). +fn jspb_msg_field(frame: &[Value], field: usize) -> Option<&Value> { + let last_idx = frame.len().checked_sub(1)?; + if last_idx < 1 || field == 0 { + return None; + } + let val = if field >= last_idx { + let last = &frame[last_idx]; + if let Value::Object(map) = last { + map.get(&field.to_string())? + } else if field == last_idx { + last + } else { + return None; + } + } else { + &frame[field] + }; + (!val.is_null()).then_some(val) +} + +/// Reads 1-based protobuf `field` from a JSPB submessage array without a message ID. +fn jspb_submsg_field(arr: &[Value], field: usize) -> Option<&Value> { + if arr.is_empty() || field == 0 { + return None; + } + let idx = field - 1; + let last_idx = arr.len() - 1; + let val = if idx >= last_idx { + let last = &arr[last_idx]; + if let Value::Object(map) = last { + map.get(&field.to_string())? + } else if idx == last_idx { + last + } else { + return None; + } + } else { + &arr[idx] + }; + (!val.is_null()).then_some(val) +} + +/// Extracts the first readable non-type-URL string inside a nested error payload. +fn first_detail_text(val: &Value) -> Option { + match val { + Value::String(s) => { + let trimmed = s.trim(); + (!trimmed.is_empty() && !trimmed.starts_with("type.googleapis.com/")) + .then(|| trimmed.to_string()) + } + Value::Array(items) => items.iter().find_map(first_detail_text), + Value::Object(map) => ["message", "reason", "detail", "error"] + .into_iter() + .find_map(|k| map.get(k).and_then(first_detail_text)) + .or_else(|| map.values().find_map(first_detail_text)), + _ => None, + } +} + +/// Formats a `wrb.fr` frame when `Yp` (`[2, 9, 10]`) is empty and field 5 holds a `google.rpc.Status` array. +fn format_wrb_error(frame: &[Value], rpc_id: Option<&str>) -> Option { + let status_arr = jspb_msg_field(frame, 5)?.as_array()?; + let code = jspb_submsg_field(status_arr, 1).and_then(Value::as_i64); + let direct_msg = jspb_submsg_field(status_arr, 2) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string); + let detail_msg = + direct_msg.or_else(|| jspb_submsg_field(status_arr, 3).and_then(first_detail_text)); + if code.unwrap_or(0) == 0 && detail_msg.is_none() { + return None; + } + let code_str = code.filter(|c| *c != 0).map(|c| c.to_string()); + let prefix = match (rpc_id, code_str.as_deref()) { + (Some(id), Some(c)) => format!("wrb.fr {id} error {c}"), + (Some(id), None) => format!("wrb.fr {id} error"), + (None, Some(c)) => format!("wrb.fr error {c}"), + (None, None) => "wrb.fr error".to_string(), + }; + Some(match detail_msg { + Some(msg) => format!("{prefix}: {msg}"), + None => prefix, + }) +} + +/// Formats one `er` (`DA`) batch executor error frame into a summary string. +fn format_er_error(frame: &[Value]) -> String { + let mut parts: Vec = Vec::new(); + for field in [2usize, 4, 9] { + if let Some(val) = jspb_msg_field(frame, field) { + let piece = val + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .or_else(|| val.as_i64().map(|n| n.to_string())); + if let Some(text) = piece + && !parts.contains(&text) + { + parts.push(text); + } + } + } + if let Some(detail) = jspb_msg_field(frame, 10).and_then(first_detail_text) + && !parts.contains(&detail) + { + parts.push(detail); + } + if parts.is_empty() { + "er".to_string() + } else { + format!("er: {}", parts.join(" ")) + } +} + +/// Accumulates RPC-specific and batch-level errors while scanning `batchexecute` chunks. +struct EnvelopeScanState { + /// Restricts `wrb.fr` errors to `BATCH_GENERATION_RPC_IDS` when true. + only_generation_rpcs: bool, + /// True once a generation RPC `wrb.fr` frame carries a response payload in `[2, 9, 10]`. + saw_generation_data: bool, + /// Matched `wrb.fr` RPC errors. + rpc_errors: Vec, + /// Unattributed `wrb.fr` or `er` batch executor errors. + batch_errors: Vec, +} + +/// Collects `wrb.fr` and `er` frames from one parsed `batchexecute` JSON value. +fn collect_envelope_errors(val: &Value, state: &mut EnvelopeScanState) { + let Some(arr) = val.as_array() else { + return; + }; + match arr.first().and_then(Value::as_str) { + Some("wrb.fr") => { + let rpc_id = jspb_msg_field(arr, 1) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()); + let has_data = [2usize, 9, 10] + .into_iter() + .any(|field| jspb_msg_field(arr, field).is_some()); + if has_data { + if rpc_id.is_some_and(is_generation_rpc_id) { + state.saw_generation_data = true; + } + return; + } + let Some(err) = format_wrb_error(arr, rpc_id) else { + return; + }; + match rpc_id { + Some(id) if !state.only_generation_rpcs || is_generation_rpc_id(id) => { + state.rpc_errors.push(err); + } + Some(_) => {} + None => state.batch_errors.push(err), + } + } + Some("er") => state.batch_errors.push(format_er_error(arr)), + Some(_) => {} + None => { + for item in arr { + collect_envelope_errors(item, state); + } + } + } +} + +/// Parses a Google `batchexecute` response body for `wrb.fr` or `er` errors. +fn parse_batchexecute_error(text: &str, only_generation_rpcs: bool) -> Option { + let trimmed = text.trim_start(); + let mut rest = trimmed.strip_prefix(")]}'").unwrap_or(trimmed); + let mut state = EnvelopeScanState { + only_generation_rpcs, + saw_generation_data: false, + rpc_errors: Vec::new(), + batch_errors: Vec::new(), + }; + while !rest.is_empty() { + rest = rest.trim_start(); + if rest.is_empty() { + break; + } + if rest.as_bytes().first().is_some_and(u8::is_ascii_digit) { + let line_end = rest.find('\n').map_or(rest.len(), |i| i + 1); + let digits = rest[..line_end].trim(); + if digits.bytes().all(|b| b.is_ascii_digit()) { + rest = &rest[line_end..]; + continue; + } + } + if rest.starts_with('[') { + let mut stream = serde_json::Deserializer::from_str(rest).into_iter::(); + if let Some(Ok(parsed)) = stream.next() { + collect_envelope_errors(&parsed, &mut state); + let consumed = stream.byte_offset(); + if consumed > 0 { + rest = &rest[consumed..]; + continue; + } + } + } + rest = match rest.find('\n') { + Some(pos) => &rest[pos + 1..], + None => "", + }; + } + let mut errors = state.rpc_errors; + if !only_generation_rpcs || !state.saw_generation_data { + errors.extend(state.batch_errors); + } + (!errors.is_empty()).then(|| errors.join("; ")) +} + +/// Fetches and truncates the error excerpt of a failed HTTP or `batchexecute` CDP response to 500 characters. +async fn fetch_error_excerpt( + transport: &CdpTransport, + request_id: &str, + status: u16, +) -> Option { let val = transport .call( "Network.getResponseBody", @@ -432,9 +684,14 @@ async fn fetch_error_excerpt(transport: &CdpTransport, request_id: &str) -> Opti } else { raw_body.to_string() }; - let excerpt = text.chars().take(500).collect::(); - let trimmed = excerpt.trim(); - (!trimmed.is_empty()).then(|| trimmed.to_string()) + if status == 200 { + let rpc_err = parse_batchexecute_error(&text, true)?; + truncate_excerpt(&rpc_err) + } else if let Some(rpc_err) = parse_batchexecute_error(&text, false) { + truncate_excerpt(&rpc_err) + } else { + truncate_excerpt(&text) + } } /// Returns the shared HTTP client for local Chrome CDP endpoint discovery. diff --git a/src/characters.rs b/src/characters.rs index 12c6de2..d1ec45b 100644 --- a/src/characters.rs +++ b/src/characters.rs @@ -761,21 +761,9 @@ pub(crate) async fn create_or_update_character_job( id: media_id.clone().unwrap_or_else(|| char_id.clone()), name: persisted_name.clone(), kind: "image".to_string(), - prompt: None, url: src, - collection_id: None, - collection_name: None, - width: None, - height: None, - duration: None, primary_media_id: media_id, - personality_notes: None, - voice: None, - trim_start_seconds: None, - trim_end_seconds: None, - media_status: None, - media_error: None, - created_at: None, + ..FlowAsset::default() }; if let Ok(rec) = download_resolved_asset( engine, diff --git a/src/engine.rs b/src/engine.rs index 110a532..8196c7f 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -44,7 +44,7 @@ pub(crate) struct NetworkResponseEvent { pub(crate) method: String, /// HTTP response status code. pub(crate) status: u16, - /// Optional truncated response body returned on HTTP error responses. + /// Optional truncated error text from an HTTP error or failed `batchexecute` response. pub(crate) error_excerpt: Option, } diff --git a/src/generation.rs b/src/generation.rs index b9f3f55..6703d24 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, transformation, 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 existing tile baseline watched for in-place edit updates or failures. + 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. @@ -259,19 +259,47 @@ fn format_submit_progress(prefix: &str, submit_res: &serde_json::Value) -> Strin ) } +/// Returns `true` when `rpc_id` is a tracked generation, transformation, or upload RPC ID. +pub(crate) fn is_generation_rpc_id(rpc_id: &str) -> bool { + BATCH_GENERATION_RPC_IDS.contains(&rpc_id.trim()) +} + +/// Returns `true` when `url` is a `batchexecute` endpoint whose `rpcids` parameter includes a generation RPC ID. +pub(crate) fn has_generation_batchexecute_rpc(url: &str) -> bool { + let without_fragment = url.split('#').next().unwrap_or(url); + let Some((path, query)) = without_fragment.split_once('?') else { + return false; + }; + if !path.ends_with("/batchexecute") { + return false; + } + for pair in query.split('&') { + let Some((key, val)) = pair.split_once('=') else { + continue; + }; + if key != "rpcids" { + continue; + } + let normalized = val.replace("%2C", ",").replace("%2c", ","); + if normalized.split(',').any(is_generation_rpc_id) { + return true; + } + } + false +} + /// Returns `true` when `url` matches a Flow generation API endpoint. -fn is_generation_rpc_url(url: &str) -> bool { +pub(crate) fn is_generation_rpc_url(url: &str) -> bool { url.contains("aisandbox-pa.googleapis.com") || url.contains("FlowCreationAgentService") || url.contains("flowMedia") || url.contains("batchGenerate") || url.contains("AsyncGenerate") || url.contains("VideoFx") - || (url.contains("batchexecute") - && BATCH_GENERATION_RPC_IDS.iter().any(|id| url.contains(id))) + || has_generation_batchexecute_rpc(url) } -/// Drains CDP network events to surface API HTTP errors, reCAPTCHA blocks, or request acceptance. +/// Drains CDP network events to surface API HTTP or RPC errors, reCAPTCHA blocks, or request acceptance. pub(crate) fn inspect_generation_network( net_rx: &mut broadcast::Receiver, on_progress: &ProgressCallback, @@ -289,7 +317,7 @@ pub(crate) fn inspect_generation_network( ); } if ev.method.eq_ignore_ascii_case("POST") && is_generation_rpc_url(&ev.url) { - if ev.status >= 400 { + if ev.status >= 400 || ev.error_excerpt.is_some() { let excerpt = ev.error_excerpt.as_deref().unwrap_or("no error body"); if excerpt.to_ascii_lowercase().contains("recaptcha") || ev.url.to_ascii_lowercase().contains("recaptcha") @@ -301,8 +329,16 @@ pub(crate) fn inspect_generation_network( excerpt ); } + if ev.status >= 400 { + anyhow::bail!( + "Flow generation API returned HTTP {} ({}): {}", + ev.status, + ev.url, + excerpt + ); + } anyhow::bail!( - "Flow generation API returned HTTP {} ({}): {}", + "Flow generation API returned RPC error (HTTP {} {}): {}", ev.status, ev.url, excerpt @@ -335,6 +371,7 @@ async fn wait_for_new_assets( let mut accepted_status: Option = None; let mut last_pending_count = 0usize; let mut last_pending_info = String::from("none"); + let mut watch_baseline: Option = spec.watch_updated.cloned(); while Instant::now() < deadline { tokio::time::sleep(Duration::from_secs(3)).await; @@ -363,15 +400,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 +424,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 +443,12 @@ 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.primary_ready != Some(true) + && a.media_status.is_none() + && !a.failed_history.is_empty()) + }) { let first = new_tiles[0]; anyhow::bail!( @@ -417,23 +457,40 @@ async fn wait_for_new_assets( first .media_error .as_deref() - .unwrap_or(first.media_status.as_deref().unwrap_or("failed")) + .or_else(|| first.latest_failure_detail()) + .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) = watch_baseline.as_mut() + && let Some(watched) = snap.assets.iter().find(|a| a.id == prev.id) { - anyhow::bail!( - "Flow edit failed on {}: {}", - tid, - watched - .media_error - .as_deref() - .unwrap_or(watched.media_status.as_deref().unwrap_or("failed")) - ); + let prev_primary_failed = prev.primary_ready != Some(true) + && (matches!(prev.media_status.as_deref(), Some("failed" | "canceled")) + || prev.media_error.is_some()); + let cur_primary_failed = watched.primary_ready != Some(true) + && (matches!(watched.media_status.as_deref(), Some("failed" | "canceled")) + || watched.media_error.is_some()); + if !cur_primary_failed && prev_primary_failed { + prev.media_status = watched.media_status.clone(); + prev.media_error = None; + prev.primary_ready = watched.primary_ready; + } + if watched.failed_history.len() < prev.failed_history.len() { + prev.failed_history = watched.failed_history.clone(); + } + let new_hist_err = watched.new_failure(&prev.failed_history); + let primary_failed = cur_primary_failed + && (!prev_primary_failed + || watched.primary_media_id != prev.primary_media_id + || watched.media_error != prev.media_error); + if new_hist_err.is_some() || primary_failed { + let detail = new_hist_err + .or(watched.media_error.as_deref()) + .or(watched.media_status.as_deref()) + .unwrap_or("failed"); + anyhow::bail!("Flow edit failed on {}: {}", prev.id, detail); + } } } @@ -700,11 +757,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..1d08bb3 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -33,6 +33,10 @@ struct ClipBaseline { media_status: Option, /// Media error recorded before extension submission, cleared if a failed clip restarts. media_error: Option, + /// True when the primary media item was ready before extension submission. + primary_ready: Option, + /// Ordered markers of failed or canceled history items recorded before extension submission. + failed_history: Vec, } impl ClipBaseline { @@ -43,6 +47,8 @@ impl ClipBaseline { url: asset.url.clone(), media_status: asset.media_status.clone(), media_error: asset.media_error.clone(), + primary_ready: asset.primary_ready, + failed_history: asset.failed_history.clone(), } } @@ -116,10 +122,11 @@ async fn confirm_trimmed_video( ) } -/// Returns `true` when `asset` currently holds a failed or canceled media state. +/// Returns `true` when `asset` currently holds a failed or canceled media or history state. fn clip_is_failed(asset: &FlowAsset) -> bool { matches!(asset.media_status.as_deref(), Some("failed" | "canceled")) || asset.media_error.is_some() + || !asset.failed_history.is_empty() } /// Returns `true` when `asset` is a video tile or clip that entered an error state since `before`. @@ -128,9 +135,28 @@ fn clip_entered_error(asset: &FlowAsset, before: &HashMap) return false; } match before.get(&asset.id) { - None => true, + None => { + matches!(asset.media_status.as_deref(), Some("failed" | "canceled")) + || asset.media_error.is_some() + || (asset.primary_ready != Some(true) + && asset.media_status.is_none() + && !asset.failed_history.is_empty()) + } Some(prior) => { + if asset.new_failure(&prior.failed_history).is_some() { + return true; + } + if asset.primary_ready == Some(true) { + return false; + } + let primary_failed = + matches!(asset.media_status.as_deref(), Some("failed" | "canceled")) + || asset.media_error.is_some(); + if !primary_failed { + return false; + } !prior.was_failed() + || prior.primary_ready == Some(true) || asset.primary_media_id != prior.primary_media_id || asset.media_error != prior.media_error } @@ -382,12 +408,16 @@ pub(crate) async fn run_video_extend( if let Ok(cur_snap) = list_assets_with_project(engine).await { for asset in &cur_snap.assets { if asset.kind == "video" - && !clip_is_failed(asset) && let Some(prior) = before.get_mut(&asset.id) - && prior.was_failed() { - prior.media_status = asset.media_status.clone(); - prior.media_error = None; + if !clip_is_failed(asset) && prior.was_failed() { + prior.media_status = asset.media_status.clone(); + prior.media_error = None; + prior.primary_ready = asset.primary_ready; + prior.failed_history.clear(); + } else if asset.failed_history.len() < prior.failed_history.len() { + prior.failed_history = asset.failed_history.clone(); + } } } if let Some(failed_tile) = cur_snap @@ -395,14 +425,17 @@ pub(crate) async fn run_video_extend( .iter() .find(|a| clip_entered_error(a, &before)) { + let detail = before + .get(&failed_tile.id) + .and_then(|prior| failed_tile.new_failure(&prior.failed_history)) + .or(failed_tile.media_error.as_deref()) + .or_else(|| failed_tile.latest_failure_detail()) + .or(failed_tile.media_status.as_deref()) + .unwrap_or("failed"); extend_err = Some(anyhow::anyhow!( "Flow video extend failed on tile {}: {}", failed_tile.id, - failed_tile - .media_error - .as_deref() - .or(failed_tile.media_status.as_deref()) - .unwrap_or("failed") + detail )); break; } diff --git a/ts/read_store_snapshot.ts b/ts/read_store_snapshot.ts index ff0c6fb..7791330 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, createdIso, fifeEnv as getFifeEnv, @@ -265,6 +266,71 @@ export function readStoreTiles(tileMap: Map): { } }; + const markerKey = (marker: string): string => { + const sep = marker.indexOf("|"); + return sep >= 0 ? marker.slice(0, sep) : marker; + }; + + const markerHasError = (marker: string): boolean => { + const first = marker.indexOf("|"); + if (first < 0) return false; + const second = marker.indexOf("|", first + 1); + return second >= 0 && second + 1 < marker.length; + }; + + const mergeFailedHistory = (base: string[], next: string[]): string[] => { + if (next.length === 0) return base; + if (base.length === 0) return [...next]; + const merged = [...base]; + const keyIndex = new Map(); + for (let i = 0; i < merged.length; i++) { + keyIndex.set(markerKey(merged[i]), i); + } + for (const item of next) { + const key = markerKey(item); + const existingIdx = keyIndex.get(key); + if (existingIdx === undefined) { + keyIndex.set(key, merged.length); + merged.push(item); + } else if (!markerHasError(merged[existingIdx]) && markerHasError(item)) { + merged[existingIdx] = item; + } + } + return merged; + }; + + const summarizeHistoryFailures = ( + items: readonly (FlowMediaPayload | null | undefined)[] | undefined, + ): string[] => { + if (!Array.isArray(items) || items.length === 0) { + return []; + } + const failedHistory: string[] = []; + const idCounts = new Map(); + let anonIndex = 0; + for (const rawItem of items) { + if (!rawItem || typeof rawItem !== "object") continue; + const item = legacyMedia(rawItem); + const status = String(item?.Zc ?? "").toLowerCase(); + const error = formatMediaError(item?.nf); + if (status === "failed" || status === "canceled" || error) { + const normStatus = status === "canceled" ? "canceled" : "failed"; + const itemId = cleanMediaId(String(item?.id ?? item?.mediaId ?? "")); + let key: string; + if (itemId) { + const occ = idCounts.get(itemId) ?? 0; + idCounts.set(itemId, occ + 1); + key = occ === 0 ? `id:${itemId}` : `id:${itemId}#${occ}`; + } else { + key = `anon:${anonIndex}`; + anonIndex += 1; + } + failedHistory.push(`${key}|${normStatus}|${error ?? ""}`); + } + } + return failedHistory; + }; + const collectionIds = new Set(); for (const [id, rawTile] of tileMap.entries()) { if (String(rawTile?.type ?? "").toUpperCase() === collectionType) { @@ -325,13 +391,16 @@ export function readStoreTiles(tileMap: Map): { 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 primaryStatus = String(t.Fb?.Zc ?? t.fb?.Zc ?? t.Zc ?? "").toLowerCase(); + const primaryError = formatMediaError(t.Fb?.nf ?? t.fb?.nf ?? t.nf); + const primaryFailed = + primaryStatus === "failed" || + primaryStatus === "canceled" || + Boolean(primaryError); const mediaNotReady = - mediaStatus === "pending" || - mediaStatus === "scheduled" || - mediaStatus === "failed" || - mediaStatus === "canceled" || + primaryStatus === "pending" || + primaryStatus === "scheduled" || + primaryFailed || Boolean(t.Fb?.nf || t.fb?.nf || t.nf); const primaryMediaId = @@ -352,10 +421,23 @@ export function readStoreTiles(tileMap: Map): { : baseKind; const cachedMediaUrl = asHttpOrDataUrl(cachedEntry?.url); + const primaryHistItem = + primaryMediaId && Array.isArray(t.history) + ? legacyMedia( + t.history.find( + (item) => + item && + cleanMediaId(String(item.id ?? item.mediaId ?? "")) === + cleanMediaId(String(primaryMediaId)), + ), + ) + : undefined; const tileMediaUrl = baseKind === "character" && charLookPrimaryMediaId ? charFallbackUrl : videoMediaUrl || + (baseKind === "video" ? readMediaUrl(primaryHistItem, true) : null) || readMediaUrl(t.Fb) || + readMediaUrl(primaryHistItem) || readMediaUrl(t) || readMediaUrl(t.fb) || charFallbackUrl || @@ -366,6 +448,10 @@ export function readStoreTiles(tileMap: Map): { ? cachedMediaUrl : tileMediaUrl || cachedMediaUrl || null; const mediaUrl = mediaNotReady ? null : rawMediaUrl; + const primaryReady = !mediaNotReady && Boolean(primaryMediaId || rawMediaUrl); + const failedHistory = summarizeHistoryFailures(t.history); + const mediaStatus = primaryStatus || null; + const mediaError = primaryError; const bio = (ttype === "CHARACTER" ? characterPersonalityNotes(t) : null) ?? @@ -409,8 +495,10 @@ export function readStoreTiles(tileMap: Map): { voice: voiceRaw != null ? voiceRaw : null, trim_start_seconds: trimStart, trim_end_seconds: trimEnd, - media_status: mediaStatus || null, + media_status: mediaStatus, media_error: mediaError, + primary_ready: primaryReady, + failed_history: failedHistory, width: typeof t.width === "number" ? t.width @@ -457,22 +545,42 @@ export function readStoreTiles(tileMap: Map): { const candidates: Array< [string, SceneClipItem | null, FlowMediaPayload | null] > = []; + const seenWorkflows = new Set(); for (const clip of clips) { const wfId = clip?.workflowId ? String(clip.workflowId) : null; - if (!wfId) continue; + if (!wfId || seenWorkflows.has(wfId)) continue; + seenWorkflows.add(wfId); const hist = history.get(wfId); const primaryId = clip?.primaryMediaId - ? String(clip.primaryMediaId) + ? cleanMediaId(String(clip.primaryMediaId)) : null; const mObj = Array.isArray(hist) - ? hist.find((x) => x && String(x.id || "") === primaryId) || + ? hist.find( + (x) => + x && + primaryId !== null && + cleanMediaId(String(x.id ?? x.mediaId ?? "")) === primaryId, + ) || + hist.find( + (x) => + x && String(legacyMedia(x)?.Zc ?? "").toLowerCase() === "success", + ) || hist[0] || null : null; candidates.push([wfId, clip, mObj]); } for (const [wfId, hist] of history) { - const mObj = Array.isArray(hist) ? hist[0] || null : null; + if (!wfId || seenWorkflows.has(wfId)) continue; + seenWorkflows.add(wfId); + const mObj = Array.isArray(hist) + ? hist.find( + (x) => + x && String(legacyMedia(x)?.Zc ?? "").toLowerCase() === "success", + ) || + hist[0] || + null + : null; candidates.push([wfId, null, mObj]); } @@ -480,19 +588,32 @@ export function readStoreTiles(tileMap: Map): { if (!wfId) continue; const mObj = legacyMedia(rawMedia); const cObj = legacyMedia(clip as FlowMediaPayload | null); - const mStatus = String( + const mPrimaryStatus = String( mObj?.Zc ?? cObj?.Zc ?? clip?.Zc ?? "", ).toLowerCase(); - const mError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const mPrimaryError = formatMediaError(mObj?.nf ?? cObj?.nf ?? clip?.nf); + const mPrimaryFailed = + mPrimaryStatus === "failed" || + mPrimaryStatus === "canceled" || + Boolean(mPrimaryError); + const candFailedHistory = summarizeHistoryFailures(history.get(wfId)); + const clipPrimaryMediaId = clip?.primaryMediaId + ? String(clip.primaryMediaId) + : mObj?.id + ? String(mObj.id) + : mObj?.mediaId + ? String(mObj.mediaId) + : null; + const mStatus = mPrimaryStatus || null; + const mError = mPrimaryError; const existing = byId.get(wfId); if (existing) { - if (mStatus === "failed" || mStatus === "canceled" || mError) { - if ( - existing.media_status !== "failed" && - existing.media_status !== "canceled" - ) { - existing.media_status = mStatus || existing.media_status; - } + existing.failed_history = mergeFailedHistory( + existing.failed_history ?? [], + candFailedHistory, + ); + if (mPrimaryFailed && !existing.primary_ready && !existing.media_status) { + existing.media_status = mStatus; if (!existing.media_error && mError) { existing.media_error = mError; } @@ -500,16 +621,10 @@ export function readStoreTiles(tileMap: Map): { continue; } const mNotReady = - mStatus === "pending" || - mStatus === "scheduled" || - mStatus === "failed" || - mStatus === "canceled" || + mPrimaryStatus === "pending" || + mPrimaryStatus === "scheduled" || + mPrimaryFailed || Boolean(mObj?.nf || cObj?.nf || clip?.nf); - const clipPrimaryMediaId = clip?.primaryMediaId - ? String(clip.primaryMediaId) - : mObj?.id - ? String(mObj.id) - : null; const cachedClipVideoUrl = clipPrimaryMediaId ? asHttpOrDataUrl( runtimeState.mediaInfoCache.get(clipPrimaryMediaId)?.url, @@ -527,6 +642,8 @@ export function readStoreTiles(tileMap: Map): { ? cachedClipVideoUrl : tileClipUrl || cachedClipVideoUrl || null; const clipUrl = mNotReady ? null : rawClipUrl; + const clipPrimaryReady = + !mNotReady && Boolean(clipPrimaryMediaId || rawClipUrl); const trimFormat = snapshotFormat()?.trim; const readClip = (key: string | undefined): number | null => { const value = key ? (clip as Record | undefined)?.[key] : undefined; @@ -583,8 +700,10 @@ export function readStoreTiles(tileMap: Map): { voice: null, trim_start_seconds: trimStartVal, trim_end_seconds: trimEndVal, - media_status: mStatus || null, + media_status: mStatus, media_error: mError, + primary_ready: clipPrimaryReady, + failed_history: candFailedHistory, width: typeof mObj?.width === "number" ? mObj.width diff --git a/ts/scene_tiles.ts b/ts/scene_tiles.ts index df2b2b4..4c04517 100644 --- a/ts/scene_tiles.ts +++ b/ts/scene_tiles.ts @@ -7,16 +7,38 @@ import { readOwn } from "./angular"; import { frontendBuild, readBuildLabel } from "./frontend_builds"; import type { FlowMediaPayload, FlowTile, SceneClipItem } from "./types"; +/** Returns true when `v` is a workflow history map or plain lookup object. */ +function isHistoryLookup( + v: unknown, +): v is Map | Record { + return ( + v instanceof Map || + (Boolean(v) && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date)) + ); +} + +/** Extracts the workflow media array from a history map entry value. */ +function toHistoryArray(val: unknown): FlowMediaPayload[] { + if (Array.isArray(val)) return val as FlowMediaPayload[]; + const nested = readOwn(val, "history"); + return Array.isArray(nested) ? (nested as FlowMediaPayload[]) : []; +} + /** Returns the clip list and history of a scene in the active build. */ export function sceneContents(tile: FlowTile) { const format = frontendBuild(readBuildLabel())?.projectStore.scene; - const clips = (format && readOwn(tile, format.clips)) ?? tile.Oc; - const history = (format && readOwn(tile, format.history)) ?? tile.Yf; - const entries: Iterable<[string, FlowMediaPayload[]]> = history instanceof Map - ? history.entries() - : history && typeof history === "object" ? Object.entries(history) : []; + const clips = [format && readOwn(tile, format.clips), tile.Oc].find(Array.isArray); + const history = [format && readOwn(tile, format.history), tile.Yf].find(isHistoryLookup); + const entries: Iterable<[unknown, unknown]> = + history instanceof Map + ? history.entries() + : history + ? Object.entries(history) + : []; return { - clips: Array.isArray(clips) ? clips as SceneClipItem[] : [], - history: new Map(Array.from(entries, ([id, media]) => [String(id), media])), + clips: clips ? (clips as SceneClipItem[]) : [], + history: new Map( + Array.from(entries, ([id, media]) => [String(id), toHistoryArray(media)]), + ), }; } diff --git a/ts/types.ts b/ts/types.ts index 6e1c59b..f63962b 100644 --- a/ts/types.ts +++ b/ts/types.ts @@ -252,6 +252,8 @@ export interface FlowTile extends FlowMediaPayload { trimEndSeconds?: number; /** Creation time alias. */ createTime?: string; + /** Workflow media generation history entries on an image or video tile. */ + history?: FlowMediaPayload[]; /** Scene clip array. */ Oc?: SceneClipItem[]; /** Scene clip workflow history lookup. */ @@ -552,6 +554,10 @@ export interface SnapshotAssetItem { media_status: string | null; /** Failure description when present. */ media_error: string | null; + /** True when the primary media item succeeded and is eligible for URL resolution. */ + primary_ready?: boolean; + /** Ordered identifiers of failed or canceled workflow history items. */ + failed_history?: string[]; /** Media width in pixels. */ width: number | null; /** Media height in pixels. */