Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/handlers/transcribe.handler.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { handleTranscribe, type TranscribeDeps } from "./transcribe.handler.js";
import { handleJobStatus, handleTranscribe, type TranscribeDeps } from "./transcribe.handler.js";

const executeMock = vi.fn();
const cacheGetMock = vi.fn();
Expand Down Expand Up @@ -110,3 +110,32 @@ describe("handleTranscribe, sample mode", () => {
expect(cacheSetMock).toHaveBeenCalled();
});
});

describe("handleJobStatus, web server jobs", () => {
it("passes the job's result through so output paths and per-clip errors reach the caller", async () => {
const result = {
total_clips: 2,
successful_clips: 1,
results: [
{ clip_index: 0, status: "success", output_path: "/out/a.mp4" },
{ clip_index: 1, status: "error", error: "Remotion caption render failed" },
],
};

vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
new Response(JSON.stringify({ status: "done", progress: 100, message: "1 of 2 clips rendered.", result })),
),
);

try {
const parsed = JSON.parse(await handleJobStatus({ job_id: "job-1", wait_seconds: 0 }));

expect(parsed.done).toBe(true);
expect(parsed.result).toEqual(result);
} finally {
vi.unstubAllGlobals();
}
});
});
7 changes: 5 additions & 2 deletions src/handlers/transcribe.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,12 +433,15 @@ export async function handleJobStatus(input: {
progress: job.progress,
message: job.message,
done: terminal,
// Renders list output paths and, for a batch, each clip's own error here;
// without it a failed clip is only visible through the web server's API.
result: job.result,
error: job.error,
next_step:
job.status === "done"
? "Job complete. For transcription: get_ui_state(include_transcript: true). For renders: clips are on disk. The result field lists paths."
? "Job complete. For transcription: get_ui_state(include_transcript: true). For renders: the result field lists output paths; a batch's message names any clips that failed, and result.results[].error has each one's full error."
: job.status === "error"
? "Job failed: check the error. Retry the original start call if appropriate."
? "Job failed: check the error (for a batch, result.results[].error has each clip's error). Fix the cause before retrying the original start call."
: `Still running: call job_status("${input.job_id}", wait_seconds: 30) again and emit one terse progress line to the user between polls.`,
});
}
Expand Down
152 changes: 152 additions & 0 deletions src/ui/web-server-batch-outcome.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { z } from "zod";
import { stubPythonBackend } from "../test-support/stub-python-backend.js";
import type { BatchClipsResult } from "../models/index.js";

// The Python batch task succeeds as a task even when every clip in it failed.
// The job used to end as "done" / "Export complete!" anyway, so an agent polling
// job_status saw success with no clips on disk.

const tmp = mkdtempSync(join(tmpdir(), "podcli-batch-outcome-"));

const savedEnv = {
PODCLI_HOME: process.env.PODCLI_HOME,
PODCLI_DATA: process.env.PODCLI_DATA,
PODCLI_OUTPUT: process.env.PODCLI_OUTPUT,
PODCLI_PORT: process.env.PODCLI_PORT,
};

const PORT = 18430;
const BASE = `http://127.0.0.1:${PORT}`;
const REMOTION_ERROR = "Remotion caption render failed. ASS fallback is disabled";

let batchReply: BatchClipsResult = { total_clips: 0, successful_clips: 0, results: [] };
let videoPath: string;

const jobSchema = z.object({
status: z.enum(["pending", "running", "done", "error"]),
message: z.string(),
error: z.string().optional(),
result: z.object({ results: z.array(z.object({ status: z.string(), error: z.string().optional() })) }).optional(),
});

async function waitForServer(): Promise<void> {
for (let i = 0; i < 50; i++) {
try {
const res = await fetch(`${BASE}/api/ui-state`);

if (res.ok) return;
} catch {
// not up yet
}

await new Promise((r) => setTimeout(r, 100));
}

throw new Error("web server never came up");
}

