Skip to content

Conversation

AppleLamps
Copy link

@AppleLamps AppleLamps commented Sep 1, 2025

Description

Please include a summary of the changes and the related issue. Please also include relevant motivation and context.

Fixes # (issue)

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Performance improvement
  • Code refactoring
  • Tests

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • Test A
  • Test B

Test Configuration:

  • Node version:
  • Browser (if applicable):
  • Operating System:

Screenshots (if applicable)

Add screenshots to help explain your changes.

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have added screenshots if ui has been changed
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Additional context

Add any other context about the pull request here.

Summary by CodeRabbit

  • New Features

    • Per-project media thumbnails are now persisted and automatically loaded when available.
    • Video thumbnails are generated in the background if missing and saved for future sessions.
    • Added ability to save media thumbnails directly, improving thumbnail accuracy and consistency.
  • Refactor

    • Editor panels load on demand with lightweight placeholders, improving initial load performance.
    • Timeline and previews use stored thumbnails instead of regenerating them synchronously.
    • Media loading no longer blocks the UI; thumbnails appear progressively as they become available.

Copy link

vercel bot commented Sep 1, 2025

@AppleLamps is attempting to deploy a commit to the OpenCut OSS Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

netlify bot commented Sep 1, 2025

👷 Deploy request for appcut pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 2ac1b45

Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Replaces editor panel static imports with dynamic client imports. Adds thumbnail support to storage: new thumbnails adapter, metadata flag, save/load/delete integrations, and a new saveMediaThumbnail API. Media loading now defers video thumbnail generation to background tasks and persists them. Timeline thumbnail sourcing now uses stored mediaFile.thumbnailUrl without preloading all media.

Changes

Cohort / File(s) Summary
Editor dynamic imports
apps/web/src/app/editor/[project_id]/page.tsx
Switched four panel components to next/dynamic with SSR disabled and simple loading fallbacks; usage unchanged.
Storage & types (thumbnails support)
apps/web/src/lib/storage/storage-service.ts, apps/web/src/lib/storage/types.ts
Introduced per-project OPFS thumbnails adapter; persisted hasThumbnail flag; save/load/delete now manage thumbnails; added saveMediaThumbnail(projectId, id, blob); load surfaces thumbnailUrl when available; types extended with hasThumbnail?.
Media store background thumbnailing
apps/web/src/stores/media-store.ts
loadProjectMedia now sets items immediately, then asynchronously generates thumbnails for videos missing thumbnailUrl; persists via storageService.saveMediaThumbnail; updates in-memory items; removed synchronous width/height propagation; uses non-blocking Promise.allSettled.
Timeline thumbnail sourcing
apps/web/src/stores/timeline-store.ts
Removed bulk media preload; picks earliest media element; uses mediaFile.thumbnailUrl for videos or url for images; simplified control flow and null-safe returns.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant MS as MediaStore
  participant SS as StorageService
  participant OPFS as Thumbnails Adapter

  U->>MS: loadProjectMedia(projectId)
  MS->>SS: loadProjectMedia(projectId)
  SS-->>MS: mediaFiles (may include thumbnailUrl)
  MS-->>U: set mediaFiles immediately (UI renders)

  par For each video without thumbnailUrl
    MS->>MS: generateThumbnail(item)
    MS->>SS: saveMediaThumbnail(projectId, id, blob)
    SS->>OPFS: put(thumbnail blob)
    SS-->>MS: ack
    MS-->>U: update in-memory item.thumbnailUrl
  and On errors
    MS-->>MS: log warning/error
  end
Loading
sequenceDiagram
  autonumber
  participant TS as TimelineStore
  participant SS as StorageService

  TS->>SS: loadMediaFile(projectId, mediaId)
  SS-->>TS: { url, type, thumbnailUrl? }
  alt type == "image"
    TS-->>TS: use url as thumbnail
  else type == "video" and thumbnailUrl exists
    TS-->>TS: use thumbnailUrl
  else
    TS-->>TS: return null (no thumbnail)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I hop through thumbs and timelines bright,
Stashing tiny pics in moonlit byte,
Panels load with airy cheer,
While backgrounds hum and make them clear.
A nibble of OPFS delight—
Thump-thump, the edits feel just right! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/web/src/lib/storage/storage-service.ts (1)

132-169: Avoid metadata/thumb drift; set hasThumbnail only after persistence succeeds.

