diff --git a/src/scenes.rs b/src/scenes.rs index 4969fcc..e5f512d 100644 --- a/src/scenes.rs +++ b/src/scenes.rs @@ -15,7 +15,7 @@ use crate::assets::{ rename_assets, resolve_asset, trash_asset, }; use crate::db::FlowDb; -use crate::engine::ChromeEngine; +use crate::engine::{ChromeEngine, checked_runtime_result}; use crate::generation::{collect_created_assets, inspect_generation_network}; use crate::project::{ ensure_flow_store, ensure_project_workspace_root, project_id_from_url, project_workspace_url, @@ -170,6 +170,32 @@ pub(crate) struct VideoParams { pub(crate) scene_id: Option, } +/// Formats a failed browser `sceneOp` result while keeping structured diagnostic fields. +fn runtime_scene_error(res: Value) -> anyhow::Error { + match checked_runtime_result(res) { + Ok(_) => anyhow::anyhow!("unknown"), + Err(err) => err, + } +} + +/// Returns `true` when `call_flow_async` failed after the CDP evaluation request left for the page. +fn write_could_have_happened(error: &anyhow::Error) -> bool { + let message = error.to_string(); + if message.starts_with("JavaScript error") + || message.starts_with("Timed out waiting for CDP command Runtime.evaluate") + || message.starts_with("Chrome CDP closed during Runtime.evaluate") + || message == "Chrome CDP connection closed" + { + return true; + } + if let Some(cdp_err) = message.strip_prefix("Chrome CDP error:") { + let detail = cdp_err.trim(); + return !detail.starts_with("Cannot find default execution context") + && !detail.starts_with("Cannot find context with specified id"); + } + false +} + /// Dispatches `flow_scenes` actions (`list`, `create`, `add_clips`, `rename`, `trash`). pub(crate) async fn handle_scenes( engine: &ChromeEngine, @@ -198,13 +224,9 @@ pub(crate) async fn handle_scenes( "name": req.name, }); let res = engine.call_flow_async("sceneOp", json!([payload])).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to create scene: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + if res.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(res); + anyhow::bail!("Failed to create scene: {err:#}"); } Ok(res) } @@ -214,21 +236,40 @@ pub(crate) async fn handle_scenes( .asset_ids .filter(|v| !v.is_empty()) .context("flow_scenes add_clips requires non-empty 'asset_ids'")?; - let _ = read_snapshot(engine).await?; + let snap = read_snapshot(engine).await?; + let project_id = snap.get("projectId").and_then(Value::as_str); + let prepare = json!({ + "action": "prepare_add_clips", + "scene_id": scene_id, + "asset_ids": asset_ids, + }); + let prepared = engine.call_flow_async("sceneOp", json!([prepare])).await?; + if prepared.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(prepared); + anyhow::bail!("Failed to add clips to scene: {err:#}"); + } + anyhow::ensure!(engine.has_page().await, "Chrome CDP connection closed"); let payload = json!({ "action": "add_clips", "scene_id": scene_id, "asset_ids": asset_ids, "position": req.position, }); - let res = engine.call_flow_async("sceneOp", json!([payload])).await?; - if res.get("ok").and_then(|v| v.as_bool()) != Some(true) { - anyhow::bail!( - "Failed to add clips to scene: {}", - res.get("error") - .and_then(|v| v.as_str()) - .unwrap_or("unknown") - ); + let res = match engine.call_flow_async("sceneOp", json!([payload])).await { + Ok(res) => res, + Err(error) if write_could_have_happened(&error) => match project_id { + Some(pid) => anyhow::bail!( + "outcome_unknown (project {pid}, scene {scene_id} add_clips): {error:#}" + ), + None => { + anyhow::bail!("outcome_unknown (scene {scene_id} add_clips): {error:#}") + } + }, + Err(error) => return Err(error), + }; + if res.get("ok").and_then(Value::as_bool) != Some(true) { + let err = runtime_scene_error(res); + anyhow::bail!("Failed to add clips to scene: {err:#}"); } Ok(res) } diff --git a/ts/project_store.ts b/ts/project_store.ts index 671857e..983195b 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -52,6 +52,8 @@ let boundStore: ProjectStore | null = null; let boundHandle: FlowStoreHandle | null = null; /** Promise chain that serializes general store mutations in this document. */ let mutationChain: Promise = Promise.resolve(); +/** Per-payload gates that unblock `mutationChain` when the server confirms a mutation early. */ +const mutationGates = new WeakMap, Promise>(); /** Returns the project ID in the current route. */ export function projectInRoute(): string | null { @@ -283,8 +285,12 @@ async function dispatchStoreMutation( /** Serializes general store mutations in the current page session. */ function mutateStore(store: ProjectStore, payload: Record): Promise { - const run = mutationChain.then(() => dispatchStoreMutation(store, payload)); - mutationChain = run.then(() => undefined, () => undefined); + const gate = mutationGates.get(payload); + mutationGates.delete(payload); + const prev = mutationChain; + const run = prev.then(() => dispatchStoreMutation(store, payload)); + const settled = run.then(() => undefined, () => undefined); + mutationChain = gate ? prev.then(() => Promise.race([settled, gate])) : settled; return run; } @@ -459,18 +465,50 @@ export async function refreshProjectStore(store: ProjectStore): Promise(); +/** True until all active project submissions settle or are confirmed by the server. */ export let projectMutationPending = false; /** Projects that need a new query result after a mutation. */ export const projectsToRefresh = new Set(); +/** Guard for one active project submission and its optional `mutationChain` gate. */ +export interface ProjectMutationGuard { + /** Marks this submission settled or confirmed and releases its gate. */ + readonly finish: () => void; + /** Binds this submission's gate to a `mutateStore` payload. */ + readonly attach: >(payload: T) => T; +} + +/** Marks one project submission as pending and returns its idempotent guard. */ +export function beginProjectMutation(): ProjectMutationGuard { + const token = Symbol("project_mutation"); + activeProjectMutations.add(token); + projectMutationPending = true; + let releaseGate: (() => void) | undefined; + const gate = new Promise((resolve) => { + releaseGate = resolve; + }); + return { + finish: () => { + if (!activeProjectMutations.delete(token)) return; + projectMutationPending = activeProjectMutations.size > 0; + releaseGate?.(); + }, + attach: >(payload: T): T => { + mutationGates.set(payload, gate); + return payload; + }, + }; +} + /** Sends one mutation and confirms it from a new server result. */ export async function mutateAndVerify( store: ProjectStore, payload: Record, verified: (tiles: Map) => boolean, ): Promise | null> { - projectMutationPending = true; + const mutation = beginProjectMutation(); projectsToRefresh.add(store.projectId); let timer: ReturnType | undefined; let timedOut = false; @@ -497,7 +535,7 @@ export async function mutateAndVerify( } catch { return null; } finally { - projectMutationPending = false; + mutation.finish(); } })(); try { @@ -507,19 +545,26 @@ export async function mutateAndVerify( } } -/** Refreshes the project before the next operation after an unknown result. */ -export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { +/** Fetches a new tile result from the server within the mutation time limit. */ +export async function fetchProjectStore( + store: ProjectStore, +): Promise | null> { let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(null), MUTATION_TIMEOUT_MS); }); try { - const tiles = await Promise.race([refreshProjectStore(store), timeout]); - if (tiles) projectsToRefresh.delete(store.projectId); - return tiles; + return await Promise.race([refreshProjectStore(store), timeout]); } catch { return null; } finally { clearTimeout(timer); } } + +/** Refreshes the project before the next operation after an unknown result. */ +export async function refreshAfterUnknown(store: ProjectStore): Promise | null> { + const tiles = await fetchProjectStore(store); + if (tiles) projectsToRefresh.delete(store.projectId); + return tiles; +} diff --git a/ts/scene_ops.ts b/ts/scene_ops.ts index fc47fbb..58c1cb7 100644 --- a/ts/scene_ops.ts +++ b/ts/scene_ops.ts @@ -4,16 +4,172 @@ // Create Google Flow scenes and append workflow clips via bound store state. import { createScene } from "./angular"; -import { delay } from "./dom"; -import { activeProjectStoreFormat } from "./frontend_builds"; +import { delay, findMediaContainer, isTrashedTile, legacyTile } from "./dom"; +import { activeProjectStoreFormat, readBuildLabel } from "./frontend_builds"; +import { + beginProjectMutation, + clearProjectStore, + currentProjectStore, + fetchProjectStore, + projectMutationPending, + projectsToRefresh, + refreshAfterUnknown, +} from "./project_store"; +import { sceneContents } from "./scene_tiles"; import { clearStore, runtimeState } from "./state"; -import type { FlowTile, SceneOpRequest } from "./types"; +import type { FlowTile, SceneClipItem, SceneOpRequest } from "./types"; + +/** Number of reads that confirm a scene change after the callback times out. */ +const SCENE_CONFIRM_ATTEMPTS = 8; +/** Time between two confirmation reads. */ +const SCENE_CONFIRM_INTERVAL_MS = 1_000; +/** Maximum time in milliseconds to wait for a scene clip addition callback. */ +const SCENE_ADD_CLIPS_TIMEOUT_MS = 10_000; + +/** Store errors thrown before a mutation leaves the browser. */ +const PRE_SUBMIT_ERRORS = new Set([ + "unsupported_front_end", + "project_store_changed", + "store_mutate_missing", +]); + +/** Recorded identifiers of one clip in a scene. */ +interface ClipIdentity { + /** Workflow identifier on the clip. */ + workflowId: string | null; + /** Primary media identifier on the clip. */ + primaryMediaId: string | null; +} + +/** Expected identifiers of one clip requested in `add_clips`. */ +interface ExpectedClip { + /** Source asset ID passed by the caller. */ + assetId: string; + /** Resolved workflow ID sent to Flow. */ + workflowId: string; + /** Source primary media ID when known. */ + primaryMediaId: string | null; +} + +/** Outcome of waiting for a submitted `add_clips` mutation and its callback. */ +type AddClipsWaitOutcome = + | { kind: "settled" } + | { kind: "timeout" } + | { kind: "rejected"; error: string; preSubmit: boolean }; + +/** Extracts the workflow and primary media IDs from a scene clip item. */ +function readClipIdentity(clip: SceneClipItem | undefined): ClipIdentity { + const wf = clip?.workflowId; + const media = clip?.primaryMediaId; + return { + workflowId: wf == null || wf === "" ? null : String(wf), + primaryMediaId: media == null || media === "" ? null : String(media), + }; +} + +/** Reads the primary media ID of a source project tile when present. */ +function sourcePrimaryMediaId(rawTile: FlowTile | undefined): string | null { + const tile = legacyTile(rawTile); + const raw = tile?.primaryMediaId ?? (rawTile ? findMediaContainer(rawTile)?.[1].id : undefined) ?? null; + return raw == null || raw === "" ? null : String(raw); +} + +/** Returns true when `tile` exists in the store and cannot act as a target scene. */ +function isInvalidSceneTile(tile: FlowTile | undefined): boolean { + return Boolean( + tile && + (isTrashedTile(tile) || + tile.isPending === true || + (typeof tile.type === "string" && tile.type.toUpperCase() !== "SCENE")), + ); +} + +/** Finds a live, non-trashed scene tile in `tiles` by ID. */ +function findLiveSceneTile( + tiles: Map | null | undefined, + sceneId: string, +): FlowTile | null { + if (!(tiles instanceof Map)) return null; + const candidate = tiles.get(sceneId); + if ( + candidate && + !isTrashedTile(candidate) && + !candidate.isPending && + String(candidate.type ?? "SCENE").toUpperCase() === "SCENE" + ) { + return candidate; + } + for (const [id, tile] of tiles.entries()) { + if ( + String(tile?.id ?? id) === sceneId && + !isTrashedTile(tile) && + !tile?.isPending && + String(tile?.type ?? "").toUpperCase() === "SCENE" + ) { + return tile; + } + } + return null; +} + +/** Returns true when `actual` matches a recorded pre-submission clip `prior`. */ +function clipMatchesPrior(actual: ClipIdentity, prior: ClipIdentity): boolean { + if (prior.workflowId !== null && actual.workflowId !== null) { + return actual.workflowId === prior.workflowId; + } + if (prior.workflowId !== null && actual.workflowId === prior.workflowId) { + return true; + } + return ( + prior.primaryMediaId !== null && + actual.primaryMediaId === prior.primaryMediaId + ); +} + +/** Returns true when `actual` matches a requested clip `expected`. */ +function clipMatchesExpected(actual: ClipIdentity, expected: ExpectedClip): boolean { + if ( + actual.workflowId !== null && + (actual.workflowId === expected.workflowId || + actual.workflowId === expected.assetId) + ) { + return true; + } + return ( + expected.primaryMediaId !== null && + actual.primaryMediaId === expected.primaryMediaId + ); +} + +/** Checks whether `afterScene` holds all `before` and `expected` clips in the intended order and count. */ +function sceneClipsConfirmed( + before: ClipIdentity[], + afterScene: FlowTile, + expected: ExpectedClip[], + position: number | null | undefined, +): boolean { + const after = sceneContents(afterScene).clips.map(readClipIdentity); + if (after.length !== before.length + expected.length) return false; + + const insertAt = + typeof position === "number" && Number.isFinite(position) + ? Math.max(0, Math.min(Math.trunc(position), before.length)) + : before.length; + return ( + before.slice(0, insertAt).every((b, i) => clipMatchesPrior(after[i], b)) && + expected.every((exp, i) => clipMatchesExpected(after[insertAt + i], exp)) && + before + .slice(insertAt) + .every((b, i) => clipMatchesPrior(after[insertAt + expected.length + i], b)) + ); +} /** Creates a scene or adds workflow clips to an existing scene. */ export async function sceneOp(req: SceneOpRequest): Promise { + const build = readBuildLabel(); if (!activeProjectStoreFormat()) { - clearStore(); - return { ok: false, error: "unsupported_front_end" }; + clearProjectStore(); + return { ok: false, error: "unsupported_front_end", build }; } const helper = runtimeState.store; if (!helper || !helper.isCurrent()) { @@ -24,16 +180,28 @@ export async function sceneOp(req: SceneOpRequest): Promise { return { ok: false, error: "store_loading" }; } const getMap = (): Map | null | undefined => helper.getTileMap(); - const tileMap = getMap(); + let tileMap = getMap(); if (!(tileMap instanceof Map) || !helper.mutate) { return { ok: false, error: "store_not_bound" }; } const action = String(req?.action || "").toLowerCase(); const resolveWfIds = (ids: string[]): string[] => - ids.map((id) => String(getMap()?.get(id)?.workflowId || id)); + ids.map((id) => String((tileMap ?? getMap())?.get(id)?.workflowId || id)); if (action === "create") { + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; + if (!refreshed) { + return { ok: false, error: "project_refresh_failed", project_id: projectId }; + } + tileMap = refreshed; + } const assetIds = Array.isArray(req?.asset_ids) ? req.asset_ids.map(String) : []; @@ -59,49 +227,256 @@ export async function sceneOp(req: SceneOpRequest): Promise { }; } + if (action === "prepare_add_clips") { + const sceneId = String(req?.scene_id || "").trim(); + const assetIds = Array.isArray(req?.asset_ids) + ? req.asset_ids.map((id) => String(id).trim()).filter(Boolean) + : []; + if (!sceneId || !assetIds.length) { + return { ok: false, error: "scene_id_and_asset_ids_required" }; + } + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; + if (!refreshed) { + return { ok: false, error: "project_refresh_failed", project_id: projectId }; + } + tileMap = refreshed; + } + if (isInvalidSceneTile(tileMap.get(sceneId))) { + return { ok: false, error: "scene_not_found", scene_id: sceneId }; + } + return { ok: true, project_id: projectId }; + } + if (action === "add_clips") { const sceneId = String(req?.scene_id || "").trim(); const assetIds = Array.isArray(req?.asset_ids) - ? req.asset_ids.map(String) + ? req.asset_ids.map((id) => String(id).trim()).filter(Boolean) : []; if (!sceneId || !assetIds.length) { return { ok: false, error: "scene_id_and_asset_ids_required" }; } + if (projectMutationPending) { + return { ok: false, error: "project_mutation_pending" }; + } + const projectId = helper.projectId; + const store = projectId ? currentProjectStore(projectId) : null; + const mutation = beginProjectMutation(); + let baseline: ReturnType[] | null; + let expectedClips: ExpectedClip[]; + try { + if (projectId && projectsToRefresh.has(projectId)) { + const refreshed = store ? await refreshAfterUnknown(store) : null; + if (!refreshed) { + mutation.finish(); + return { ok: false, error: "project_refresh_failed", project_id: projectId }; + } + tileMap = refreshed; + } + if (isInvalidSceneTile(tileMap.get(sceneId))) { + mutation.finish(); + return { ok: false, error: "scene_not_found", scene_id: sceneId }; + } + const beforeScene = findLiveSceneTile(tileMap, sceneId); + baseline = beforeScene + ? sceneContents(beforeScene).clips.map(readClipIdentity) + : null; + expectedClips = assetIds.map((assetId) => { + const rawSource = tileMap?.get(assetId); + return { + assetId, + workflowId: String(rawSource?.workflowId || assetId), + primaryMediaId: sourcePrimaryMediaId(rawSource), + }; + }); + } catch (err) { + mutation.finish(); + return { + ok: false, + error: err instanceof Error ? err.message : String(err ?? "project_refresh_failed"), + }; + } + const workflowIds = expectedClips.map((clip) => clip.workflowId); + let callbackErr: unknown = null; + let resolveSettled: () => void = () => {}; + let rejectSettled: (err: unknown) => void = () => {}; + const settledPromise = new Promise((resolve, reject) => { + resolveSettled = resolve; + rejectSettled = reject; + }); const completion = { - resolve: () => {}, + resolve: () => { + if (callbackErr === null) { + resolveSettled(); + } + }, reject: (err: unknown) => { callbackErr ??= err; + rejectSettled(callbackErr); }, }; - const workflowIds = resolveWfIds(assetIds); + + if (projectId) projectsToRefresh.add(projectId); + let mutateSettled = false; + let releaseOnMutateSettle = false; + let lateError: string | null = null; + const payload = mutation.attach({ + type: "add_workflows_to_scene", + Lc: sceneId, + Ic: sceneId, + rg: workflowIds, + YWa: workflowIds, + position: typeof req.position === "number" ? req.position : undefined, + Mh: undefined, + Eh: undefined, + De: completion, + ve: completion, + }); + const mutatePromise = Promise.resolve().then(() => helper.mutate(payload)); + void mutatePromise.then( + () => { + mutateSettled = true; + completion.resolve(); + if (releaseOnMutateSettle) { + mutation.finish(); + } + }, + (err: unknown) => { + mutateSettled = true; + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message === "mutation_timeout") { + rejectSettled(new Error("mutation_timeout")); + } else { + lateError ??= message; + completion.reject(err); + } + if (releaseOnMutateSettle) { + mutation.finish(); + } + }, + ); + void settledPromise.then( + () => undefined, + (err: unknown) => { + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message !== "mutation_timeout") { + lateError ??= message; + } + }, + ); + try { - await helper.mutate({ - type: "add_workflows_to_scene", - Lc: sceneId, - Ic: sceneId, - rg: workflowIds, - YWa: workflowIds, - position: typeof req.position === "number" ? req.position : undefined, - Mh: undefined, - Eh: undefined, - De: completion, - ve: completion, + let timer: ReturnType | undefined; + const outcome: AddClipsWaitOutcome = await Promise.race([ + settledPromise.then( + (): AddClipsWaitOutcome => ({ kind: "settled" }), + (err: unknown): AddClipsWaitOutcome => { + const message = + err instanceof Error ? err.message : String(err ?? "add_workflows_failed"); + if (message === "mutation_timeout") { + return { kind: "timeout" }; + } + return { + kind: "rejected", + error: message, + preSubmit: PRE_SUBMIT_ERRORS.has(message), + }; + }, + ), + new Promise((resolve) => { + timer = setTimeout(() => { + resolve({ kind: "timeout" }); + }, SCENE_ADD_CLIPS_TIMEOUT_MS); + }), + ]).finally(() => { + if (timer !== undefined) clearTimeout(timer); }); + + if (outcome.kind === "rejected") { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } + if (outcome.preSubmit && projectId) { + projectsToRefresh.delete(projectId); + } + return { ok: false, error: outcome.error }; + } + + if (outcome.kind === "timeout") { + let confirmed = false; + for (let attempt = 0; attempt < SCENE_CONFIRM_ATTEMPTS && !confirmed; attempt += 1) { + if (attempt > 0) await delay(SCENE_CONFIRM_INTERVAL_MS); + const freshTiles = store ? await fetchProjectStore(store) : null; + const afterScene = findLiveSceneTile(freshTiles, sceneId); + confirmed = + baseline !== null && + afterScene !== null && + sceneClipsConfirmed(baseline, afterScene, expectedClips, req.position); + if (lateError !== null) break; + } + if (confirmed) { + mutation.finish(); + if (projectId) projectsToRefresh.delete(projectId); + return { + ok: true, + scene_id: sceneId, + added: assetIds.length, + confirmed: true, + }; + } + if (lateError !== null) { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } + return { ok: false, error: lateError }; + } + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } + return { + ok: false, + error: "outcome_unknown", + project_id: projectId, + stage: "add_clips", + scene_id: sceneId, + asset_ids: assetIds, + }; + } + + mutation.finish(); + if (projectId) projectsToRefresh.delete(projectId); + await delay(400); + return { ok: true, scene_id: sceneId, added: assetIds.length }; } catch (err) { + if (mutateSettled) { + mutation.finish(); + } else { + releaseOnMutateSettle = true; + } return { ok: false, - error: err instanceof Error ? err.message : String(err ?? "add_workflows_failed"), - }; - } - if (callbackErr) { - return { - ok: false, - error: callbackErr instanceof Error ? callbackErr.message : String(callbackErr), + error: "outcome_unknown", + detail: err instanceof Error ? err.message : String(err), + project_id: projectId, + stage: "add_clips", + scene_id: sceneId, + asset_ids: assetIds, }; } - await delay(400); - return { ok: true, scene_id: sceneId, added: assetIds.length }; } return { ok: false, error: `unknown_scene_action:${action}` };