Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: support safe AI summary and chapter edits

Richie McIlroy60163188f9ae
diff --git a/apps/web/__tests__/unit/ai-content.test.ts b/apps/web/__tests__/unit/ai-content.test.ts
new file mode 100644
index 000000000..eb644e00b
--- /dev/null
+++ b/apps/web/__tests__/unit/ai-content.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatChapterTime,
+ MAX_CHAPTERS,
+ parseChapterTime,
+ validateAiContent,
+} from "@/lib/ai-content";
+
+const content = (starts: number[]) => ({
+ summary: "A summary",
+ chapters: starts.map((start) => ({ title: "Topic", start })),
+});
+
+describe("chapter timestamps", () => {
+ it.each([
+ ["00:00", 0],
+ ["02:30", 150],
+ ["90:10", 5410],
+ ["1:30:10.125", 5410.125],
+ [" 00:01.5 ", 1.5],
+ ])("parses %s", (text, seconds) => {
+ expect(parseChapterTime(text)).toBe(seconds);
+ });
+ it.each([
+ "",
+ "12",
+ "1:60",
+ "1:99:00",
+ "-1:00",
+ "1:2",
+ "1:00garbage",
+ "NaN",
+ "Infinity",
+ ])("rejects %s", (value) => {
+ expect(parseChapterTime(value)).toBeNaN();
+ });
+ it.each([0, 1.123, 59.999, 60, 3599, 3600, 5410.125, 86400])(
+ "round-trips %s seconds",
+ (seconds) => {
+ expect(parseChapterTime(formatChapterTime(seconds))).toBe(seconds);
+ },
+ );
+});
+
+describe("AI content validation", () => {
+ it("allows removing all summary and chapters", () => {
+ expect(validateAiContent({ summary: "", chapters: [] }, 10)).toBeNull();
+ });
+ it("allows strictly ordered chapters within duration", () => {
+ expect(validateAiContent(content([0, 10.125, 59]), 60)).toBeNull();
+ });
+ it.each([
+ [0, 0],
+ [10, 5],
+ ])("rejects duplicate or unordered times %j", (...starts) => {
+ expect(validateAiContent(content(starts), 60)).toContain(
+ "increasing order",
+ );
+ });
+ it.each([Number.NaN, Number.POSITIVE_INFINITY, -1])(
+ "rejects invalid time %s",
+ (start) => {
+ expect(validateAiContent(content([start]))).toContain("valid timestamp");
+ },
+ );
+ it("rejects timestamps at or beyond the end", () => {
+ expect(validateAiContent(content([60]), 60)).toContain(
+ "before the video ends",
+ );
+ });
+ it("supports recordings with unknown duration", () => {
+ expect(validateAiContent(content([0, 600]), null)).toBeNull();
+ });
+ it("rejects blank titles and oversized content", () => {
+ expect(
+ validateAiContent({ summary: "", chapters: [{ title: " ", start: 0 }] }),
+ ).toContain("needs a title");
+ expect(
+ validateAiContent({ summary: "x".repeat(50001), chapters: [] }),
+ ).toContain("summary under");
+ expect(
+ validateAiContent(
+ content(Array.from({ length: MAX_CHAPTERS + 1 }, (_, i) => i)),
+ ),
+ ).toContain("no more than");
+ });
+});
diff --git a/apps/web/__tests__/unit/edit-ai-content.test.ts b/apps/web/__tests__/unit/edit-ai-content.test.ts
new file mode 100644
index 000000000..4e95b19cd
--- /dev/null
+++ b/apps/web/__tests__/unit/edit-ai-content.test.ts
@@ -0,0 +1,247 @@
+import { MySqlDialect } from "drizzle-orm/mysql-core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getCurrentUser: vi.fn(),
+ transaction: vi.fn(),
+ revalidatePath: vi.fn(),
+ entitled: vi.fn(),
+ lockedRead: vi.fn(),
+ write: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({
+ db: () => ({ transaction: mocks.transaction }),
+}));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/lib/ai-generation-entitlement", () => ({
+ isAiGenerationEnabledForUser: mocks.entitled,
+}));
+
+import type { Video } from "@cap/web-domain";
+import { sql } from "drizzle-orm";
+import { editAiContent } from "@/actions/videos/edit-ai-content";
+import { setGeneratedAiContent } from "@/lib/ai-content-metadata";
+
+const videoId = "video-id" as Video.VideoId;
+const expected = {
+ summary: "Original",
+ chapters: [{ title: "Intro", start: 0 }],
+};
+let readSql: string;
+let writeSql: string;
+let writeParams: unknown[];
+let metadata: Record<string, unknown>;
+
+beforeEach(() => {
+ metadata = {
+ ...expected,
+ aiGenerationStatus: "COMPLETE",
+ customCreatedAt: "2026-01-01",
+ };
+ mocks.getCurrentUser.mockResolvedValue({ id: "owner" });
+ mocks.entitled.mockReturnValue(true);
+ mocks.lockedRead.mockImplementation(async () => [
+ { metadata, duration: 120 },
+ ]);
+ mocks.write.mockResolvedValue([{ affectedRows: 1 }]);
+ const dialect = new MySqlDialect();
+ const tx = {
+ select: () => ({
+ from: () => ({
+ where: (condition: Parameters<MySqlDialect["sqlToQuery"]>[0]) => {
+ readSql = JSON.stringify(dialect.sqlToQuery(condition));
+ return { for: mocks.lockedRead };
+ },
+ }),
+ }),
+ update: () => ({
+ set: (values: {
+ metadata: Parameters<MySqlDialect["sqlToQuery"]>[0];
+ }) => {
+ const query = dialect.sqlToQuery(values.metadata);
+ writeSql = query.sql;
+ writeParams = query.params;
+ return { where: mocks.write };
+ },
+ }),
+ };
+ mocks.transaction.mockImplementation((callback) => callback(tx));
+});
+
+describe("editing AI content", () => {
+ it("compares chapters independently of MySQL JSON key ordering", async () => {
+ metadata.chapters = [{ start: 0, title: "Intro" }];
+ expect(
+ (
+ await editAiContent(videoId, {
+ expected,
+ value: { ...expected, chapters: [{ title: "Renamed", start: 0 }] },
+ })
+ ).success,
+ ).toBe(true);
+ });
+ it("blocks edits during transcription after a media change", async () => {
+ mocks.lockedRead.mockResolvedValueOnce([
+ { metadata, duration: 120, transcriptionStatus: "PROCESSING" },
+ ]);
+ expect(
+ (
+ await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: "Edited" },
+ })
+ ).success,
+ ).toBe(false);
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+ it("requires authentication and Pro entitlement", async () => {
+ mocks.getCurrentUser.mockResolvedValueOnce(null);
+ expect((await editAiContent(videoId, {})).success).toBe(false);
+ mocks.entitled.mockReturnValueOnce(false);
+ expect((await editAiContent(videoId, {})).success).toBe(false);
+ expect(mocks.transaction).not.toHaveBeenCalled();
+ });
+ it("scopes the locked row to its owner", async () => {
+ mocks.lockedRead.mockResolvedValueOnce([]);
+ expect(
+ (
+ await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: "Edited" },
+ })
+ ).success,
+ ).toBe(false);
+ expect(readSql).toContain("ownerId");
+ expect(readSql).toContain("owner");
+ expect(mocks.lockedRead).toHaveBeenCalledWith("update");
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+ it("updates only the summary while retaining concurrently updated chapters", async () => {
+ metadata.chapters = [{ title: "Updated elsewhere", start: 10 }];
+ const result = await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: " **Edited** " },
+ });
+ expect(result).toEqual({
+ success: true,
+ data: { summary: "**Edited**", chapters: metadata.chapters },
+ });
+ expect(writeSql).toContain("JSON_SET");
+ expect(writeSql).toContain("summaryManuallyEdited");
+ expect(writeSql).not.toContain("chaptersManuallyEdited");
+ expect(writeParams).toContain("**Edited**");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/s/video-id");
+ });
+ it("updates chapters as JSON and preserves a concurrent summary edit", async () => {
+ metadata.summary = "Updated elsewhere";
+ const result = await editAiContent(videoId, {
+ expected,
+ value: { ...expected, chapters: [{ title: " Changed ", start: 20 }] },
+ });
+ expect(result).toEqual({
+ success: true,
+ data: {
+ summary: "Updated elsewhere",
+ chapters: [{ title: "Changed", start: 20 }],
+ },
+ });
+ expect(writeSql).toContain("CAST(? AS JSON)");
+ expect(writeSql).not.toContain("summaryManuallyEdited");
+ expect(writeParams).toContain('[{"title":"Changed","start":20}]');
+ });
+ it("rejects stale edits without writing", async () => {
+ metadata.summary = "Newer saved summary";
+ const result = await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: "Stale edit" },
+ });
+ expect(result).toMatchObject({
+ success: false,
+ message: expect.stringContaining("changed since"),
+ });
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+ it.each(["QUEUED", "PROCESSING"])(
+ "rejects edits while %s",
+ async (status) => {
+ metadata.aiGenerationStatus = status;
+ expect(
+ (
+ await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: "Edited" },
+ })
+ ).success,
+ ).toBe(false);
+ expect(mocks.write).not.toHaveBeenCalled();
+ },
+ );
+ it.each([
+ { summary: 123, chapters: [] },
+ { summary: "x", chapters: [{ title: "Bad", start: Number.NaN }] },
+ { summary: "x", chapters: [{ title: "Bad", start: 120 }] },
+ { summary: "x", chapters: [{ title: "", start: 0 }] },
+ {
+ summary: "x",
+ chapters: [
+ { title: "A", start: 10 },
+ { title: "B", start: 10 },
+ ],
+ },
+ ])("rejects malformed or invalid content", async (value) => {
+ expect((await editAiContent(videoId, { expected, value })).success).toBe(
+ false,
+ );
+ expect(mocks.write).not.toHaveBeenCalled();
+ });
+ it("allows deliberate removal and avoids writing unchanged data", async () => {
+ expect(
+ (await editAiContent(videoId, { expected, value: expected })).success,
+ ).toBe(true);
+ expect(mocks.write).not.toHaveBeenCalled();
+ expect(
+ await editAiContent(videoId, {
+ expected,
+ value: { summary: "", chapters: [] },
+ }),
+ ).toEqual({ success: true, data: { summary: "", chapters: [] } });
+ expect(writeSql).toContain("summaryManuallyEdited");
+ expect(writeSql).toContain("chaptersManuallyEdited");
+ });
+ it("reports storage failures without pretending the draft was saved", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ mocks.write.mockRejectedValueOnce(new Error("database unavailable"));
+ expect(
+ (
+ await editAiContent(videoId, {
+ expected,
+ value: { ...expected, summary: "Edited" },
+ })
+ ).success,
+ ).toBe(false);
+ expect(mocks.revalidatePath).not.toHaveBeenCalled();
+ });
+});
+
+describe("generation preserves manual content", () => {
+ it.each(["summary", "chapters"] as const)(
+ "guards %s using the current row and permits regeneration after content removal",
+ (field) => {
+ const query = new MySqlDialect().sqlToQuery(
+ setGeneratedAiContent(
+ sql`JSON_OBJECT()`,
+ field,
+ field === "summary" ? "Generated" : [],
+ ),
+ );
+ expect(query.sql).toContain("JSON_CONTAINS_PATH");
+ expect(query.sql).toContain("IF(");
+ expect(query.params).toContain(`$.${field}ManuallyEdited`);
+ expect(query.params).toContain(`$.${field}`);
+ expect(query.sql).toContain("CAST('false' AS JSON)");
+ },
+ );
+});
diff --git a/apps/web/__tests__/unit/generate-ai-start.test.ts b/apps/web/__tests__/unit/generate-ai-start.test.ts
index da945bd12..874318650 100644
--- a/apps/web/__tests__/unit/generate-ai-start.test.ts
+++ b/apps/web/__tests__/unit/generate-ai-start.test.ts
@@ -80,6 +80,20 @@ beforeEach(() => {
});
describe("startAiGeneration", () => {
+ it("queues without replacing concurrently edited metadata", async () => {
+ const update = makeUpdateChain(1);
+ mockDb
+ .mockReturnValueOnce(makeSelectChain(video))
+ .mockReturnValueOnce(update);
+ const { startAiGeneration } = await import("@/lib/generate-ai");
+ await startAiGeneration("video-1" as never, "user-1");
+ const value = update.set.mock.calls[0]?.[0];
+ expect(value.metadata.strings.join("")).toContain("JSON_SET(COALESCE(");
+ expect(value.metadata.strings.join("")).toContain(
+ "'$.aiGenerationStatus', 'QUEUED'",
+ );
+ expect(value.metadata.values).toEqual(["videos.metadata"]);
+ });
it("fails fast when no AI provider is configured", async () => {
serverEnvMock.mockReturnValue({});
diff --git a/apps/web/actions/videos/edit-ai-content.ts b/apps/web/actions/videos/edit-ai-content.ts
new file mode 100644
index 000000000..f7c1c32c7
--- /dev/null
+++ b/apps/web/actions/videos/edit-ai-content.ts
@@ -0,0 +1,136 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos } from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { and, eq, sql } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+import { z } from "zod";
+import {
+ type AiContent,
+ chaptersEqual,
+ MAX_CHAPTER_TITLE_LENGTH,
+ MAX_CHAPTERS,
+ MAX_SUMMARY_LENGTH,
+ validateAiContent,
+} from "@/lib/ai-content";
+import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
+
+const chapterSchema = z.object({
+ title: z.string().max(MAX_CHAPTER_TITLE_LENGTH),
+ start: z.number().finite().nonnegative(),
+});
+
+const aiContentSchema = z.object({
+ summary: z.string().max(MAX_SUMMARY_LENGTH),
+ chapters: z.array(chapterSchema).max(MAX_CHAPTERS),
+});
+
+const editAiContentSchema = z.object({
+ value: aiContentSchema,
+ expected: aiContentSchema,
+});
+
+type EditResult =
+ | { success: true; data: AiContent }
+ | { success: false; message: string };
+
+export async function editAiContent(
+ videoId: Video.VideoId,
+ input: unknown,
+): Promise<EditResult> {
+ const user = await getCurrentUser();
+ if (!user) return { success: false, message: "Sign in to edit this video." };
+ if (!isAiGenerationEnabledForUser(user)) {
+ return {
+ success: false,
+ message: "Cap Pro is required to edit AI content.",
+ };
+ }
+ const parsed = editAiContentSchema.safeParse(input);
+ if (typeof videoId !== "string" || !videoId || !parsed.success) {
+ return { success: false, message: "Invalid summary or chapter data." };
+ }
+ const { value, expected } = parsed.data;
+ value.summary = value.summary.trim();
+ value.chapters = value.chapters.map((chapter) => ({
+ ...chapter,
+ title: chapter.title.trim(),
+ }));
+ const summaryChanged = value.summary !== expected.summary;
+ const chaptersChanged = !chaptersEqual(value.chapters, expected.chapters);
+
+ try {
+ const result = await db().transaction(async (tx): Promise<EditResult> => {
+ const [video] = await tx
+ .select({
+ metadata: videos.metadata,
+ duration: videos.duration,
+ transcriptionStatus: videos.transcriptionStatus,
+ })
+ .from(videos)
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)))
+ .for("update");
+ if (!video) {
+ return {
+ success: false,
+ message: "You don't have permission to edit this video.",
+ };
+ }
+ const metadata = video.metadata ?? {};
+ if (
+ video.transcriptionStatus === "PROCESSING" ||
+ metadata.aiGenerationStatus === "QUEUED" ||
+ metadata.aiGenerationStatus === "PROCESSING"
+ ) {
+ return {
+ success: false,
+ message: "Wait for AI generation to finish before editing.",
+ };
+ }
+ const current = {
+ summary: metadata.summary || "",
+ chapters: metadata.chapters ?? [],
+ };
+ if (
+ (summaryChanged && current.summary !== expected.summary) ||
+ (chaptersChanged && !chaptersEqual(current.chapters, expected.chapters))
+ ) {
+ return {
+ success: false,
+ message:
+ "This content changed since you started editing. Copy your changes, then cancel and reopen the editor to load the latest version.",
+ };
+ }
+ const next = {
+ summary: summaryChanged ? value.summary : current.summary,
+ chapters: chaptersChanged ? value.chapters : current.chapters,
+ };
+ const validationError = validateAiContent(next, video.duration);
+ if (validationError) return { success: false, message: validationError };
+ let updatedMetadata = sql`COALESCE(${videos.metadata}, JSON_OBJECT())`;
+ if (summaryChanged) {
+ updatedMetadata = sql`JSON_SET(${updatedMetadata}, '$.summary', ${next.summary}, '$.summaryManuallyEdited', CAST('true' AS JSON))`;
+ }
+ if (chaptersChanged) {
+ updatedMetadata = sql`JSON_SET(${updatedMetadata}, '$.chapters', CAST(${JSON.stringify(next.chapters)} AS JSON), '$.chaptersManuallyEdited', CAST('true' AS JSON))`;
+ }
+ if (summaryChanged || chaptersChanged) {
+ await tx
+ .update(videos)
+ .set({ metadata: updatedMetadata })
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
+ }
+ return { success: true, data: next };
+ });
+ if (result.success) revalidatePath(`/s/${videoId}`);
+ return result;
+ } catch (error) {
+ console.error("Failed to edit AI content", { videoId, error });
+ return {
+ success: false,
+ message: "Couldn't save your changes. Please try again.",
+ };
+ }
+}
diff --git a/apps/web/lib/ai-content-metadata.ts b/apps/web/lib/ai-content-metadata.ts
new file mode 100644
index 000000000..dcc63ff1a
--- /dev/null
+++ b/apps/web/lib/ai-content-metadata.ts
@@ -0,0 +1,17 @@
+import { videos } from "@cap/database/schema";
+import { type SQL, sql } from "drizzle-orm";
+
+export function setGeneratedAiContent(
+ metadata: SQL,
+ field: "summary" | "chapters",
+ value: string | { title: string; start: number }[],
+) {
+ const path = `$.${field}`;
+ const editedPath = `$.${field}ManuallyEdited`;
+ return sql`IF(
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, ${editedPath})) = 'true'
+ AND JSON_CONTAINS_PATH(${videos.metadata}, 'one', ${path}),
+ ${metadata},
+ JSON_SET(${metadata}, ${path}, CAST(${JSON.stringify(value)} AS JSON), ${editedPath}, CAST('false' AS JSON))
+ )`;
+}
diff --git a/apps/web/lib/ai-content.ts b/apps/web/lib/ai-content.ts
new file mode 100644
index 000000000..08815f3c9
--- /dev/null
+++ b/apps/web/lib/ai-content.ts
@@ -0,0 +1,70 @@
+export const MAX_SUMMARY_LENGTH = 50000;
+export const MAX_CHAPTERS = 200;
+export const MAX_CHAPTER_TITLE_LENGTH = 300;
+
+export type AiContent = {
+ summary: string;
+ chapters: { title: string; start: number }[];
+};
+
+export function validateAiContent(
+ content: AiContent,
+ duration?: number | null,
+) {
+ if (content.summary.length > MAX_SUMMARY_LENGTH) {
+ return `Keep the summary under ${MAX_SUMMARY_LENGTH.toLocaleString()} characters.`;
+ }
+ if (content.chapters.length > MAX_CHAPTERS) {
+ return `Use no more than ${MAX_CHAPTERS} chapters.`;
+ }
+ for (const [index, chapter] of content.chapters.entries()) {
+ const label = `Chapter ${index + 1}`;
+ if (!chapter.title.trim()) return `${label} needs a title.`;
+ if (chapter.title.length > MAX_CHAPTER_TITLE_LENGTH) {
+ return `${label}'s title must be ${MAX_CHAPTER_TITLE_LENGTH} characters or fewer.`;
+ }
+ if (!Number.isFinite(chapter.start) || chapter.start < 0) {
+ return `${label} needs a valid timestamp (MM:SS or HH:MM:SS).`;
+ }
+ if (duration != null && duration > 0 && chapter.start >= duration) {
+ return `${label} must start before the video ends.`;
+ }
+ const previous = content.chapters[index - 1];
+ if (previous && chapter.start <= previous.start) {
+ return "Chapter timestamps must be unique and in increasing order.";
+ }
+ }
+ return null;
+}
+
+export function parseChapterTime(value: string) {
+ const match = /^(?:(\d+):)?(\d+):([0-5]\d(?:\.\d{1,3})?)$/.exec(value.trim());
+ if (!match) return Number.NaN;
+ const hours = match[1] ? Number(match[1]) : 0;
+ const minutes = Number(match[2]);
+ if (match[1] && minutes > 59) return Number.NaN;
+ return hours * 3600 + minutes * 60 + Number(match[3]);
+}
+
+export function formatChapterTime(time: number) {
+ const milliseconds = Math.round(time * 1000);
+ const hours = Math.floor(milliseconds / 3600000);
+ const minutes = Math.floor((milliseconds % 3600000) / 60000);
+ const seconds = Math.floor((milliseconds % 60000) / 1000);
+ const fraction = milliseconds % 1000;
+ return `${hours ? `${hours}:` : ""}${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}${fraction ? `.${String(fraction).padStart(3, "0").replace(/0+$/, "")}` : ""}`;
+}
+
+export function chaptersEqual(
+ left: AiContent["chapters"],
+ right: AiContent["chapters"],
+) {
+ return (
+ left.length === right.length &&
+ left.every(
+ (chapter, index) =>
+ chapter.title === right[index]?.title &&
+ chapter.start === right[index]?.start,
+ )
+ );
+}
diff --git a/apps/web/lib/generate-ai.ts b/apps/web/lib/generate-ai.ts
index 12ac36abf..d7d5aeaeb 100644
--- a/apps/web/lib/generate-ai.ts
+++ b/apps/web/lib/generate-ai.ts
@@ -89,10 +89,7 @@ export async function startAiGeneration(
const transitionResult = await db()
.update(videos)
.set({
- metadata: {
- ...metadata,
- aiGenerationStatus: "QUEUED",
- },
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.aiGenerationStatus', 'QUEUED')`,
})
.where(
and(
diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.ts
index 774844ea1..3cb97545b 100644
--- a/apps/web/workflows/generate-ai.ts
+++ b/apps/web/workflows/generate-ai.ts
@@ -15,6 +15,7 @@ import { Effect, Option } from "effect";
import { FatalError } from "workflow";
import { isAiConfigured } from "@/lib/ai/provider";
import { AiUnavailableError, runWithAiProviders } from "@/lib/ai/run";
+import { setGeneratedAiContent } from "@/lib/ai-content-metadata";
import { enqueueVideoStorageNameSync } from "@/lib/sync-video-storage-names";
import { decodeStorageVideo } from "@/lib/video-storage";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
@@ -163,7 +164,7 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {
["$.aiTitle", LEGACY_AI_TITLE_FALLBACK],
["$.summary", LEGACY_AI_SUMMARY_FALLBACK],
] as const) {
- processingMetadata = sql`IF(JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, ${metadataPath})) = ${fallback}, JSON_REMOVE(${processingMetadata}, ${metadataPath}), ${processingMetadata})`;
+ processingMetadata = sql`IF(JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, ${metadataPath})) = ${fallback} AND (${metadataPath} <> '$.summary' OR COALESCE(JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.summaryManuallyEdited')), 'false') <> 'true'), JSON_REMOVE(${processingMetadata}, ${metadataPath}), ${processingMetadata})`;
}
await db()
@@ -376,10 +377,18 @@ async function saveResults(
metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.aiTitle', ${generatedTitle})`;
}
if (result.summary) {
- metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.summary', ${result.summary})`;
+ metadataUpdate = setGeneratedAiContent(
+ metadataUpdate,
+ "summary",
+ result.summary,
+ );
}
if (result.chapters) {
- metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.chapters', CAST(${JSON.stringify(result.chapters)} AS JSON))`;
+ metadataUpdate = setGeneratedAiContent(
+ metadataUpdate,
+ "chapters",
+ result.chapters,
+ );
}
metadataUpdate = sql`JSON_SET(${metadataUpdate}, '$.aiGenerationStatus', 'COMPLETE')`;
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index aa846dad2..082c9ed56 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -53,10 +53,12 @@ export interface VideoMetadata {
* AI generated summary of the content
*/
summary?: string;
+ summaryManuallyEdited?: boolean;
/**
* Chapter markers generated from the transcript
*/
chapters?: { title: string; start: number }[];
+ chaptersManuallyEdited?: boolean;
aiGenerationStatus?:
| "QUEUED"
| "PROCESSING"