Drive Google Flow from Claude, Codex or a local control panel, on Mac or Windows — using your Google AI subscription credits instead of the pay-per-use video API. No browser extension.
Image batches: retry just the failed images; trash refuses ambiguous titles
GTAI-1e1fc449e2c38
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3722b1f..6870650 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -412,3 +412,16 @@ The preview tool could not read the project while it lived in ~/Desktop; check tthe start.) freshMedia now counts a video tile without its thumbnail (or a <video>) as busy, and waitForNewMediatakes title-tracked tiles only once the same titles show on two polls running. Same clip with the fix: done in48 s, renamed SettleTest-scene-01, 4.0 s file downloaded.+- RETRY ONLY THE FAILED IMAGES (2026-10-18, the user's request). A batch that ends "done" with some scenes still+ failed (after the agent was asked again and the one-by-one route) now records job.failed_scenes (scene numbers).+ flow_retry on such a job queues a NEW agent batch of just those scenes with agent_numbers, so they save as scene-07,+ scene-12 (numberOf() in agentRound and the one-by-one fallback); the list moves to the new job so it is never retried+ twice. The Monitor shows "Retry N failed image(s)" on that batch (before, Retry only showed on failed jobs, and would+ have re-run the whole batch). The note now starts with "still failed: ..." (the panel clamps notes to two lines).+ Test hooks: FLOW_MCP_SIMULATE_MISSING=n drops scene n from agent rounds, FLOW_MCP_SIMULATE_FAILED=n skips its+ one-by-one rerun; neither applies to a retry batch. Verified live, 0 credits: 3 scenes with 2 forced to fail ->+ done with scene-01/03 and "still failed: scene 2", the panel button pressed in a headless panel -> only scene-02+ made -> folder 01, 02, 03; the button gone afterwards.+- TRASH GUARD WAS BLIND TO DUPLICATES: scanGrid keeps one entry per title, so trashAsset's "two items share this name"+ check never fired and it trashed one of several same-titled tiles. countTitled() counts copies by media id (images)+ and by how many show at once (id-less videos). Verified: three "Red fox sitting in snow" -> refused.diff --git a/src/core.ts b/src/core.tsindex ef180a7..2edff70 100644--- a/src/core.ts+++ b/src/core.ts@@ -181,7 +181,7 @@ export const shapes = {type Args<K extends keyof typeof shapes> = z.infer<z.ZodObject<(typeof shapes)[K]>>;-export const jobView = ({ id, status, params, files, attempts, credits, progress, note, error }: Job) => ({+export const jobView = ({ id, status, params, files, attempts, credits, progress, note, error, failed_scenes }: Job) => ({id,status,project: params.output_dir,@@ -193,6 +193,7 @@ export const jobView = ({ id, status, params, files, attempts, credits, progressfiles,note,error,+ failed_scenes,});// One implementation runs in whichever process owns the Flow tab; the other process talks to it over HTTP (remote.ts).@@ -332,9 +333,33 @@ export class LocalCore implements Core {}async retry({ job_ids }: Args<"retry">) {- const ids = job_ids ?? this.queue.list().filter((j) => j.status === "failed").map((j) => j.id);- const jobs = ids.map((id) => this.queue.retry(id)).filter((j): j is Job => Boolean(j));- if (!jobs.length) throw new Error("No failed jobs to retry.");+ const ids = job_ids ?? this.queue.list().filter((j) => j.status === "failed" || j.failed_scenes?.length).map((j) => j.id);+ const jobs: Job[] = [];+ for (const id of ids) {+ const job = this.queue.get(id);+ const p = job?.params;+ if (job?.failed_scenes?.length && p?.agent_scenes && job.status === "done") {+ // A batch that finished with some images still failed: make just those again, under their own scene numbers,+ // instead of re-running the whole batch. The list moves to the new job, so it is never retried twice.+ const base = Number(p.file_stem.match(/\d+/)?.[0] ?? 1);+ const numbers = p.agent_numbers ?? p.agent_scenes.map((_, i) => base + i);+ const pick = job.failed_scenes.map((n) => numbers.indexOf(n)).filter((i) => i >= 0);+ job.failed_scenes = undefined;+ jobs.push(+ this.queue.add({+ ...p,+ prompt: `Agent batch: ${pick.length} failed image(s) again`,+ agent_scenes: pick.map((i) => p.agent_scenes![i]),+ agent_numbers: pick.map((i) => numbers[i]),+ file_stem: `scene-${String(numbers[pick[0]]).padStart(2, "0")}`,+ }),+ );+ continue;+ }+ const again = this.queue.retry(id);+ if (again) jobs.push(again);+ }+ if (!jobs.length) throw new Error("Nothing to retry: no failed jobs, and no batch with failed images.");return { jobs: jobs.map(jobView) };}diff --git a/src/flow.ts b/src/flow.tsindex 799fb63..ebd89ee 100644--- a/src/flow.ts+++ b/src/flow.ts@@ -1036,6 +1036,38 @@ export async function downloadAsset(name: string, targetStem: string, quality: D// is recoverable - and it never deletes permanently. Flow asks NO confirmation (mapped 2026-10-01: the tile menu's// "Move to trash" removes the tile at once), so whoever calls this must confirm with the user first. Matching is by// EXACT title, and an ambiguous title is refused: Flow reuses titles, and trashing the wrong one is the worst outcome.+// How many tiles carry this exact title. scanGrid keeps one entry per title (the virtual grid shows the same tile again+// as it scrolls), so it can never see two items with the same name: trashAsset's "two share it" guard never fired,+// and Flow's agent reuses titles freely (three "Red fox sitting in snow" in one test, 2026-10-18). Images are told apart+// by their media ids; id-less videos only when two of them are on screen together.+async function countTitled(page: Page, name: string): Promise<number> {+ await scrollToTop(page);+ const ids = new Set<string>();+ let together = 0;+ for (let step = 0; step < 200; step++) {+ const found = await page.evaluate(+ ([js, title]) => {+ const idOf = eval(js) as (t: Element) => string | undefined;+ return [...document.querySelectorAll("flow-grid-tile-container")].filter((t) => t.getAttribute("aria-label") === title).map((t) => idOf(t) ?? "");+ },+ [TILE_ID_JS, name] as const,+ );+ together = Math.max(together, found.length);+ for (const id of found) if (id && !id.startsWith("title:")) ids.add(id);+ const moved = await page.evaluate(() => {+ const el = document.querySelector(".page-container");+ if (!el) return false;+ const before = el.scrollTop;+ el.scrollTop = before + el.clientHeight * 0.8;+ return el.scrollTop > before;+ });+ if (!moved) break;+ await pause(page, 500);+ }+ await scrollToTop(page);+ return Math.max(ids.size, together);+}+export async function trashAsset(name: string): Promise<{ trashed: string }> {const state = await getFlowState();if (!state.signedIn || !state.inProject) throw new Error(state.hint);@@ -1043,7 +1075,8 @@ export async function trashAsset(name: string): Promise<{ trashed: string }> {await ensureProjectGrid(page);const same = (await scanGrid(page)).filter((a) => a.name === name);if (!same.length) throw new Error(`Nothing in the open project is called "${name}".`);- if (same.length > 1) throw new Error(`${same.length} items are called "${name}", so it isn't clear which one to trash. Rename one in Flow first.`);+ const copies = await countTitled(page, name);+ if (copies > 1) throw new Error(`${copies} items are called "${name}", so it isn't clear which one to trash. Rename one in Flow first.`);// Scan again, stopping on the tile so it stays mounted in the virtual grid (no scrollToTop before acting on it).await scanGrid(page, (seen) => seen.some((a) => a.name === name));const tile = tileOf(page, same[0]);@@ -1389,6 +1422,8 @@ async function agentRound(): Promise<RoundOutcome> {const s = job.params;const aspect = s.aspect_ratio ?? "16:9";+ const base = Number(s.file_stem.match(/\d+/)?.[0] ?? 1);+ const numberOf = (i: number) => s.agent_numbers?.[i] ?? base + i;await ensureProjectGrid(page);const seenBefore = await scanGrid(page);// Ids are unique per generation; titles are not (the agent reuses wording), so only id-less tiles fall back to a name.@@ -1398,7 +1433,7 @@ async function agentRound(const clear = page.getByRole("button", { name: "Clear prompt" });if (await clear.isVisible().catch(() => false)) await clear.click();- const script = indexes.map((i) => `Scene ${i + 1}: ${scenes[i].replace(/\s*\n+\s*/g, " ").trim()}`).join(" ");+ const script = indexes.map((i) => `Scene ${numberOf(i)}: ${scenes[i].replace(/\s*\n+\s*/g, " ").trim()}`).join(" ");const lead = retry? `${indexes.length} image(s) from the last batch failed to generate. Generate them again now, one image per scene`: `Generate exactly ${indexes.length} separate images, one image per scene, in scene order`;@@ -1460,16 +1495,15 @@ async function agentRound();const drop = Number(process.env.FLOW_MCP_SIMULATE_MISSING ?? 0); // test hook: pretend this scene number failedmkdirSync(s.output_dir, { recursive: true });- const base = Number(s.file_stem.match(/\d+/)?.[0] ?? 1);let produced = 0;for (const [n, tileIndexes] of assigned.entries()) {const sceneIndex = indexes[n];- if (!tileIndexes.length || sceneIndex + 1 === drop) continue;+ if (!tileIndexes.length || (numberOf(sceneIndex) === drop && !s.agent_numbers)) continue;for (const [v, tileIndex] of tileIndexes.entries()) {const id = fresh[tileIndex].id!;await scanGrid(page, (seen) => seen.some((x) => x.id === id));- const stem = join(s.output_dir, `scene-${String(base + sceneIndex).padStart(2, "0")}${v ? `-v${v + 1}` : ""}`);- step(job, `downloading scene ${sceneIndex + 1}`);+ const stem = join(s.output_dir, `scene-${String(numberOf(sceneIndex)).padStart(2, "0")}${v ? `-v${v + 1}` : ""}`);+ step(job, `downloading scene ${numberOf(sceneIndex)}`);files.push(...(await downloadTile(page, mediaTile(page, id), stem, s.download_quality ?? "original")));await pause(page, 800);}@@ -1648,8 +1682,14 @@ export async function runAgentBatch(job: Job): Promise<string[]> {const missing = scenes.map((_, i) => i).filter((i) => !done.has(i));const failed: number[] = [];const base = Number(s.file_stem.match(/\d+/)?.[0] ?? 1);+ const numberOf = (i: number) => s.agent_numbers?.[i] ?? base + i;+ const stillFails = Number(process.env.FLOW_MCP_SIMULATE_FAILED ?? 0); // test hook: pretend this scene failed for goodfor (const [n, i] of missing.entries()) {- job.progress = `re-running scene ${i + 1} one by one (${n + 1}/${missing.length})`;+ job.progress = `re-running scene ${numberOf(i)} one by one (${n + 1}/${missing.length})`;+ if (numberOf(i) === stillFails && !job.params.agent_numbers) {+ failed.push(numberOf(i));+ continue;+ }const single: Job = {...job,files: [],@@ -1660,7 +1700,7 @@ export async function runAgentBatch(job: Job): Promise<string[]> {aspect_ratio: s.aspect_ratio,download_quality: s.download_quality,output_dir: s.output_dir,- file_stem: `scene-${String(base + i).padStart(2, "0")}`,+ file_stem: `scene-${String(numberOf(i)).padStart(2, "0")}`,},};let ok = false;@@ -1673,20 +1713,22 @@ export async function runAgentBatch(job: Job): Promise<string[]> {/* one more attempt, then give up on this scene */}}- if (!ok) failed.push(i + 1);+ if (!ok) failed.push(numberOf(i));}+ job.failed_scenes = failed.length ? failed : undefined;step(job, "reading the credit balance");const left = await readCredits(page).catch(() => undefined);step(job, undefined);files.sort();job.note = [+ // What still needs doing first: the panel shows only the start of a long note.+ failed.length ? `still failed: scene ${failed.join(", ")} (use Retry)` : "",agentProblem ? `agent mode failed (${agentProblem}), so the images were made one by one` : "",agentTimedOut ? "the agent stalled and was stopped" : "",`${done.size} of ${scenes.length} scenes came from the agent`,agentRetries ? `${agentRetries} asked again` : "",failedTiles ? `${failedTiles} tile(s) failed in Flow` : "",- missing.length ? `${missing.length - failed.length} re-run one by one` : "",- failed.length ? `still failed: scene ${failed.join(", ")} (use Retry)` : "",+ missing.length > failed.length ? `${missing.length - failed.length} re-run one by one` : "",].filter(Boolean).join(" · ");diff --git a/src/index.ts b/src/index.tsindex 913455e..09a559e 100644--- a/src/index.ts+++ b/src/index.ts@@ -135,7 +135,7 @@ server.registerTool("flow_retry",{title: "Retry failed Flow jobs",- description: "Put failed jobs back in the queue with the same settings and file names (default: all failed jobs). Scenes already retry once on their own when Flow reports a failure.",+ description: "Put failed jobs back in the queue with the same settings and file names (default: all failed jobs). Scenes already retry once on their own when Flow reports a failure. An image batch that finished with some images still failed (its job lists failed_scenes) is not run again whole: only those images are made again, saved under their own scene numbers.",inputSchema: shapes.retry,annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },},diff --git a/src/playbook.ts b/src/playbook.tsindex 96d8354..e2055b5 100644--- a/src/playbook.ts+++ b/src/playbook.ts@@ -5,6 +5,7 @@ export const PLAYBOOK = {"Plan the whole piece as scenes of one shot each, then send them in ONE flow_generate call so file numbering and chaining work.","Tell the user the expected credit total before queueing anything that costs credits.","Call flow_wait repeatedly until finished is true; scenes run one at a time with 25-70 s pauses.",+ "If an image batch finishes with \"still failed: scene ...\" in its note, call flow_retry with its job id: only those images are made again, under their own scene numbers.","No call blocks for more than about 45 s. A reply with still_working and a task_id means Flow is still busy with it: pass the task_id to flow_wait, and never repeat the call.",],models: {diff --git a/src/queue.ts b/src/queue.tsindex c7c0e10..ae8f00f 100644--- a/src/queue.ts+++ b/src/queue.ts@@ -18,6 +18,9 @@ export interface SceneParams {reference_from?: string;edit_asset?: string;agent_scenes?: string[];+ // The scene number each agent scene is saved as. A retry of scenes 7 and 12 keeps scene-07 and scene-12; without it+ // the numbers run on from file_stem.+ agent_numbers?: number[];continue_from?: string;attach?: string[];continue_mode?: "exact" | "likeness";@@ -37,6 +40,8 @@ export interface Job {progress?: string;note?: string;error?: string;+ // Scene numbers a batch still could not make after all its own retries; flow_retry redoes just these.+ failed_scenes?: number[];createdAt: string;finishedAt?: string;}diff --git a/studio/index.html b/studio/index.htmlindex ba44cf2..58019ea 100644--- a/studio/index.html+++ b/studio/index.html@@ -917,13 +917,13 @@ function renderStatus(st) {$("#hint").innerHTML = f.hint ? `<div class="hint">${esc(f.hint)}</div>` : "";$("#pacing").innerHTML = st.pacing ? `<div class="pacing">⏱ ${esc(st.pacing)}</div>` : "";const jobs = [...st.jobs].reverse();- const sig = JSON.stringify(jobs.map((j) => [j.id, j.status, j.progress, j.files.length, j.credits, j.attempts]));+ const sig = JSON.stringify(jobs.map((j) => [j.id, j.status, j.progress, j.files.length, j.credits, j.attempts, j.failed_scenes?.length ?? 0]));if (sig !== renderStatus.sig) {if (renderStatus.sig && LIVE) loadGallery(slateFolder());renderStatus.sig = sig;$("#jobs").innerHTML = jobs.map((j) => `<div class="job"><div class="top"><span class="name">${esc((j.project || "").split(/[\\/]/).pop())} · ${esc(j.scene)}</span><span class="badge ${j.status}">${j.status}${j.progress ? " " + esc(j.progress) : ""}</span>${j.credits !== undefined ? `<span class="badge">${j.credits} cr</span>` : ""}${j.attempts > 1 ? `<span class="badge">try ${j.attempts}</span>` : ""}- ${j.status === "queued" ? `<button class="btn small ghost" data-cancel="${j.id}">Cancel</button>` : ""}${/failed|cancelled/.test(j.status) ? `<button class="btn small" data-retry="${j.id}">Retry</button>` : ""}</div>+ ${j.status === "queued" ? `<button class="btn small ghost" data-cancel="${j.id}">Cancel</button>` : ""}${/failed|cancelled/.test(j.status) ? `<button class="btn small" data-retry="${j.id}">Retry</button>` : ""}${j.status === "done" && j.failed_scenes?.length ? `<button class="btn small" data-retry="${j.id}">Retry ${j.failed_scenes.length} failed image${j.failed_scenes.length > 1 ? "s" : ""}</button>` : ""}</div>${j.status === "running" ? `<div class="meter"><i style="width:${parseInt(j.progress) || 4}%"></i></div>` : ""}<p>${esc(j.prompt)}</p>${j.note ? `<p style="color:var(--warn)">${esc(j.note)}</p>` : ""}${j.error ? `<p class="err">${esc(j.error)}</p>` : ""}${j.files.map((p) => (/\.(mp4|webm|mov)$/i.test(p) ? `<video controls playsinline preload="metadata" src="${media(p)}"></video>` : /\.(m4a|mp3|wav)$/i.test(p) ? `<audio controls src="${media(p)}"></audio>` : `<img class="out" src="${media(p)}">`)).join("")}</div>`).join("") || `<p class="empty">Nothing queued yet.</p>`;