async function finishedJob(path: string, body: ExportRequest): Promise<z.infer<typeof jobSchema>> {
const start = await fetch(`${BASE}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});

expect(start.status).toBe(200);

const { job_id } = z.object({ job_id: z.string() }).parse(await start.json());

for (let i = 0; i < 100; i++) {
const job = jobSchema.parse(await (await fetch(`${BASE}/api/job/${job_id}`)).json());

if (job.status === "done" || job.status === "error") return job;
await new Promise((r) => setTimeout(r, 50));
}

throw new Error("batch job never finished");
}

const clips = [
{ start_second: 10, end_second: 40, title: "one" },
{ start_second: 60, end_second: 90, title: "two" },
{ start_second: 120, end_second: 150, title: "three" },
];

interface ExportRequest {
video_path: string;
clips: typeof clips;
}

function rows(statuses: Array<"success" | "error">): BatchClipsResult {
return {
total_clips: statuses.length,
successful_clips: statuses.filter((s) => s === "success").length,
results: statuses.map((status, i) =>
status === "success"
? { clip_index: i, status: "success" as const, output_path: join(tmp, `clip-${i}.mp4`) }
: { clip_index: i, status: "error" as const, error: `${REMOTION_ERROR} (clip ${i})` },
),
};
}

beforeAll(async () => {
process.env.PODCLI_HOME = join(tmp, "home");
process.env.PODCLI_DATA = join(tmp, "data");
process.env.PODCLI_OUTPUT = join(tmp, "data", "output");
process.env.PODCLI_PORT = String(PORT);
mkdirSync(process.env.PODCLI_HOME, { recursive: true });
videoPath = join(tmp, "episode.mp4");
writeFileSync(videoPath, "not really a video");

await stubPythonBackend((taskType) => (taskType === "batch_clips" ? batchReply : {}));
await import("./web-server.js");
await waitForServer();
}, 20_000);

afterAll(() => {
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}

rmSync(tmp, { recursive: true, force: true });
});

describe.each([
["/api/batch-clips", "Batch complete!"],
["/api/mcp/export", "Export complete!"],
])("POST %s", (path, successMessage) => {
it("ends as an error with the first clip's error when no clip rendered", async () => {
batchReply = rows(["error", "error", "error"]);
const job = await finishedJob(path, { video_path: videoPath, clips });

expect(job.status).toBe("error");
expect(job.error).toContain("All 3 clips failed");
expect(job.error).toContain(`${REMOTION_ERROR} (clip 0)`);
expect(job.message).toContain(REMOTION_ERROR);
// The per-clip errors stay readable on the job.
expect(job.result?.results.map((r) => r.error)).toHaveLength(3);
});

it("says how many rendered and lists the failures when some clips failed", async () => {
batchReply = rows(["success", "error", "success"]);
const job = await finishedJob(path, { video_path: videoPath, clips });

expect(job.status).toBe("done");
expect(job.error).toBeUndefined();
expect(job.message).toContain("2 of 3 clips rendered");
expect(job.message).toContain(`clip 2: ${REMOTION_ERROR} (clip 1)`);
});

it("keeps the plain success message when every clip rendered", async () => {
batchReply = rows(["success", "success", "success"]);
const job = await finishedJob(path, { video_path: videoPath, clips });

expect(job.status).toBe("done");
expect(job.message).toBe(successMessage);
});
});
32 changes: 23 additions & 9 deletions src/ui/web-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ import { playbackDuration, validateHook } from "../utils/clip-hook.js";
import { hookSchema } from "../handlers/suggest-clips.handler.js";
import { needsFrame, thumbnailRenderArgs } from "../utils/thumbnail-layout.js";
import { parseThumbnailRender } from "../utils/thumbnail-render-output.js";
import { advanceProgress, tagSubmittedClip, tagSubmittedClips } from "../utils/clip-results.js";
import { advanceProgress, summarizeBatchOutcome, tagSubmittedClip, tagSubmittedClips } from "../utils/clip-results.js";
import { DEMO_ASSETS_DIR } from "./demo-fixtures.js";
import { registerConfigIntegrationRoutes } from "../handlers/integrations.routes.js";
import { childLogger } from "../utils/logger.js";
Expand Down Expand Up @@ -1811,9 +1811,11 @@ app.post("/api/batch-clips", async (req, res) => {
)
.then(async (result) => {
const data = tagSubmittedClips(result.data, enrichedClips);
job.status = "done";
const outcome = summarizeBatchOutcome(data, "Batch complete!");
job.status = outcome.status;
job.progress = 100;
job.message = "Batch complete!";
job.message = outcome.message;
job.error = outcome.error;
job.result = data;
// Persist here too: the studio tab may be closed (an MCP-driven
// export), and it only stores results when it hears job-complete.
Expand All @@ -1828,8 +1830,13 @@ app.post("/api/batch-clips", async (req, res) => {
});
}

setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
if (outcome.status === "error") {
setExportState("review", null);
broadcastSSE("job-error", { jobId, error: outcome.error, result: data });
} else {
setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
}
})
.catch((err) => {
job.status = "error";
Expand Down Expand Up @@ -5750,9 +5757,11 @@ app.post("/api/mcp/export", async (req, res) => {
)
.then(async (result) => {
const data = tagSubmittedClips(result.data, styledClips);
job.status = "done";
const outcome = summarizeBatchOutcome(data, "Export complete!");
job.status = outcome.status;
job.progress = 100;
job.message = "Export complete!";
job.message = outcome.message;
job.error = outcome.error;
job.result = data;
uiState.results = data?.results ?? [];

Expand All @@ -5765,8 +5774,13 @@ app.post("/api/mcp/export", async (req, res) => {
});
}

setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
if (outcome.status === "error") {
setExportState("review", null);
broadcastSSE("job-error", { jobId, error: outcome.error, result: data });
} else {
setExportState("done", null);
broadcastSSE("job-complete", { jobId, result: data });
}
})
.catch((err) => {
job.status = "error";
Expand Down
47 changes: 46 additions & 1 deletion src/utils/clip-results.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { advanceProgress, tagSubmittedClip, tagSubmittedClips } from "./clip-results.js";
import { advanceProgress, summarizeBatchOutcome, tagSubmittedClip, tagSubmittedClips } from "./clip-results.js";
import type { BatchClipsResult } from "../models/index.js";

const specs = [
Expand Down Expand Up @@ -76,3 +76,48 @@ describe("advanceProgress", () => {
expect(job.progress).toBe(75);
});
});

describe("summarizeBatchOutcome", () => {
const fail = (clip_index: number, error: string) => ({ clip_index, status: "error" as const, error });
const ok = (clip_index: number) => ({ clip_index, status: "success" as const, output_path: `/out/${clip_index}.mp4` });

it("fails the job with the first clip's error when nothing rendered", () => {
const outcome = summarizeBatchOutcome(
{ total_clips: 2, successful_clips: 0, results: [fail(0, "bundle failed"), fail(1, "other")] },
"Export complete!",
);

expect(outcome.status).toBe("error");
expect(outcome.error).toBe("All 2 clips failed. First error (clip 1): bundle failed");
expect(outcome.message).toBe(`Error: ${outcome.error}`);
});

it("names the rendered count and every failed clip on a partial batch", () => {
const outcome = summarizeBatchOutcome(
{ total_clips: 3, successful_clips: 1, results: [ok(0), fail(1, "a"), fail(2, "b")] },
"Export complete!",
);

expect(outcome).toEqual({ status: "done", message: "1 of 3 clips rendered. Failed: clip 2: a; clip 3: b" });
});

it("keeps the success message when every clip rendered", () => {
expect(summarizeBatchOutcome({ total_clips: 1, successful_clips: 1, results: [ok(0)] }, "Batch complete!"))
.toEqual({ status: "done", message: "Batch complete!" });
});

it("fails a batch that came back with no rows", () => {
expect(summarizeBatchOutcome(undefined, "Batch complete!").status).toBe("error");
expect(summarizeBatchOutcome({ total_clips: 0, successful_clips: 0, results: [] }, "x").status).toBe("error");
});

it("shortens a long stack trace to one line in the message", () => {
const outcome = summarizeBatchOutcome(
{ total_clips: 1, successful_clips: 0, results: [fail(0, `boom\n${"at frame\n".repeat(200)}`)] },
"x",
);

expect(outcome.message).not.toContain("\n");
expect(outcome.message.length).toBeLessThan(400);
});
});
60 changes: 60 additions & 0 deletions src/utils/clip-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,63 @@ export function advanceProgress(job: { progress: number }, percent: number): num

return job.progress;
}

export interface BatchOutcome {
status: "done" | "error";
message: string;
/** Set when no clip rendered: the first clip's error, for the job's error field. */
error?: string;
}

// Remotion failures carry long stack traces; the status line only needs the gist.
// The full text stays in result.results[].error.
const MAX_ERROR_CHARS = 300;

function shortError(text: string): string {
const oneLine = text.replace(/\s+/g, " ").trim();

return oneLine.length > MAX_ERROR_CHARS ? `${oneLine.slice(0, MAX_ERROR_CHARS - 1)}…` : oneLine;
}

function clipLabel(row: ClipResultRow, position: number): string {
return `clip ${(row.clip_index ?? position) + 1}`;
}

// The Python batch task succeeds as a task even when every clip in it failed, so
// the job's final state has to come from the per-clip rows: a batch where nothing
// rendered is a failed job, and a partial one says which clips are missing.
export function summarizeBatchOutcome(
data: BatchClipsResult | undefined,
successMessage: string,
): BatchOutcome {
const results = data?.results ?? [];

if (!data || results.length === 0) {
const error = "The batch render returned no clip results.";

return { status: "error", message: `Error: ${error}`, error };
}

const total = data.total_clips ?? results.length;

const failures = results
.map((row, position) => ({ row, position }))
.filter(({ row }) => row.status !== "success");

const rendered = results.length - failures.length;

if (failures.length === 0) return { status: "done", message: successMessage };

const failureList = failures
.map(({ row, position }) => `${clipLabel(row, position)}: ${shortError(row.error || "unknown error")}`)
.join("; ");

if (rendered === 0) {
const first = failures[0];
const error = `All ${total} clips failed. First error (${clipLabel(first.row, first.position)}): ${shortError(first.row.error || "unknown error")}`;

return { status: "error", message: `Error: ${error}`, error };
}

return { status: "done", message: `${rendered} of ${total} clips rendered. Failed: ${failureList}` };
}