Skip to content
75 changes: 58 additions & 17 deletions src/scenes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -170,6 +170,32 @@ pub(crate) struct VideoParams {
pub(crate) scene_id: Option<String>,
}

/// 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,
Expand Down Expand Up @@ -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)
}
Expand All @@ -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)
}
Expand Down
65 changes: 55 additions & 10 deletions ts/project_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> = Promise.resolve();
/** Per-payload gates that unblock `mutationChain` when the server confirms a mutation early. */
const mutationGates = new WeakMap<Record<string, unknown>, Promise<void>>();

/** Returns the project ID in the current route. */
export function projectInRoute(): string | null {
Expand Down Expand Up @@ -283,8 +285,12 @@ async function dispatchStoreMutation(

/** Serializes general store mutations in the current page session. */
function mutateStore(store: ProjectStore, payload: Record<string, unknown>): Promise<unknown> {
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;
}

Expand Down Expand Up @@ -459,18 +465,50 @@ export async function refreshProjectStore(store: ProjectStore): Promise<Map<stri
const MUTATION_TIMEOUT_MS = 10_000;
/** Time between checks for a submitted change. */
const MUTATION_CHECK_INTERVAL_MS = 250;
/** True until the previous project submission settles. */
/** Active submissions that have not settled or been confirmed by the server. */
const activeProjectMutations = new Set<symbol>();
/** 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<string>();

/** 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: <T extends Record<string, unknown>>(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<void>((resolve) => {
releaseGate = resolve;
});
return {
finish: () => {
if (!activeProjectMutations.delete(token)) return;
projectMutationPending = activeProjectMutations.size > 0;
releaseGate?.();
},
attach: <T extends Record<string, unknown>>(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<string, unknown>,
verified: (tiles: Map<string, FlowTile>) => boolean,
): Promise<Map<string, FlowTile> | null> {
projectMutationPending = true;
const mutation = beginProjectMutation();
projectsToRefresh.add(store.projectId);
let timer: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
Expand All @@ -497,7 +535,7 @@ export async function mutateAndVerify(
} catch {
return null;
} finally {
projectMutationPending = false;
mutation.finish();
}
})();
try {
Expand All @@ -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<Map<string, FlowTile> | null> {
/** Fetches a new tile result from the server within the mutation time limit. */
export async function fetchProjectStore(
store: ProjectStore,
): Promise<Map<string, FlowTile> | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<null>((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<Map<string, FlowTile> | null> {
const tiles = await fetchProjectStore(store);
if (tiles) projectsToRefresh.delete(store.projectId);
return tiles;
}
Loading
Loading