Currently hasThumbnail is derived from a runtime URL; if fetch/set fails, metadata stays true while no blob exists. Flip the order and update after success. Also check Response.ok before reading the blob.

   // Save metadata to project-specific IndexedDB
-  const metadata: MediaFileData = {
+  const metadata: MediaFileData = {
     id: mediaItem.id,
     name: mediaItem.name,
     type: mediaItem.type,
     size: mediaItem.file.size,
     lastModified: mediaItem.file.lastModified,
     width: mediaItem.width,
     height: mediaItem.height,
     duration: mediaItem.duration,
     ephemeral: mediaItem.ephemeral,
-    hasThumbnail: Boolean(mediaItem.thumbnailUrl),
+    // Only mark true after we persist the blob successfully
+    hasThumbnail: false,
   };
 
   await mediaMetadataAdapter.set(mediaItem.id, metadata);
 
-  if (mediaItem.thumbnailUrl) {
+  if (mediaItem.thumbnailUrl) {
     try {
-      const res = await fetch(mediaItem.thumbnailUrl);
+      const res = await fetch(mediaItem.thumbnailUrl);
+      if (!res.ok) throw new Error(`Thumbnail fetch failed: ${res.status}`);
       const blob = await res.blob();
       const thumbFile = new File([blob], `${mediaItem.id}.jpg`, {
         type: blob.type || "image/jpeg",
       });
       await mediaThumbnailsAdapter.set(mediaItem.id, thumbFile);
+      await mediaMetadataAdapter.set(mediaItem.id, {
+        ...metadata,
+        hasThumbnail: true,
+      });
     } catch (e) {
       console.error("Failed to persist media thumbnail:", e);
     }
   }
🧹 Nitpick comments (5)
apps/web/src/lib/storage/types.ts (1)

23-25: Clarify persistence semantics of hasThumbnail.

Add a short doc so callers know this flag means “persisted in OPFS,” not just “had a runtime data URL.”

 export interface MediaFileData {
   id: string;
   name: string;
   type: "image" | "video" | "audio";
   size: number;
   lastModified: number;
   width?: number;
   height?: number;
   duration?: number;
   ephemeral?: boolean;
   sourceStickerIconName?: string;
+  /** True only when a thumbnail blob has been persisted in OPFS for this item. */
   hasThumbnail?: boolean;
   // File will be stored separately in OPFS
 }
apps/web/src/app/editor/[project_id]/page.tsx (2)

11-14: Remove commented-out static imports.

Dead commented code adds noise.

-// import { MediaPanel } from "@/components/editor/media-panel";
-// import { PropertiesPanel } from "@/components/editor/properties-panel";
-// import { Timeline } from "@/components/editor/timeline";
-// import { PreviewPanel } from "@/components/editor/preview-panel";

22-49: DRY the dynamic() boilerplate (optional).

A tiny helper eliminates repetition across the four panels.

+const clientOnly = (
+  loader: () => Promise<{ default: React.ComponentType<any> }>
+) => dynamic(loader, { ssr: false, loading: () => <div className="w-full h-full bg-panel" /> });
+
-const Timeline = dynamic(
-  () =>
-    import("@/components/editor/timeline").then((m) => ({
-      default: m.Timeline,
-    })),
-  { ssr: false, loading: () => <div className="w-full h-full bg-panel" /> }
-);
+const Timeline = clientOnly(() =>
+  import("@/components/editor/timeline").then((m) => ({ default: m.Timeline }))
+);
 
-const PreviewPanel = dynamic(
-  () =>
-    import("@/components/editor/preview-panel").then((m) => ({
-      default: m.PreviewPanel,
-    })),
-  { ssr: false, loading: () => <div className="w-full h-full bg-panel" /> }
-);
+const PreviewPanel = clientOnly(() =>
+  import("@/components/editor/preview-panel").then((m) => ({ default: m.PreviewPanel }))
+);
 
-const MediaPanel = dynamic(
-  () =>
-    import("@/components/editor/media-panel").then((m) => ({
-      default: m.MediaPanel,
-    })),
-  { ssr: false, loading: () => <div className="w-full h-full bg-panel" /> }
-);
+const MediaPanel = clientOnly(() =>
+  import("@/components/editor/media-panel").then((m) => ({ default: m.MediaPanel }))
+);
 
-const PropertiesPanel = dynamic(
-  () =>
-    import("@/components/editor/properties-panel").then((m) => ({
-      default: m.PropertiesPanel,
-    })),
-  { ssr: false, loading: () => <div className="w-full h-full bg-panel" /> }
-);
+const PropertiesPanel = clientOnly(() =>
+  import("@/components/editor/properties-panel").then((m) => ({ default: m.PropertiesPanel }))
+);
apps/web/src/stores/timeline-store.ts (1)

1243-1251: Potential object URL lifetime leak.

loadMediaFile returns a blob URL for stored thumbnails; getProjectThumbnail forwards it. Nothing revokes that URL later. Consider returning a cached URL + a dispose, or documenting that the consumer must revoke. Alternatively, add a tiny cache in storageService for project thumbnails and revoke on next refresh.

apps/web/src/lib/storage/storage-service.ts (1)

275-293: Thumb save API is clear; consider idempotence note.

If called repeatedly it overwrites, which is fine. Optionally short-circuit when identical sizes or hashes match, but not required now.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 37d4014 and 2ac1b45.

📒 Files selected for processing (5)
  • apps/web/src/app/editor/[project_id]/page.tsx (1 hunks)
  • apps/web/src/lib/storage/storage-service.ts (6 hunks)
  • apps/web/src/lib/storage/types.ts (1 hunks)
  • apps/web/src/stores/media-store.ts (1 hunks)
  • apps/web/src/stores/timeline-store.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use TypeScript namespaces.
Don't use non-null assertions with the ! postfix operator.
Don't use parameter properties in class constructors.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use either T[] or Array<T> consistently.
Initialize each enum member value explicitly.
Use export type for types.
Use import type for types.
Make sure all enum members are literal values.
Don't use TypeScript const enum.
Don't declare empty interfaces.
Don't let variables evolve into any type through reassignments.
Don't use the any type.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use implicit any type on variable declarations.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use the TypeScript directive @ts-ignore.
Use consistent accessibility modifiers on class properties and methods.
Use function types instead of object types with call signatures.
Don't use void type outside of generic or return types.

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Use either T[] or Array consistently
Don't use the any type

Files:

  • apps/web/src/lib/storage/types.ts
  • apps/web/src/stores/media-store.ts
  • apps/web/src/app/editor/[project_id]/page.tsx
  • apps/web/src/lib/storage/storage-service.ts
  • apps/web/src/stores/timeline-store.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,jsx,ts,tsx}: Don't use the return value of React.render.
Don't use consecutive spaces in regular expression literals.
Don't use the arguments object.
Don't use primitive type aliases or misleading types.
Don't use the comma operator.
Don't write functions that exceed a given Cognitive Complexity score.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names that aren't base 10 or use underscore separators.
Remove redundant terms from logical expressions.
Use while loops instead of...

Files:

  • apps/web/src/lib/storage/types.ts
  • apps/web/src/stores/media-store.ts
  • apps/web/src/app/editor/[project_id]/page.tsx
  • apps/web/src/lib/storage/storage-service.ts
  • apps/web/src/stores/timeline-store.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{ts,tsx,js,jsx}: Don't use the comma operator
Use for...of statements instead of Array.forEach
Don't initialize variables to undefined
Use .flatMap() instead of map().flat() when possible
Don't assign a value to itself
Avoid unused imports and variables
Don't use await inside loops
Don't hardcode sensitive data like API keys and tokens
Don't use the delete operator
Don't use global eval()
Use String.slice() instead of String.substr() and String.substring()
Don't use else blocks when the if block breaks early
Put default function parameters and optional function parameters last
Use new when throwing an error
Use String.trimStart() and String.trimEnd() over String.trimLeft() and String.trimRight()

Files:

  • apps/web/src/lib/storage/types.ts
  • apps/web/src/stores/media-store.ts
  • apps/web/src/app/editor/[project_id]/page.tsx
  • apps/web/src/lib/storage/storage-service.ts
  • apps/web/src/stores/timeline-store.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{jsx,tsx}: Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Don't use distracting elements like <marquee> or <blink>.
Only use the scope prop on <th> elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Use semantic elements instead of role attributes in JSX.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with...

Files:

  • apps/web/src/app/editor/[project_id]/page.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{tsx,jsx}: Always include a title element for icons unless there's text beside the icon
Always include a type attribute for button elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Don't import React itself
Don't define React components inside other components
Don't use both children and dangerouslySetInnerHTML on the same element
Don't insert comments as text nodes
Use <>...</> instead of ...

Files:

  • apps/web/src/app/editor/[project_id]/page.tsx
🧬 Code graph analysis (3)
apps/web/src/stores/media-store.ts (2)
apps/web/src/lib/storage/opfs-adapter.ts (1)
  • set (30-37)
apps/web/src/lib/storage/indexeddb-adapter.ts (1)
  • set (42-52)
apps/web/src/app/editor/[project_id]/page.tsx (4)
apps/web/src/components/editor/timeline/index.tsx (1)
  • Timeline (71-910)
apps/web/src/components/editor/preview-panel.tsx (1)
  • PreviewPanel (39-664)
apps/web/src/components/editor/media-panel/index.tsx (1)
  • MediaPanel (13-52)
apps/web/src/components/editor/properties-panel/index.tsx (1)
  • PropertiesPanel (11-53)
apps/web/src/lib/storage/storage-service.ts (2)
apps/web/src/lib/storage/opfs-adapter.ts (1)
  • OPFSAdapter (3-73)
apps/web/src/types/media.ts (1)
  • MediaFile (4-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Vade Review
🔇 Additional comments (7)
apps/web/src/app/editor/[project_id]/page.tsx (1)

22-49: Client-only dynamic panels look good.

Correct use of next/dynamic with ssr: false and simple fallbacks.

apps/web/src/stores/timeline-store.ts (1)

1234-1235: Graceful null check on timeline load.

Returning null when no stored tracks is fine.

apps/web/src/lib/storage/storage-service.ts (3)

49-55: Adapters composition looks solid.

Per-project OPFS dir for files and thumbnails + IndexedDB for metadata is a good split.


205-216: Good: tolerant load when thumb metadata is stale.

Warn and continue if the thumb blob is missing.


247-258: Atomic deletion across stores looks good.

OPFSAdapter.remove already ignores NotFound; Promise.all keeps it fast.

apps/web/src/stores/media-store.ts (2)

229-231: Fast-path state set is the right UX tradeoff.

Immediate render with persisted data keeps UI snappy.


260-261: Background execution via allSettled is appropriate.

Non-blocking thumbnail enrichment matches the new flow.

Comment on lines +233 to 258
const missing = mediaItems.filter(
(item) => item.type === "video" && !item.thumbnailUrl && item.file
);

const tasks = missing.map((item) =>
(async () => {
try {
const { thumbnailUrl } = await generateVideoThumbnail(item.file);
const res = await fetch(thumbnailUrl);
const blob = await res.blob();

await storageService.saveMediaThumbnail(projectId, item.id, blob);

set((state) => ({
mediaFiles: state.mediaFiles.map((m) =>
m.id === item.id ? { ...m, thumbnailUrl } : m
),
}));
} catch (error) {
console.error(
`Failed to generate thumbnail for video ${item.id}:`,
error
);
}
return item;
})
})()
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Don’t gate in-memory thumbnail update on persistence.

If OPFS isn’t available (Safari/older browsers) saveMediaThumbnail will fail and you’ll never display the generated thumbnail. Update state regardless; keep persistence best-effort.

-      const tasks = missing.map((item) =>
-        (async () => {
-          try {
-            const { thumbnailUrl } = await generateVideoThumbnail(item.file);
-            const res = await fetch(thumbnailUrl);
-            const blob = await res.blob();
-
-            await storageService.saveMediaThumbnail(projectId, item.id, blob);
-
-            set((state) => ({
-              mediaFiles: state.mediaFiles.map((m) =>
-                m.id === item.id ? { ...m, thumbnailUrl } : m
-              ),
-            }));
-          } catch (error) {
-            console.error(
-              `Failed to generate thumbnail for video ${item.id}:`,
-              error
-            );
-          }
-        })()
-      );
+      const tasks = missing.map((item) =>
+        (async () => {
+          const { thumbnailUrl } = await generateVideoThumbnail(item.file);
+          try {
+            const res = await fetch(thumbnailUrl);
+            const blob = await res.blob();
+            await storageService.saveMediaThumbnail(projectId, item.id, blob);
+          } catch (error) {
+            console.error(
+              `Failed to generate thumbnail for video ${item.id}:`,
+              error
+            );
+          } finally {
+            set((state) => ({
+              mediaFiles: state.mediaFiles.map((m) =>
+                m.id === item.id ? { ...m, thumbnailUrl } : m
+              ),
+            }));
+          }
+        })()
+      );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const missing = mediaItems.filter(
(item) => item.type === "video" && !item.thumbnailUrl && item.file
);
const tasks = missing.map((item) =>
(async () => {
try {
const { thumbnailUrl } = await generateVideoThumbnail(item.file);
const res = await fetch(thumbnailUrl);
const blob = await res.blob();
await storageService.saveMediaThumbnail(projectId, item.id, blob);
set((state) => ({
mediaFiles: state.mediaFiles.map((m) =>
m.id === item.id ? { ...m, thumbnailUrl } : m
),
}));
} catch (error) {
console.error(
`Failed to generate thumbnail for video ${item.id}:`,
error
);
}
return item;
})
})()
);
const missing = mediaItems.filter(
(item) => item.type === "video" && !item.thumbnailUrl && item.file
);
const tasks = missing.map((item) =>
(async () => {
const { thumbnailUrl } = await generateVideoThumbnail(item.file);
try {
const res = await fetch(thumbnailUrl);
const blob = await res.blob();
await storageService.saveMediaThumbnail(projectId, item.id, blob);
} catch (error) {
console.error(
`Failed to generate thumbnail for video ${item.id}:`,
error
);
} finally {
set((state) => ({
mediaFiles: state.mediaFiles.map((m) =>
m.id === item.id ? { ...m, thumbnailUrl } : m
),
}));
}
})()
);
🤖 Prompt for AI Agents
In apps/web/src/stores/media-store.ts around lines 233 to 258, the current flow
waits for storageService.saveMediaThumbnail to succeed before updating in-memory
state, which means a failed persistence (e.g. OPFS absent) prevents the
generated thumbnail from being shown; change the order so you immediately update
state with the new thumbnailUrl (set state before attempting persistence) and
then call saveMediaThumbnail as a best-effort asynchronous operation inside its
own try/catch so failures are logged but do not prevent UI update.

);
return item;
}
// Fast path: immediately set items (use persisted thumbnails if available)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory leak in generateVideoThumbnail function - the object URL created for the video element is never revoked, causing memory to accumulate with each thumbnail generation.

View Details
📝 Patch Details
diff --git a/apps/web/src/stores/media-store.ts b/apps/web/src/stores/media-store.ts
index 0e2add9..0244aa0 100644
--- a/apps/web/src/stores/media-store.ts
+++ b/apps/web/src/stores/media-store.ts
@@ -47,11 +47,13 @@ export const getImageDimensions = (
       const width = img.naturalWidth;
       const height = img.naturalHeight;
       resolve({ width, height });
+      URL.revokeObjectURL(img.src);
       img.remove();
     });
 
     img.addEventListener("error", () => {
       reject(new Error("Could not load image"));
+      URL.revokeObjectURL(img.src);
       img.remove();
     });
 
@@ -90,12 +92,14 @@ export const generateVideoThumbnail = (
       resolve({ thumbnailUrl, width, height });
 
       // Cleanup
+      URL.revokeObjectURL(video.src);
       video.remove();
       canvas.remove();
     });
 
     video.addEventListener("error", () => {
       reject(new Error("Could not load video"));
+      URL.revokeObjectURL(video.src);
       video.remove();
       canvas.remove();
     });
@@ -114,11 +118,13 @@ export const getMediaDuration = (file: File): Promise<number> => {
 
     element.addEventListener("loadedmetadata", () => {
       resolve(element.duration);
+      URL.revokeObjectURL(element.src);
       element.remove();
     });
 
     element.addEventListener("error", () => {
       reject(new Error("Could not load media"));
+      URL.revokeObjectURL(element.src);
       element.remove();
     });
 

Analysis

The generateVideoThumbnail function creates an object URL on line 103 using URL.createObjectURL(file) to load the video for thumbnail generation, but this URL is never revoked with URL.revokeObjectURL().

Object URLs consume memory until they are explicitly revoked or the document is closed. Since this function is called in background tasks for each video file that needs a thumbnail generated (line 240), and potentially multiple times during a user session, this will cause memory to accumulate over time.

The cleanup code on lines 93-94 and 99-100 only removes the DOM elements but doesn't handle the object URL cleanup. The fix is to add URL.revokeObjectURL(video.src) before removing the video element in both the success and error cleanup paths.

This memory leak will be particularly problematic in long-running editor sessions where users work with multiple video files, as each thumbnail generation will leave behind an unreleased object URL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant