Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat(web): sync latest web and desktop updates

Augustus Otu128d99b7d1b8
diff --git a/.gitignore b/.gitignore
index 442e4121..1403634b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,12 +44,15 @@ coverage/
.docs/
docs/*
!docs/superpowers/
+!docs/android-port/
.worktrees/
# Project-specific
/public/projects/
*.openreel
!apps/desktop/crates/openreel-project/tests/fixtures/*.openreel
-apps/cloud/
+apps/cloud/node_modules/
+apps/cloud/dist/
+apps/cloud/.wrangler/
apps/ios
apps/android
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 9a61cf54..24b086d5 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "@openreel/desktop",
"private": true,
- "version": "1.0.0-alpha.10",
+ "version": "1.0.0-alpha.16",
"type": "commonjs",
"main": "dist/main/index.js",
"bin": {
diff --git a/apps/desktop/src/main/gpu/instance-id.ts b/apps/desktop/src/main/gpu/instance-id.ts
deleted file mode 100644
index a28821cb..00000000
--- a/apps/desktop/src/main/gpu/instance-id.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { promises as fs } from "node:fs";
-import { randomUUID } from "node:crypto";
-import path from "node:path";
-import { getKeyStore } from "../ipc/keychain";
-
-const INSTANCE_ID_KEY = "gpu-instance-id";
-
-export async function getOrCreateInstanceId(): Promise<string> {
- const store = getKeyStore();
- try {
- const existing = await store.get(INSTANCE_ID_KEY);
- if (existing) return existing;
- const id = randomUUID();
- await store.set(INSTANCE_ID_KEY, id);
- return id;
- } catch {
- const { app } = require("electron") as typeof import("electron");
- const file = path.join(app.getPath("userData"), "openreel-gpu-instance.txt");
- try {
- const fromFile = (await fs.readFile(file, "utf8")).trim();
- if (fromFile) return fromFile;
- } catch {}
- const id = randomUUID();
- await fs.writeFile(file, id, { mode: 0o600 });
- return id;
- }
-}
diff --git a/apps/desktop/src/main/gpu/job-client.test.ts b/apps/desktop/src/main/gpu/job-client.test.ts
deleted file mode 100644
index 04df25f8..00000000
--- a/apps/desktop/src/main/gpu/job-client.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { GpuJobClient, normalizePresign } from "./job-client";
-
-function jsonRes(body: unknown, init: { ok?: boolean; status?: number } = {}): Response {
- return {
- ok: init.ok ?? true,
- status: init.status ?? 200,
- json: async () => body,
- headers: new Headers(),
- } as unknown as Response;
-}
-
-describe("desktop GpuJobClient", () => {
- it("normalizes optional download URL aliases", () => {
- const out = normalizePresign({
- putUrl: "https://r2/put",
- objectKey: "jobs/export.mp4",
- getUrl: "https://r2/get",
- });
- expect(out.downloadUrl).toBe("https://r2/get");
- });
-
- it("uploads ArrayBuffer bytes without copying into a second Uint8Array", async () => {
- const fetchFn = vi
- .fn()
- .mockResolvedValueOnce(
- jsonRes({
- putUrl: "https://r2/put",
- objectKey: "jobs/export.mp4",
- downloadUrl: "https://r2/get",
- }),
- )
- .mockResolvedValueOnce({
- ok: true,
- status: 200,
- headers: new Headers(),
- } as unknown as Response);
- const client = new GpuJobClient({
- gpuBaseUrl: "https://gpu",
- brokerBaseUrl: "https://broker",
- bundleId: "com.openreel.video",
- tokenProvider: {
- getToken: vi.fn().mockResolvedValue("tok"),
- invalidate: vi.fn(),
- },
- fetchFn,
- });
-
- const bytes = new ArrayBuffer(3);
- new Uint8Array(bytes).set([1, 2, 3]);
- const result = await client.uploadBytes({
- bytes,
- filename: "export.mp4",
- contentType: "video/mp4",
- });
-
- expect(result).toEqual({
- mediaKey: "jobs/export.mp4",
- downloadUrl: "https://r2/get",
- });
- const put = fetchFn.mock.calls[1];
- expect(put[0]).toBe("https://r2/put");
- expect(put[1].body).toBeInstanceOf(Uint8Array);
- expect((put[1].body as Uint8Array).buffer).toBe(bytes);
- });
-});
diff --git a/apps/desktop/src/main/gpu/job-client.ts b/apps/desktop/src/main/gpu/job-client.ts
deleted file mode 100644
index 79d361e8..00000000
--- a/apps/desktop/src/main/gpu/job-client.ts
+++ /dev/null
@@ -1,206 +0,0 @@
-import { readFile, writeFile } from "node:fs/promises";
-
-export interface NormalizedPresign {
- uploadUrl: string;
- mediaKey: string;
- downloadUrl?: string;
- headers: Record<string, string>;
-}
-
-export function normalizePresign(raw: Record<string, unknown>): NormalizedPresign {
- const uploadUrl = (raw.uploadURL ?? raw.putUrl) as string | undefined;
- const mediaKey = (raw.mediaKey ?? raw.objectKey) as string | undefined;
- if (!uploadUrl || !mediaKey) {
- throw new Error("presign response missing uploadURL/putUrl or mediaKey/objectKey");
- }
- const downloadUrl = (raw.getUrl ?? raw.downloadURL ?? raw.downloadUrl) as string | undefined;
- const headers = (raw.headers as Record<string, string> | undefined) ?? {};
- return { uploadUrl, mediaKey, downloadUrl, headers };
-}
-
-export interface SubmitArgs {
- kind: string;
- params: Record<string, unknown>;
- mediaKey?: string;
- mediaFilename?: string;
-}
-
-export function buildSubmitBody(args: SubmitArgs): { body: string; contentType: string } {
- const request = { kind: args.kind, params: args.params };
- if (args.mediaKey) {
- return {
- body: JSON.stringify({ request, mediaKey: args.mediaKey, mediaFilename: args.mediaFilename }),
- contentType: "application/json",
- };
- }
- return { body: JSON.stringify(request), contentType: "application/json" };
-}
-
-export interface GpuJobClientDeps {
- gpuBaseUrl: string;
- brokerBaseUrl: string;
- bundleId: string;
- tokenProvider: { getToken(): Promise<string>; invalidate(): void };
- fetchFn?: typeof fetch;
- tempFilePath?: (ext: string) => Promise<string>;
-}
-
-export interface GpuJobStatus {
- jobID: string;
- status: string;
- progress?: number;
- message?: string;
- manifestURL?: string;
- error?: string;
- queuePosition?: number;
- pendingAhead?: number;
-}
-
-export interface GpuJobCreated {
- jobID: string;
- status: string;
- manifestURL?: string;
-}
-
-export class GpuRetryableError extends Error {
- constructor(
- message: string,
- readonly status: number,
- readonly retryAfterSeconds?: number,
- ) {
- super(message);
- this.name = "GpuRetryableError";
- }
-}
-
-export class GpuJobClient {
- constructor(private readonly deps: GpuJobClientDeps) {}
-
- private get fetchFn(): typeof fetch {
- return this.deps.fetchFn ?? fetch;
- }
-
- private async authHeaders(): Promise<Record<string, string>> {
- const token = await this.deps.tokenProvider.getToken();
- return {
- Authorization: `Bearer ${token}`,
- "X-Bundle-ID": this.deps.bundleId,
- Accept: "application/json",
- };
- }
-
- private async authedFetch(url: string, init: RequestInit): Promise<Response> {
- const headers = { ...(init.headers as Record<string, string>), ...(await this.authHeaders()) };
- let res = await this.fetchFn(url, { ...init, headers });
- if (res.status === 401) {
- this.deps.tokenProvider.invalidate();
- const retryHeaders = { ...(init.headers as Record<string, string>), ...(await this.authHeaders()) };
- res = await this.fetchFn(url, { ...init, headers: retryHeaders });
- }
- return res;
- }
-
- async uploadMedia(args: { srcPath: string; filename: string; contentType?: string }): Promise<{ mediaKey: string; downloadUrl?: string }> {
- const bytes = await readFile(args.srcPath);
- return this.uploadBytes({
- bytes: new Uint8Array(bytes),
- filename: args.filename,
- contentType: args.contentType,
- });
- }
-
- async uploadBytes(args: {
- bytes: Uint8Array | ArrayBuffer | ArrayBufferView;
- filename: string;
- contentType?: string;
- }): Promise<{ mediaKey: string; downloadUrl?: string }> {
- const presignRes = await this.authedFetch(`${this.deps.brokerBaseUrl}/auth/upload-url`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ filename: args.filename, contentType: args.contentType }),
- });
- if (!presignRes.ok) {
- throw new Error(`presign failed: ${presignRes.status}`);
- }
- const presign = normalizePresign((await presignRes.json()) as Record<string, unknown>);
- const body =
- args.bytes instanceof Uint8Array
- ? args.bytes
- : args.bytes instanceof ArrayBuffer
- ? new Uint8Array(args.bytes)
- : new Uint8Array(args.bytes.buffer, args.bytes.byteOffset, args.bytes.byteLength);
- const putHeaders: Record<string, string> = { ...presign.headers };
- if (!putHeaders["Content-Type"] && !putHeaders["content-type"] && args.contentType) {
- putHeaders["Content-Type"] = args.contentType;
- }
- const putRes = await this.fetchFn(presign.uploadUrl, {
- method: "PUT",
- headers: putHeaders,
- body: body as unknown as BodyInit,
- });
- if (!putRes.ok) {
- throw new Error(`upload PUT failed: ${putRes.status}`);
- }
- return { mediaKey: presign.mediaKey, downloadUrl: presign.downloadUrl };
- }
-
- async submitJob(args: SubmitArgs): Promise<GpuJobCreated> {
- const { body, contentType } = buildSubmitBody(args);
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs`, {
- method: "POST",
- headers: { "Content-Type": contentType },
- body,
- });
- if (res.status === 503) {
- const retryAfter = Number(res.headers.get("retry-after"));
- throw new GpuRetryableError("queue full", 503, Number.isFinite(retryAfter) ? retryAfter : undefined);
- }
- if (!res.ok) {
- throw new Error(`submit failed: ${res.status}`);
- }
- return (await res.json()) as GpuJobCreated;
- }
-
- async jobStatus(jobID: string): Promise<GpuJobStatus> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}`, { method: "GET" });
- if (!res.ok) {
- throw new GpuRetryableError(`status failed: ${res.status}`, res.status);
- }
- return (await res.json()) as GpuJobStatus;
- }
-
- async fetchManifest(jobID: string): Promise<Record<string, unknown>> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}/manifest`, { method: "GET" });
- if (!res.ok) {
- throw new Error(`manifest failed: ${res.status}`);
- }
- return (await res.json()) as Record<string, unknown>;
- }
-
- async downloadArtifact(jobID: string, relativePath: string): Promise<{ tempPath: string; mime: string }> {
- if (!this.deps.tempFilePath) {
- throw new Error("tempFilePath dependency not provided");
- }
- const res = await this.authedFetch(
- `${this.deps.gpuBaseUrl}/jobs/${jobID}/artifacts/${relativePath}`,
- { method: "GET" },
- );
- if (!res.ok) {
- throw new Error(`artifact download failed: ${res.status}`);
- }
- const mime = res.headers.get("content-type") ?? "application/octet-stream";
- const ext = relativePath.split(".").pop() ?? "bin";
- const tempPath = await this.deps.tempFilePath(ext);
- const buffer = Buffer.from(await res.arrayBuffer());
- await writeFile(tempPath, buffer);
- return { tempPath, mime };
- }
-
- async cancelJob(jobID: string): Promise<GpuJobStatus> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}`, { method: "DELETE" });
- if (!res.ok) {
- throw new Error(`cancel failed: ${res.status}`);
- }
- return (await res.json()) as GpuJobStatus;
- }
-}
diff --git a/apps/desktop/src/main/gpu/token-provider.ts b/apps/desktop/src/main/gpu/token-provider.ts
deleted file mode 100644
index 79b19a36..00000000
--- a/apps/desktop/src/main/gpu/token-provider.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-export interface TokenProviderDeps {
- brokerBaseUrl: string;
- bundleId: string;
- instanceId: string;
- fetchFn?: typeof fetch;
- now?: () => number;
-}
-
-interface CachedToken {
- token: string;
- exp: number;
-}
-
-const REFRESH_LEEWAY_SECONDS = 60;
-
-export class GpuTokenProvider {
- private cached: CachedToken | null = null;
- private inflight: Promise<string> | null = null;
-
- constructor(private readonly deps: TokenProviderDeps) {}
-
- invalidate(): void {
- this.cached = null;
- }
-
- async getToken(): Promise<string> {
- if (this.cached && this.cached.exp - this.nowSeconds() > REFRESH_LEEWAY_SECONDS) {
- return this.cached.token;
- }
- if (this.inflight) {
- return this.inflight;
- }
- this.inflight = this.mint().finally(() => {
- this.inflight = null;
- });
- return this.inflight;
- }
-
- private nowSeconds(): number {
- return Math.floor((this.deps.now ? this.deps.now() : Date.now()) / 1000);
- }
-
- private get fetchFn(): typeof fetch {
- return this.deps.fetchFn ?? fetch;
- }
-
- private headers(): Record<string, string> {
- return {
- "Content-Type": "application/json",
- Accept: "application/json",
- "X-Bundle-ID": this.deps.bundleId,
- };
- }
-
- private async mint(): Promise<string> {
- const challengeRes = await this.fetchFn(`${this.deps.brokerBaseUrl}/auth/challenge`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform: "desktop", instanceId: this.deps.instanceId }),
- });
- if (!challengeRes.ok) {
- throw new Error(`auth challenge failed: ${challengeRes.status}`);
- }
- const challenge = (await challengeRes.json()) as { challengeId?: string };
- if (!challenge.challengeId) {
- throw new Error("auth challenge missing challengeId");
- }
-
- const tokenRes = await this.fetchFn(`${this.deps.brokerBaseUrl}/auth/token`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform: "desktop", challengeId: challenge.challengeId }),
- });
- if (!tokenRes.ok) {
- throw new Error(`auth token mint failed: ${tokenRes.status}`);
- }
- const minted = (await tokenRes.json()) as { token?: string; exp?: number };
- if (!minted.token || typeof minted.exp !== "number") {
- throw new Error("auth token response malformed");
- }
- this.cached = { token: minted.token, exp: minted.exp };
- return minted.token;
- }
-}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 8f57b88e..07714403 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -23,9 +23,6 @@ import {
} from "./ipc/aurora";
import { getKeyStore } from "./ipc/keychain";
import { cloudFetch } from "./ipc/cloud";
-import { GpuTokenProvider } from "./gpu/token-provider";
-import { GpuJobClient } from "./gpu/job-client";
-import { getOrCreateInstanceId } from "./gpu/instance-id";
import { applyWindowControl, windowIsMaximized } from "./window-controls";
import { installApplicationMenu, sendMenuAction } from "./app-menu";
import { attachUnsavedGuard, markQuitting } from "./lifecycle";
@@ -80,11 +77,6 @@ import {
rigHumanoidModelArgsSchema,
rigHumanoidModelResultSchema,
cloudFetchArgsSchema,
- gpuUploadMediaArgsSchema,
- gpuUploadExportArgsSchema,
- gpuSubmitJobArgsSchema,
- gpuJobIdArgsSchema,
- gpuArtifactArgsSchema,
windowControlArgsSchema,
} from "../shared/ipc-contract";
import type {
@@ -112,30 +104,6 @@ if (!hasSingleInstanceLock) {
app.quit();
}
-const BROKER_BASE_URL =
- process.env.OPENREEL_AUTH_BROKER_BASE_URL ?? "https://api.openreel.video";
-const GPU_BASE_URL = process.env.OPENREEL_GPU_BASE_URL ?? "https://ai.openreel.video";
-const GPU_BUNDLE_ID = "com.openreel.video";
-
-let gpuClient: GpuJobClient | null = null;
-async function getGpuClient(): Promise<GpuJobClient> {
- if (gpuClient) return gpuClient;
- const instanceId = await getOrCreateInstanceId();
- const tokenProvider = new GpuTokenProvider({
- brokerBaseUrl: BROKER_BASE_URL,
- bundleId: GPU_BUNDLE_ID,
- instanceId,
- });
- gpuClient = new GpuJobClient({
- gpuBaseUrl: GPU_BASE_URL,
- brokerBaseUrl: BROKER_BASE_URL,
- bundleId: GPU_BUNDLE_ID,
- tokenProvider,
- tempFilePath: (ext: string) => tempFilePath({ ext }),
- });
- return gpuClient;
-}
-
function rendererRoot(): string {
return app.isPackaged
? path.join(process.resourcesPath, "renderer")
@@ -246,27 +214,6 @@ app.whenReady().then(() => {
);
handle(CHANNELS.keychainDelete, z.object({ id: z.string() }), ({ id }) => getKeyStore().delete(id));
handle(CHANNELS.cloudFetch, cloudFetchArgsSchema, cloudFetch);
- handle(CHANNELS.gpuUploadMedia, gpuUploadMediaArgsSchema, async (args) =>
- (await getGpuClient()).uploadMedia(args),
- );
- handle(CHANNELS.gpuUploadExport, gpuUploadExportArgsSchema, async (args) =>
- (await getGpuClient()).uploadBytes(args),
- );
- handle(CHANNELS.gpuSubmitJob, gpuSubmitJobArgsSchema, async (args) =>
- (await getGpuClient()).submitJob(args),
- );
- handle(CHANNELS.gpuJobStatus, gpuJobIdArgsSchema, async ({ jobID }) =>
- (await getGpuClient()).jobStatus(jobID),
- );
- handle(CHANNELS.gpuFetchManifest, gpuJobIdArgsSchema, async ({ jobID }) =>
- (await getGpuClient()).fetchManifest(jobID),
- );
- handle(CHANNELS.gpuDownloadArtifact, gpuArtifactArgsSchema, async ({ jobID, relativePath }) =>
- (await getGpuClient()).downloadArtifact(jobID, relativePath),
- );
- handle(CHANNELS.gpuCancelJob, gpuJobIdArgsSchema, async ({ jobID }) =>
- (await getGpuClient()).cancelJob(jobID),
- );
ipcMain.handle(CHANNELS.exportStart, (e, raw) => startExport(e.sender, raw));
handle(
CHANNELS.exportWriteAudioWav,
diff --git a/apps/desktop/src/main/ipc/cloud.ts b/apps/desktop/src/main/ipc/cloud.ts
index 10a51a28..79906d62 100644
--- a/apps/desktop/src/main/ipc/cloud.ts
+++ b/apps/desktop/src/main/ipc/cloud.ts
@@ -1,6 +1,11 @@
import { getKeyStore } from "./keychain";
-export type CloudService = "elevenlabs" | "openai" | "anthropic";
+export type CloudService =
+ | "elevenlabs"
+ | "openai"
+ | "anthropic"
+ | "openai-compatible"
+ | "anthropic-compatible";
interface ServiceConfig {
baseUrl: string;
@@ -9,7 +14,10 @@ interface ServiceConfig {
// Mirror of apps/web/src/services/api-proxy.ts DIRECT_CONFIG. apps/desktop cannot import apps/web,
// so this is a deliberate duplication — keep it in sync if the web config changes.
-export const DIRECT_CONFIG: Record<CloudService, ServiceConfig> = {
+export const DIRECT_CONFIG: Record<
+ Exclude<CloudService, "openai-compatible" | "anthropic-compatible">,
+ ServiceConfig
+> = {
elevenlabs: {
baseUrl: "https://api.elevenlabs.io/v1",
authHeaders: (key) => ({ "xi-api-key": key }),
@@ -31,12 +39,76 @@ export interface UpstreamRequest {
body?: string;
}
+function normalizeCompatibleBaseUrl(input: string | undefined): string {
+ const value = input?.trim() ?? "";
+ if (!value) throw new Error("Missing compatible API base URL");
+ const url = new URL(value);
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new Error("Compatible endpoint must use HTTP or HTTPS");
+ }
+ if (url.username || url.password || url.search || url.hash) {
+ throw new Error("Compatible endpoint cannot contain credentials, query, or fragment");
+ }
+ let pathname = url.pathname.replace(/\/+$/, "");
+ pathname = pathname.replace(/\/(?:chat\/completions|messages|models)$/i, "");
+ url.pathname = pathname;
+ return url.toString().replace(/\/$/, "");
+}
+
export function buildUpstreamRequest(
service: CloudService,
path: string,
key: string,
- options: { method?: string; headers?: Record<string, string>; body?: string },
+ options: {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ baseUrl?: string;
+ },
): UpstreamRequest {
+ if (
+ service === "openai-compatible" ||
+ service === "anthropic-compatible"
+ ) {
+ const allowedPaths =
+ service === "openai-compatible"
+ ? ["/chat/completions", "/models"]
+ : ["/messages", "/models"];
+ if (!allowedPaths.includes(path)) {
+ throw new Error(`Unsupported ${service} API path`);
+ }
+ const safeHeaders = Object.fromEntries(
+ Object.entries(options.headers ?? {}).filter(
+ ([name]) =>
+ ![
+ "authorization",
+ "x-api-key",
+ "anthropic-version",
+ "anthropic-dangerous-direct-browser-access",
+ ].includes(name.toLowerCase()),
+ ),
+ );
+ const authHeaders: Record<string, string> = {};
+ if (service === "openai-compatible") {
+ if (key) authHeaders.Authorization = `Bearer ${key}`;
+ } else {
+ authHeaders["anthropic-version"] = "2023-06-01";
+ if (key) {
+ authHeaders["x-api-key"] = key;
+ authHeaders.Authorization = `Bearer ${key}`;
+ }
+ }
+ return {
+ url: `${normalizeCompatibleBaseUrl(options.baseUrl)}${path}`,
+ method: options.method ?? "GET",
+ headers: {
+ ...safeHeaders,
+ ...authHeaders,
+ },
+ body: options.body,
+ };
+ }
+
const cfg = DIRECT_CONFIG[service];
return {
url: `${cfg.baseUrl}${path}`,
@@ -60,9 +132,10 @@ export async function cloudFetch(args: {
method?: string;
headers?: Record<string, string>;
body?: string;
+ baseUrl?: string;
}): Promise<CloudFetchResult> {
- const key = await getKeyStore().get(args.service);
- if (!key) {
+ const key = (await getKeyStore().get(args.service)) ?? "";
+ if (!key && !args.service.endsWith("-compatible")) {
return {
status: 401,
statusText: `No API key stored for ${args.service}`,
diff --git a/apps/desktop/src/main/mcp/renderer-bridge.ts b/apps/desktop/src/main/mcp/renderer-bridge.ts
index 2f12091d..3b54368a 100644
--- a/apps/desktop/src/main/mcp/renderer-bridge.ts
+++ b/apps/desktop/src/main/mcp/renderer-bridge.ts
@@ -12,21 +12,15 @@ let responseListener: ((event: unknown, response: BridgeResponse) => void) | nul
null;
/**
- * Tools that render/encode/upload or run a remote job legitimately take far
- * longer than a normal editing call. They get a generous timeout so long
- * exports aren't killed by the default bridge limit.
+ * Local tools that render or encode legitimately take far longer than a normal
+ * editing call. They get a generous timeout so long exports aren't killed by
+ * the default bridge limit.
*/
const LONG_RUNNING_TOOLS = new Set<string>([
"export_video",
"export_audio",
"render_motion_frame",
"render_creation_preview",
- "transcribe",
- "detect_highlights",
- "remove_background",
- "upscale",
- "generate_music",
- "inpaint",
"sync_motion_to_audio",
]);
const LONG_RUNNING_TIMEOUT_MS = 30 * 60_000;
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index aa906eea..f7f4f2c4 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -76,19 +76,14 @@ contextBridge.exposeInMainWorld("openreel", {
fetch: (
service: string,
path: string,
- options?: { method?: string; headers?: Record<string, string>; body?: string },
+ options?: {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ baseUrl?: string;
+ },
) => ipcRenderer.invoke(CHANNELS.cloudFetch, { service, path, ...(options ?? {}) }),
},
- gpu: {
- uploadMedia: (args: unknown) => ipcRenderer.invoke(CHANNELS.gpuUploadMedia, args),
- uploadExport: (args: unknown) => ipcRenderer.invoke(CHANNELS.gpuUploadExport, args),
- submitJob: (args: unknown) => ipcRenderer.invoke(CHANNELS.gpuSubmitJob, args),
- jobStatus: (jobID: string) => ipcRenderer.invoke(CHANNELS.gpuJobStatus, { jobID }),
- fetchManifest: (jobID: string) => ipcRenderer.invoke(CHANNELS.gpuFetchManifest, { jobID }),
- downloadArtifact: (jobID: string, relativePath: string) =>
- ipcRenderer.invoke(CHANNELS.gpuDownloadArtifact, { jobID, relativePath }),
- cancelJob: (jobID: string) => ipcRenderer.invoke(CHANNELS.gpuCancelJob, { jobID }),
- },
win: {
minimize: () => ipcRenderer.invoke(CHANNELS.windowControl, { action: "minimize" }),
toggleMaximize: () => ipcRenderer.invoke(CHANNELS.windowControl, { action: "toggleMaximize" }),
diff --git a/apps/desktop/src/shared/channels.ts b/apps/desktop/src/shared/channels.ts
index 00365f3b..ded811d2 100644
--- a/apps/desktop/src/shared/channels.ts
+++ b/apps/desktop/src/shared/channels.ts
@@ -34,13 +34,6 @@ export const CHANNELS = {
riggingProbeBackend: "openreel:rigging:probeBackend",
riggingRigHumanoidModel: "openreel:rigging:rigHumanoidModel",
cloudFetch: "openreel:cloud:fetch",
- gpuUploadMedia: "openreel:gpu:uploadMedia",
- gpuUploadExport: "openreel:gpu:uploadExport",
- gpuSubmitJob: "openreel:gpu:submitJob",
- gpuJobStatus: "openreel:gpu:jobStatus",
- gpuFetchManifest: "openreel:gpu:fetchManifest",
- gpuDownloadArtifact: "openreel:gpu:downloadArtifact",
- gpuCancelJob: "openreel:gpu:cancelJob",
windowControl: "openreel:window:control",
windowIsMaximized: "openreel:window:isMaximized",
lifecycleUnsavedQuery: "openreel:lifecycle:unsavedQuery",
diff --git a/apps/desktop/src/shared/ipc-contract.ts b/apps/desktop/src/shared/ipc-contract.ts
index cfc389c4..3870cf73 100644
--- a/apps/desktop/src/shared/ipc-contract.ts
+++ b/apps/desktop/src/shared/ipc-contract.ts
@@ -100,11 +100,18 @@ export const rigHumanoidModelResultSchema = z.object({
export type RigHumanoidModelResult = z.infer<typeof rigHumanoidModelResultSchema>;
export const cloudFetchArgsSchema = z.object({
- service: z.enum(["elevenlabs", "openai", "anthropic"]),
+ service: z.enum([
+ "elevenlabs",
+ "openai",
+ "anthropic",
+ "openai-compatible",
+ "anthropic-compatible",
+ ]),
path: z.string(),
method: z.string().optional(),
headers: z.record(z.string()).optional(),
body: z.string().optional(),
+ baseUrl: z.string().optional(),
});
export interface AuroraRenderPreviewArgs {
@@ -264,25 +271,6 @@ export type AuroraSequenceSessionEvent = z.infer<
typeof auroraSequenceSessionEventSchema
>;
-export const gpuUploadMediaArgsSchema = z.object({
- srcPath: z.string(),
- filename: z.string(),
- contentType: z.string().optional(),
-});
-export const gpuUploadExportArgsSchema = z.object({
- bytes: z.union([z.instanceof(ArrayBuffer), z.instanceof(Uint8Array)]),
- filename: z.string(),
- contentType: z.string().optional(),
-});
-export const gpuSubmitJobArgsSchema = z.object({
- kind: z.string(),
- params: z.record(z.unknown()),
- mediaKey: z.string().optional(),
- mediaFilename: z.string().optional(),
-});
-export const gpuJobIdArgsSchema = z.object({ jobID: z.string() });
-export const gpuArtifactArgsSchema = z.object({ jobID: z.string(), relativePath: z.string() });
-
export const windowControlArgsSchema = z.object({
action: z.enum(["minimize", "toggleMaximize", "close"]),
});
diff --git a/apps/desktop/test/cloud-fetch.test.ts b/apps/desktop/test/cloud-fetch.test.ts
index 5d62db50..f59ecc78 100644
--- a/apps/desktop/test/cloud-fetch.test.ts
+++ b/apps/desktop/test/cloud-fetch.test.ts
@@ -41,4 +41,56 @@ describe("buildUpstreamRequest", () => {
const r = buildUpstreamRequest("elevenlabs", "/models", "KEY", {});
expect(r.method).toBe("GET");
});
+
+ it("routes an OpenAI-compatible request to its user-defined endpoint", () => {
+ const r = buildUpstreamRequest("openai-compatible", "/chat/completions", "CUSTOM", {
+ method: "POST",
+ baseUrl: "http://localhost:11434/v1/",
+ body: "{}",
+ });
+ expect(r.url).toBe("http://localhost:11434/v1/chat/completions");
+ expect(r.headers.Authorization).toBe("Bearer CUSTOM");
+ });
+
+ it("allows keyless local compatible endpoints and complete endpoint URLs", () => {
+ const r = buildUpstreamRequest("openai-compatible", "/chat/completions", "", {
+ baseUrl: "http://127.0.0.1:1234/v1/chat/completions",
+ });
+ expect(r.url).toBe("http://127.0.0.1:1234/v1/chat/completions");
+ expect(r.headers.Authorization).toBeUndefined();
+ });
+
+ it("does not accept renderer-supplied compatible authorization", () => {
+ const r = buildUpstreamRequest("openai-compatible", "/chat/completions", "STORED", {
+ baseUrl: "https://provider.example/v1",
+ headers: { authorization: "Bearer injected" },
+ });
+ expect(r.headers.authorization).toBeUndefined();
+ expect(r.headers.Authorization).toBe("Bearer STORED");
+ });
+
+ it("routes Anthropic-compatible messages and model discovery", () => {
+ const message = buildUpstreamRequest(
+ "anthropic-compatible",
+ "/messages",
+ "STORED",
+ {
+ method: "POST",
+ baseUrl: "https://gateway.example/v1/messages",
+ body: "{}",
+ },
+ );
+ expect(message.url).toBe("https://gateway.example/v1/messages");
+ expect(message.headers["x-api-key"]).toBe("STORED");
+ expect(message.headers.Authorization).toBe("Bearer STORED");
+ expect(message.headers["anthropic-version"]).toBe("2023-06-01");
+
+ const models = buildUpstreamRequest(
+ "anthropic-compatible",
+ "/models",
+ "",
+ { baseUrl: "http://localhost:4000/v1" },
+ );
+ expect(models.url).toBe("http://localhost:4000/v1/models");
+ });
});
diff --git a/apps/desktop/test/gpu-job-client.test.ts b/apps/desktop/test/gpu-job-client.test.ts
deleted file mode 100644
index cb131f0e..00000000
--- a/apps/desktop/test/gpu-job-client.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { normalizePresign, buildSubmitBody, GpuJobClient } from "../src/main/gpu/job-client";
-
-function clientWith(fetchImpl: (url: string, init?: RequestInit) => Promise<Response>) {
- const tokenProvider = { getToken: vi.fn(async () => "tok"), invalidate: vi.fn() };
- const client = new GpuJobClient({
- gpuBaseUrl: "https://gpu.test",
- brokerBaseUrl: "https://broker.test",
- bundleId: "com.openreel.video",
- tokenProvider,
- fetchFn: fetchImpl as unknown as typeof fetch,
- });
- return { client, tokenProvider };
-}
-
-function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}): Response {
- return {
- ok: status >= 200 && status < 300,
- status,
- headers: { get: (k: string) => headers[k.toLowerCase()] ?? null },
- json: async () => body,
- } as unknown as Response;
-}
-
-describe("normalizePresign", () => {
- it("accepts the canonical shape (uploadURL/mediaKey)", () => {
- const r = normalizePresign({ uploadURL: "https://r2/put", mediaKey: "jobs/a/b/file.mp4", headers: { "Content-Type": "video/mp4" } });
- expect(r).toEqual({ uploadUrl: "https://r2/put", mediaKey: "jobs/a/b/file.mp4", headers: { "Content-Type": "video/mp4" } });
- });
- it("accepts the broker shape (putUrl/objectKey)", () => {
- const r = normalizePresign({ putUrl: "https://r2/put", objectKey: "jobs/a/b/file.mp4" });
- expect(r.uploadUrl).toBe("https://r2/put");
- expect(r.mediaKey).toBe("jobs/a/b/file.mp4");
- expect(r.headers).toEqual({});
- });
- it("throws when both url aliases are missing", () => {
- expect(() => normalizePresign({ mediaKey: "k" })).toThrow();
- });
-});
-
-describe("buildSubmitBody", () => {
- it("JSON-only when no mediaKey", () => {
- const { body, contentType } = buildSubmitBody({ kind: "music_generation", params: { prompt: "lofi" } });
- expect(contentType).toBe("application/json");
- expect(JSON.parse(body)).toEqual({ kind: "music_generation", params: { prompt: "lofi" } });
- });
- it("JSON wrapper with mediaKey + mediaFilename", () => {
- const { body } = buildSubmitBody({ kind: "upscale", params: { context: { clipID: "c1" } }, mediaKey: "jobs/x/y/in.mp4", mediaFilename: "in.mp4" });
- expect(JSON.parse(body)).toEqual({
- request: { kind: "upscale", params: { context: { clipID: "c1" } } },
- mediaKey: "jobs/x/y/in.mp4",
- mediaFilename: "in.mp4",
- });
- });
-});
-
-describe("GpuJobClient.submitJob", () => {
- it("sends Bearer + X-Bundle-ID and returns the created job", async () => {
- const seen: { init?: RequestInit } = {};
- const { client } = clientWith(async (_url, init) => {
- seen.init = init;
- return jsonResponse(200, { jobID: "job1", status: "queued", manifestURL: "/jobs/job1/manifest" });
- });
- const res = await client.submitJob({ kind: "upscale", params: {}, mediaKey: "jobs/a/b/in.mp4", mediaFilename: "in.mp4" });
- expect(res.jobID).toBe("job1");
- const headers = seen.init!.headers as Record<string, string>;
- expect(headers.Authorization).toBe("Bearer tok");
- expect(headers["X-Bundle-ID"]).toBe("com.openreel.video");
- });
-
- it("surfaces a 503 as a retryable error carrying Retry-After", async () => {
- const { client } = clientWith(async () => jsonResponse(503, { error: "queue_full" }, { "retry-after": "30" }));
- await expect(client.submitJob({ kind: "upscale", params: {}, mediaKey: "k", mediaFilename: "f" })).rejects.toMatchObject({ status: 503, retryAfterSeconds: 30 });
- });
-
- it("on a 401 invalidates the token and retries once", async () => {
- let n = 0;
- const { client, tokenProvider } = clientWith(async () => {
- n += 1;
- return n === 1 ? jsonResponse(401, { error: "invalid_token" }) : jsonResponse(200, { jobID: "j", status: "queued" });
- });
- const res = await client.submitJob({ kind: "denoise", params: {}, mediaKey: "k", mediaFilename: "f" });
- expect(res.jobID).toBe("j");
- expect(tokenProvider.invalidate).toHaveBeenCalledTimes(1);
- expect(n).toBe(2);
- });
-});
-
-describe("GpuJobClient.jobStatus", () => {
- it("GETs /jobs/{id} and returns the status payload", async () => {
- const { client } = clientWith(async (url) => {
- expect(url).toBe("https://gpu.test/jobs/job1");
- return jsonResponse(200, { jobID: "job1", status: "processing", progress: 0.5, queuePosition: 0, pendingAhead: 0 });
- });
- const s = await client.jobStatus("job1");
- expect(s.status).toBe("processing");
- expect(s.progress).toBe(0.5);
- });
-});
diff --git a/apps/desktop/test/gpu-token-provider.test.ts b/apps/desktop/test/gpu-token-provider.test.ts
deleted file mode 100644
index edec3db0..00000000
--- a/apps/desktop/test/gpu-token-provider.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { GpuTokenProvider } from "../src/main/gpu/token-provider";
-
-function fakeFetch(responses: Array<{ ok: boolean; status: number; json: unknown }>) {
- const calls: Array<{ url: string; init?: RequestInit }> = [];
- let i = 0;
- const fn = vi.fn(async (url: string, init?: RequestInit) => {
- calls.push({ url, init });
- const r = responses[Math.min(i, responses.length - 1)];
- i += 1;
- return { ok: r.ok, status: r.status, json: async () => r.json } as unknown as Response;
- });
- return { fn, calls };
-}
-
-const okChallenge = { ok: true, status: 200, json: { challengeId: "ch1", challenge: "abc" } };
-const okToken = (exp: number) => ({ ok: true, status: 200, json: { token: "tok", exp } });
-
-describe("GpuTokenProvider", () => {
- it("mints via challenge then token and caches until near expiry", async () => {
- const now = () => 1_000_000; // ms
- const exp = Math.floor(now() / 1000) + 600;
- const { fn, calls } = fakeFetch([okChallenge, okToken(exp)]);
- const p = new GpuTokenProvider({
- brokerBaseUrl: "https://broker.test",
- bundleId: "com.openreel.video",
- instanceId: "inst-1",
- fetchFn: fn as unknown as typeof fetch,
- now,
- });
- expect(await p.getToken()).toBe("tok");
- expect(await p.getToken()).toBe("tok"); // cached, no new mint
- expect(calls.filter((c) => c.url.endsWith("/auth/challenge")).length).toBe(1);
- expect(calls.filter((c) => c.url.endsWith("/auth/token")).length).toBe(1);
- const chBody = JSON.parse(calls[0].init!.body as string);
- expect(chBody).toEqual({ platform: "desktop", instanceId: "inst-1" });
- const tokBody = JSON.parse(calls[1].init!.body as string);
- expect(tokBody).toEqual({ platform: "desktop", challengeId: "ch1" });
- });
-
- it("re-mints after invalidate()", async () => {
- const now = () => 1_000_000;
- const exp = Math.floor(now() / 1000) + 600;
- const { fn, calls } = fakeFetch([okChallenge, okToken(exp), okChallenge, okToken(exp)]);
- const p = new GpuTokenProvider({ brokerBaseUrl: "https://b", bundleId: "x", instanceId: "i", fetchFn: fn as unknown as typeof fetch, now });
- await p.getToken();
- p.invalidate();
- await p.getToken();
- expect(calls.filter((c) => c.url.endsWith("/auth/token")).length).toBe(2);
- });
-
- it("re-mints when the cached token is within 60s of expiry", async () => {
- let t = 1_000_000;
- const now = () => t;
- const exp = Math.floor(t / 1000) + 100; // expires in 100s
- const { fn, calls } = fakeFetch([okChallenge, okToken(exp), okChallenge, okToken(exp + 600)]);
- const p = new GpuTokenProvider({ brokerBaseUrl: "https://b", bundleId: "x", instanceId: "i", fetchFn: fn as unknown as typeof fetch, now });
- await p.getToken();
- t += 50_000; // now 50s before expiry -> within leeway
- await p.getToken();
- expect(calls.filter((c) => c.url.endsWith("/auth/token")).length).toBe(2);
- });
-
- it("throws on a failed challenge", async () => {
- const { fn } = fakeFetch([{ ok: false, status: 503, json: { error: "auth_unconfigured" } }]);
- const p = new GpuTokenProvider({ brokerBaseUrl: "https://b", bundleId: "x", instanceId: "i", fetchFn: fn as unknown as typeof fetch });
- await expect(p.getToken()).rejects.toThrow();
- });
-});
diff --git a/apps/desktop/test/parity.md b/apps/desktop/test/parity.md
index c840c404..dd94a677 100644
--- a/apps/desktop/test/parity.md
+++ b/apps/desktop/test/parity.md
@@ -72,62 +72,6 @@ For a **no-audio project**, any visual tail that extends beyond `timeline.durati
may be truncated by `-shortest` (ffmpeg ends muxing at the shortest input stream).
Tracked as a v1 limitation — see spec §13.
-# Desktop GPU AI panel — pending human E2E (Task D5)
-
-The GPU cloud-jobs pipeline (token mint → presign → upload → poll → artifact import)
-is unit/integration covered (`apps/desktop/test/gpu-token-provider.test.ts`,
-`gpu-job-client.test.ts`, `cloud-fetch.test.ts`; `apps/web/src/services/gpu-result-import.test.ts`;
-`packages/core/src/ai/cloud-job-types.test.ts`), but the full launch-to-clip flow
-requires a deployed Worker and a human on-screen run. The following are **pending
-human verification**:
-
-1. **Deploy the `apps/cloud` Worker first.** The desktop AI path depends on the new
- `plat:"desktop"` leg of `POST /auth/token` in the auth broker Worker. Deploy
- `apps/cloud` before testing desktop AI; nothing in `infra/gpu-worker` changes for
- this task (no GPU worker redeploy needed).
-
-2. **Confirm the broker + GPU base URLs point at live services.** Verify
- `OPENREEL_AUTH_BROKER_BASE_URL`
- (default `https://openreel-cloud.niiyeboah1996.workers.dev`) and
- `OPENREEL_GPU_BASE_URL` (default `https://ai.openreel.video`) resolve to the
- deployed Worker and the live GPU render service.
-
-3. **Manual E2E — upscale a clip end to end.** Launch the desktop app, open the AI
- panel via the **Sparkles** toolbar toggle, select a single clip, and run
- `upscale`. Confirm the sequence: token mint → presign → upload of the source temp
- file → status poll until `completed` → artifact download → import back into the
- media library as a clip. Verify the imported item replaces its placeholder
- **in place** (same media id, not a duplicate), is no longer stuck pending, and has
- the **correct media type** (video result imports as `type:"video"` with real
- duration — not mislabeled as an image).
-
-4. **Spot-check non-image kinds.** Because the v1 routing now types results from the
- decoded media (see decision below), run at least one video-producing kind and one
- audio-producing kind and confirm thumbnails/waveforms generate and the
- `duration`/dimensions are non-zero.
-
-## v1 routing decision (Task D5 Part 1)
-
-`importGpuResult` now routes **all** artifact kinds through
-`projectStore.replaceMediaAsset(mediaId, file)` instead of the image-only
-`replacePlaceholderMedia`. `replaceMediaAsset` resolves the item **in place by id**,
-detects `video`/`audio`/`image` from the decoded media metadata (fixing the prior bug
-where every GPU result was hardcoded to `type:"image"` with `duration:0`), clears
-`isPlaceholder` and leaves `isPending` falsy, and generates thumbnails/waveforms.
-
-**Added persistence step:** unlike `replacePlaceholderMedia`, `replaceMediaAsset` does
-not itself write the blob to IndexedDB (it is normally used for file-handle-backed
-desktop relinks that persist via the source file). A GPU result has no `sourceFile`
-handle, so `importGpuResult` explicitly calls `saveMediaBlob(projectId, mediaId, file,
-metadata)` after a successful replace, ensuring the result survives a project reload.
-On a failed replace it throws, which the poller (`useGpuJobPoller`) catches to flag the
-placeholder's error state.
-
-**Remaining limitation:** the result media type is inferred from the bytes the GPU
-worker returns (via the native media bridge decode), not from the requested `kind`. If
-a worker returns an unexpected container/codec the bridge cannot decode, the import
-fails and the placeholder is flagged rather than partially imported.
-
# Desktop Native Pro Redesign — pending human checks (Phases 1–2)
Automated tests + builds are green; these need a real launch / packaged build to confirm:
diff --git a/apps/web/package.json b/apps/web/package.json
index 51c7e60b..b4e2f3d5 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,6 +1,6 @@
{
"name": "@openreel/web",
- "version": "0.1.1",
+ "version": "0.1.2",
"private": true,
"type": "module",
"scripts": {
@@ -20,6 +20,7 @@
"@astryxdesign/theme-neutral": "^0.1.1",
"@gsap/react": "^2.1.2",
"@huggingface/transformers": "3.8.1",
+ "@mediapipe/tasks-vision": "^0.10.35",
"@openreel/agent": "workspace:*",
"@openreel/core": "workspace:*",
"@openreel/ui": "workspace:*",
@@ -28,11 +29,14 @@
"@types/uuid": "^11.0.0",
"framer-motion": "^12.23.24",
"gsap": "^3.14.2",
+ "idb-keyval": "^6.2.2",
"lucide-react": "^0.555.0",
"posthog-js": "^1.335.2",
"react": "^19.2.7",
"react-dom": "^19.2.7",
+ "react-markdown": "^10.1.0",
"react-syntax-highlighter": "^16.1.0",
+ "remark-gfm": "^4.0.1",
"three": "^0.182.0",
"uuid": "^13.0.0",
"zustand": "^4.5.2"
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index 224bfa0a..63839d95 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -11,7 +11,6 @@ import { useProjectStore } from "./stores/project-store";
import { useRouter } from "./hooks/use-router";
import { useProjectRecovery } from "./hooks/useProjectRecovery";
import { useKieAIPoller } from "./hooks/useKieAIPoller";
-import { useGpuJobPoller } from "./hooks/useGpuJobPoller";
import { SOCIAL_MEDIA_PRESETS, type SocialMediaCategory } from "@openreel/core";
import { ToolcraftText as Text } from "@openreel/ui";
@@ -55,7 +54,6 @@ function App() {
const isMotionSurface = isMotionHost || route === "motion";
useKieAIPoller();
- useGpuJobPoller();
useEffect(() => {
if (hasHandledInitialRoute.current) return;
diff --git a/apps/web/src/components/audio-mixer/AudioMixer.tsx b/apps/web/src/components/audio-mixer/AudioMixer.tsx
index 35f3bcb5..3b11ac6c 100644
--- a/apps/web/src/components/audio-mixer/AudioMixer.tsx
+++ b/apps/web/src/components/audio-mixer/AudioMixer.tsx
@@ -9,7 +9,7 @@ import { useProjectStore } from "../../stores/project-store";
import { ChannelStrip } from "./ChannelStrip";
import type { ChannelStripState } from "./types";
import { volumeToDb, formatDb } from "./types";
-import { getRealtimeAudioGraph } from "@openreel/core";
+import { getRealtimeAudioGraph, trackHasAudioItems } from "@openreel/core";
import { ToolcraftIconButton as IconButton } from "@openreel/ui";
import { ToolcraftSlider as Slider } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
@@ -141,10 +141,8 @@ export const AudioMixer: React.FC<AudioMixerProps> = ({
// Get audio tracks from the timeline (Requirement 20.1) – safe if project/timeline not ready
const audioTracks = useMemo(() => {
const tracks = project?.timeline?.tracks ?? [];
- return tracks.filter(
- (track) => track.type === "audio" || track.type === "video",
- );
- }, [project?.timeline?.tracks]);
+ return tracks.filter((track) => trackHasAudioItems(project, track.id));
+ }, [project]);
useEffect(() => {
try {
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index 34f3301e..c7f93519 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -34,6 +34,7 @@ import { KieAIImageDialog } from "./kieai/KieAIImageDialog";
import { loadMediaBlob } from "../../services/media-storage";
import { useKieAIStore } from "../../stores/kieai-store";
import { StickerPickerPanel } from "./inspector/StickerPickerPanel";
+import { insertTimelineOverlay } from "../../stores/project/insert-timeline-overlay";
const formatDuration = (seconds: number): string => {
const mins = Math.floor(seconds / 60);
@@ -1252,30 +1253,24 @@ export const AssetsPanel: React.FC = () => {
key={shape.type}
label={shape.label}
onClick={async () => {
- const state = useProjectStore.getState();
- const { createShapeClip, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .createShapeClip(
+ trackId,
+ playheadPosition,
+ shape.type,
+ ),
);
- if (newGraphicsTrack) {
- const created = createShapeClip(
- newGraphicsTrack.id,
- playheadPosition,
- shape.type,
- );
- if (created) {
- select({
- type: "shape-clip",
- id: created.id,
- trackId: newGraphicsTrack.id,
- });
- }
+ if (created) {
+ select({
+ type: "shape-clip",
+ id: created.id,
+ trackId: created.trackId,
+ });
}
}}
className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group"
@@ -1309,38 +1304,30 @@ export const AssetsPanel: React.FC = () => {
key={mesh.type}
label={mesh.label}
onClick={async () => {
- const state = useProjectStore.getState();
- const { createShapeClip, addTrack, updateClipRotate3D } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .createShapeClip(
+ trackId,
+ playheadPosition,
+ mesh.type,
+ ),
);
- if (newGraphicsTrack) {
- const created = createShapeClip(
- newGraphicsTrack.id,
- playheadPosition,
- mesh.type,
+ // Nudge the rotation so the 3D depth is visible from
+ // the get-go (otherwise a head-on cube looks flat).
+ if (created) {
+ useProjectStore.getState().updateClipRotate3D(
+ created.id,
+ { x: -18, y: 28, z: 0 },
);
- // Nudge the rotation so the 3D depth is
- // visible from the get-go (otherwise a
- // head-on cube looks like a flat square).
- if (created) {
- updateClipRotate3D(created.id, {
- x: -18,
- y: 28,
- z: 0,
- });
- select({
- type: "shape-clip",
- id: created.id,
- trackId: newGraphicsTrack.id,
- });
- }
+ select({
+ type: "shape-clip",
+ id: created.id,
+ trackId: created.trackId,
+ });
}
}}
className="aspect-square bg-background-tertiary rounded-lg border border-border hover:border-primary/50 hover:bg-primary/5 transition-all flex flex-col items-center justify-center gap-1 group"
@@ -1370,30 +1357,20 @@ export const AssetsPanel: React.FC = () => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
const content = await file.text();
- const state = useProjectStore.getState();
- const { importSVG, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("graphics", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newGraphicsTrack = tracksAfter.find(
- (t) =>
- t.type === "graphics" &&
- !tracksBefore.some((bt) => bt.id === t.id),
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .importSVG(content, trackId, playheadPosition),
);
- if (newGraphicsTrack) {
- const created = importSVG(
- content,
- newGraphicsTrack.id,
- playheadPosition,
- );
- if (created) {
- select({
- type: "shape-clip",
- id: created.id,
- trackId: newGraphicsTrack.id,
- });
- }
+ if (created) {
+ select({
+ type: "shape-clip",
+ id: created.id,
+ trackId: created.trackId,
+ });
}
}
};
@@ -1426,32 +1403,26 @@ export const AssetsPanel: React.FC = () => {
<PanelButton
label="Add Title"
onClick={async () => {
- const state = useProjectStore.getState();
- const { createTextClip, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("text", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newTextTrack = tracksAfter.find(
- (t) =>
- t.type === "text" &&
- !tracksBefore.some((bt) => bt.id === t.id),
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .createTextClip(
+ trackId,
+ playheadPosition,
+ "New Title",
+ 5,
+ DEFAULT_TITLE_STYLE,
+ ),
);
- if (newTextTrack) {
- const created = createTextClip(
- newTextTrack.id,
- playheadPosition,
- "New Title",
- 5,
- DEFAULT_TITLE_STYLE,
- );
- if (created) {
- select({
- type: "text-clip",
- id: created.id,
- trackId: newTextTrack.id,
- });
- }
+ if (created) {
+ select({
+ type: "text-clip",
+ id: created.id,
+ trackId: created.trackId,
+ });
}
}}
className="flex min-h-[72px] w-full min-w-0 flex-col items-center justify-center rounded-lg border border-border bg-background-tertiary px-3 py-3 text-center transition-all hover:border-primary/50 hover:bg-primary/5"
@@ -1475,32 +1446,26 @@ export const AssetsPanel: React.FC = () => {
key={preset.name}
label={preset.name}
onClick={async () => {
- const state = useProjectStore.getState();
- const { createTextClip, addTrack } = state;
- const tracksBefore = state.project.timeline.tracks;
- await addTrack("text", 0);
- const tracksAfter =
- useProjectStore.getState().project.timeline.tracks;
- const newTextTrack = tracksAfter.find(
- (t) =>
- t.type === "text" &&
- !tracksBefore.some((bt) => bt.id === t.id),
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .createTextClip(
+ trackId,
+ playheadPosition,
+ preset.text,
+ 5,
+ preset.style,
+ ),
);
- if (newTextTrack) {
- const created = createTextClip(
- newTextTrack.id,
- playheadPosition,
- preset.text,
- 5,
- preset.style,
- );
- if (created) {
- select({
- type: "text-clip",
- id: created.id,
- trackId: newTextTrack.id,
- });
- }
+ if (created) {
+ select({
+ type: "text-clip",
+ id: created.id,
+ trackId: created.trackId,
+ });
}
}}
className="flex min-h-[44px] min-w-0 items-center justify-center rounded-lg border border-border bg-background-tertiary px-2 py-2 text-center text-xs font-medium leading-tight text-text-secondary transition-all hover:border-primary/50 hover:bg-primary/5 hover:text-text-primary"
diff --git a/apps/web/src/components/editor/EditorActionRail.tsx b/apps/web/src/components/editor/EditorActionRail.tsx
index 8c9af590..df371236 100644
--- a/apps/web/src/components/editor/EditorActionRail.tsx
+++ b/apps/web/src/components/editor/EditorActionRail.tsx
@@ -84,9 +84,6 @@ export const EditorActionRail: React.FC = () => {
}
}, [createMotionComposition, navigate]);
- const isDesktop =
- typeof window !== "undefined" && window.openreel?.platform === "desktop";
-
return (
<nav
data-tour="toolbar"
@@ -152,14 +149,6 @@ export const EditorActionRail: React.FC = () => {
onClick={() => togglePanel("agentChat")}
active={Boolean(panels.agentChat?.visible)}
/>
- {isDesktop && (
- <RailButton
- label="AI"
- icon="sparkles"
- onClick={() => togglePanel("ai")}
- active={Boolean(panels.ai?.visible)}
- />
- )}
<RailButton
label="Project JSON / Comments"
icon="curlybraces"
diff --git a/apps/web/src/components/editor/EditorInterface.tsx b/apps/web/src/components/editor/EditorInterface.tsx
index d7ef1480..15695cc3 100644
--- a/apps/web/src/components/editor/EditorInterface.tsx
+++ b/apps/web/src/components/editor/EditorInterface.tsx
@@ -9,7 +9,6 @@ import { InspectorPanel } from "./InspectorPanel";
import { Timeline } from "./Timeline";
import { KeyframeEditorPanel } from "./KeyframeEditorPanel";
import { AudioMixer } from "../audio-mixer";
-import { AIPanel } from "./ai-panel/AIPanel";
import { KeyboardShortcutsOverlay } from "./KeyboardShortcutsOverlay";
import { PanelErrorBoundary } from "../ErrorBoundary";
import { SpotlightTour, MoGraphTour } from "./tour";
@@ -573,14 +572,6 @@ export const EditorInterface: React.FC = () => {
</div>
)}
- {panels.ai?.visible && (
- <div className="shrink-0 border-b border-border">
- <PanelErrorBoundary name="AI">
- <AIPanel />
- </PanelErrorBoundary>
- </div>
- )}
-
<div className="flex-1 min-h-0 flex">
<div className="flex-1 min-w-0 min-h-0">
<PanelErrorBoundary name="Timeline">
diff --git a/apps/web/src/components/editor/ExportDialog.test.tsx b/apps/web/src/components/editor/ExportDialog.test.tsx
new file mode 100644
index 00000000..cbfff3c4
--- /dev/null
+++ b/apps/web/src/components/editor/ExportDialog.test.tsx
@@ -0,0 +1,82 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { SourceExportMatch } from "../../services/export-source-match";
+import { ExportDialog } from "./ExportDialog";
+
+vi.mock("@openreel/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@openreel/core")>();
+ return {
+ ...actual,
+ estimateExportTime: vi.fn(() => null),
+ getCodecRecommendations: vi.fn(() => []),
+ getDeviceProfile: vi.fn(() => new Promise<never>(() => undefined)),
+ };
+});
+
+const SOURCE_MATCH: SourceExportMatch = {
+ width: 4000,
+ height: 2400,
+ frameRate: 30,
+ bitrate: 60_000,
+ sourceName: "source-match.mp4",
+};
+
+describe("ExportDialog", () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("keeps the source-match shortcut in the presets view", () => {
+ render(
+ <ExportDialog
+ isOpen
+ onClose={vi.fn()}
+ onExport={vi.fn()}
+ duration={1}
+ sourceMatch={SOURCE_MATCH}
+ />,
+ );
+
+ expect(screen.getByTestId("quick-export-card")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("radio", { name: "Custom Settings" }));
+
+ expect(screen.queryByTestId("quick-export-card")).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("heading", { name: "Quality & encoding" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Audio" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("heading", { name: "Enhance quality" }),
+ ).toBeInTheDocument();
+ });
+
+ it("exports source settings from the quick action", () => {
+ const onClose = vi.fn();
+ const onExport = vi.fn();
+
+ render(
+ <ExportDialog
+ isOpen
+ onClose={onClose}
+ onExport={onExport}
+ duration={1}
+ sourceMatch={SOURCE_MATCH}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Quick Export" }));
+
+ expect(onExport).toHaveBeenCalledWith(
+ expect.objectContaining({
+ format: "mp4",
+ codec: "h264",
+ width: 4000,
+ height: 2400,
+ frameRate: 30,
+ bitrate: 60_000,
+ }),
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/components/editor/ExportDialog.tsx b/apps/web/src/components/editor/ExportDialog.tsx
index daee6385..b4dceef8 100644
--- a/apps/web/src/components/editor/ExportDialog.tsx
+++ b/apps/web/src/components/editor/ExportDialog.tsx
@@ -20,10 +20,20 @@ import {
Minimize2,
AlertTriangle,
} from "@/icons/lucide-compat";
-import { ToolcraftSegmentedControl, ToolcraftSwitchControl } from "@openreel/ui";
+import {
+ ToolcraftSegmentedControl,
+ ToolcraftSwitchControl,
+} from "@openreel/ui";
import { ToolcraftButton as Button } from "@openreel/ui";
-import { ToolcraftDialog as Dialog, ToolcraftDialogHeader as DialogHeader } from "@openreel/ui";
-import { ToolcraftLayout as Layout, ToolcraftLayoutContent as LayoutContent, ToolcraftLayoutFooter as LayoutFooter } from "@openreel/ui";
+import {
+ ToolcraftDialog as Dialog,
+ ToolcraftDialogHeader as DialogHeader,
+} from "@openreel/ui";
+import {
+ ToolcraftLayout as Layout,
+ ToolcraftLayoutContent as LayoutContent,
+ ToolcraftLayoutFooter as LayoutFooter,
+} from "@openreel/ui";
import { ToolcraftNumberInputControl } from "@openreel/ui";
import { ToolcraftSelectableCard as SelectableCard } from "@openreel/ui";
import { ToolcraftSelectControl as Selector } from "@openreel/ui";
@@ -54,11 +64,13 @@ import {
compressionPlanToExportSettings,
COMPRESSION_SIZE_PRESETS,
exportSettingsRequireNativeEncoder,
+ resolveWebCodecsExportLimits,
type DeviceProfile,
type BenchmarkProgress,
type TimeEstimate,
type CodecRecommendation,
} from "@openreel/core";
+import { EDITING_FRAME_RATE_OPTIONS } from "./editing-frame-rate";
const WEB_EXPORT_GUARDRAIL_MESSAGE =
"Web export can't produce ProRes or alpha — this will encode H.264 without transparency. Use the desktop app for ProRes/alpha.";
@@ -138,9 +150,11 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
frameRate = 30,
sourceMatch = null,
}) => {
- const [activeTab, setActiveTab] = useState<
- "presets" | "custom" | "reduce"
- >("presets");
+ const isDesktop =
+ typeof window !== "undefined" && window.openreel?.platform === "desktop";
+ const [activeTab, setActiveTab] = useState<"presets" | "custom" | "reduce">(
+ "presets",
+ );
const [selectedPlatform, setSelectedPlatform] = useState<string | null>(
"recommended",
);
@@ -157,7 +171,7 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
encodeMode: "balanced",
width: projectWidth,
height: projectHeight,
- frameRate: 30,
+ frameRate,
bitrate: 15000,
bitrateMode: "vbr",
quality: 90,
@@ -176,6 +190,13 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
},
});
+ useEffect(() => {
+ if (!isOpen) return;
+ setCustomSettings((current) =>
+ current.frameRate === frameRate ? current : { ...current, frameRate },
+ );
+ }, [frameRate, isOpen]);
+
const [reduceMode, setReduceMode] = useState<"quality" | "size">("quality");
const [reduceQuality, setReduceQuality] =
useState<CompressionQuality>("balanced");
@@ -239,11 +260,40 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
return customSettings;
}, [activeTab, selectedPreset, reducePlan, customSettings]);
- const [deviceProfile, setDeviceProfile] = useState<DeviceProfile | null>(null);
+ const webExportAdjustment = useMemo(
+ () =>
+ isDesktop
+ ? null
+ : resolveWebCodecsExportLimits(effectiveSettings, duration),
+ [duration, effectiveSettings, isDesktop],
+ );
+
+ const matchSourceWebAdjustment = useMemo(() => {
+ if (isDesktop || !sourceMatch) return null;
+ return resolveWebCodecsExportLimits(
+ {
+ ...customSettings,
+ format: "mp4",
+ codec: "h264",
+ width: sourceMatch.width,
+ height: sourceMatch.height,
+ frameRate: sourceMatch.frameRate,
+ bitrate: sourceMatch.bitrate,
+ },
+ duration,
+ );
+ }, [customSettings, duration, isDesktop, sourceMatch]);
+
+ const [deviceProfile, setDeviceProfile] = useState<DeviceProfile | null>(
+ null,
+ );
const [timeEstimate, setTimeEstimate] = useState<TimeEstimate | null>(null);
- const [codecRecommendations, setCodecRecommendations] = useState<CodecRecommendation[]>([]);
+ const [codecRecommendations, setCodecRecommendations] = useState<
+ CodecRecommendation[]
+ >([]);
const [isBenchmarking, setIsBenchmarking] = useState(false);
- const [benchmarkProgress, setBenchmarkProgress] = useState<BenchmarkProgress | null>(null);
+ const [benchmarkProgress, setBenchmarkProgress] =
+ useState<BenchmarkProgress | null>(null);
const [showDeviceInfo, setShowDeviceInfo] = useState(false);
const [h264FallbackAcknowledged, setH264FallbackAcknowledged] =
useState(false);
@@ -258,7 +308,10 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
getDeviceProfile().then((profile) => {
setDeviceProfile(profile);
setCodecRecommendations(
- getCodecRecommendations(profile, { width: projectWidth, height: projectHeight })
+ getCodecRecommendations(profile, {
+ width: projectWidth,
+ height: projectHeight,
+ }),
);
});
}
@@ -297,7 +350,10 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
const updatedProfile = await getDeviceProfile(true);
setDeviceProfile(updatedProfile);
setCodecRecommendations(
- getCodecRecommendations(updatedProfile, { width: projectWidth, height: projectHeight })
+ getCodecRecommendations(updatedProfile, {
+ width: projectWidth,
+ height: projectHeight,
+ }),
);
} catch (error) {
console.error("Benchmark failed:", error);
@@ -321,8 +377,6 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
? presets.filter((p) => p.platform === selectedPlatform)
: exportPresetsManager.getRecommendedPresets();
- const isDesktop =
- typeof window !== "undefined" && window.openreel?.platform === "desktop";
const isNativeExportAvailable = isDesktop;
const guardrailActive =
@@ -412,849 +466,1102 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
if (!isOpen) return null;
return (
- <Dialog isOpen onOpenChange={(open) => !open && onClose()} width={896} purpose="form">
+ <Dialog
+ isOpen
+ onOpenChange={(open) => !open && onClose()}
+ width={1000}
+ purpose="form"
+ className="rounded-xl"
+ >
<Layout
+ className="h-[min(820px,calc(100vh-40px))]"
header={
<DialogHeader
title="Export Video"
+ subtitle="Choose a ready-made preset or fine-tune every setting."
onOpenChange={(open) => !open && onClose()}
- startContent={<Download size={20} className="text-primary" aria-hidden />}
+ startContent={
+ <Download size={20} className="text-primary" aria-hidden />
+ }
/>
}
content={
- <LayoutContent className="flex max-h-[85vh] flex-col overflow-hidden p-0">
- <div className="border-b border-border p-2">
- <ToolcraftSegmentedControl<"presets" | "custom" | "reduce">
- ariaLabel="Export mode"
- value={activeTab}
- onChange={setActiveTab}
- options={[
- { value: "presets", label: "Presets" },
- { value: "reduce", label: "Reduce Size" },
- { value: "custom", label: "Custom" },
- ]}
- />
- </div>
-
- {sourceMatch && (
- <Button
- label="Quick Export Match Source"
- variant="ghost"
- onClick={handleMatchSourceExport}
- className="flex items-center justify-between gap-3 mx-3 mt-3 p-3 rounded-lg border border-primary/40 bg-primary/10 hover:bg-primary/15 transition-colors text-left"
- >
- <div className="flex items-center gap-2.5 min-w-0">
- <Zap size={16} className="text-primary shrink-0" />
- <div className="min-w-0">
- <div className="text-sm font-semibold text-text-primary">
- Quick Export — Match Source
- </div>
- <div className="text-[11px] text-text-muted truncate">
- {sourceMatch.width}×{sourceMatch.height}
- {sourceMatch.frameRate ? ` • ${sourceMatch.frameRate}fps` : ""} • MP4 · matches “{sourceMatch.sourceName}”
- </div>
- </div>
- </div>
- <span className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-primary text-black text-xs font-medium shrink-0">
- <Download size={14} />
- Export
- </span>
- </Button>
- )}
-
- {activeTab === "presets" && (
- <div className="flex flex-1 overflow-hidden">
- <div className="w-48 border-r border-border overflow-y-auto">
- <SelectableCard
- label="For Your Video"
- isSelected={selectedPlatform === "recommended"}
- onClick={() => setSelectedPlatform("recommended")}
- onChange={() => setSelectedPlatform("recommended")}
- padding={3}
- variant={selectedPlatform === "recommended" ? "green" : "muted"}
- className={`w-full flex flex-col items-start p-3 text-sm transition-colors ${
- selectedPlatform === "recommended"
- ? "bg-primary/10 text-primary border-r-2 border-primary"
- : "text-text-secondary hover:bg-background-tertiary"
- }`}
+ <LayoutContent className="flex min-h-0 flex-1 flex-col overflow-hidden bg-bg p-0">
+ <div className="shrink-0 space-y-3 border-b border-border bg-bg-1 px-5 py-4">
+ <ToolcraftSegmentedControl<"presets" | "custom" | "reduce">
+ ariaLabel="Export mode"
+ value={activeTab}
+ onChange={setActiveTab}
+ className="max-w-[440px] bg-bg-2"
+ options={[
+ { value: "presets", label: "Presets" },
+ { value: "reduce", label: "Smaller File" },
+ { value: "custom", label: "Custom Settings" },
+ ]}
+ />
+
+ {sourceMatch && activeTab === "presets" && (
+ <div
+ data-testid="quick-export-card"
+ className="flex min-h-[72px] items-center justify-between gap-4 rounded-[10px] border border-accent/30 bg-accent/5 px-4 py-3"
>
- <div className="flex items-center gap-2">
- <Zap size={14} />
- <span className="font-medium">For Your Video</span>
+ <div className="flex min-w-0 items-start gap-3">
+ <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-accent/15 text-accent">
+ <Zap size={16} aria-hidden />
+ </span>
+ <div className="min-w-0">
+ <div className="text-[13px] font-semibold text-fg">
+ Match source
+ </div>
+ <div className="mt-0.5 truncate text-[11px] text-fg-muted">
+ {sourceMatch.width}×{sourceMatch.height}
+ {sourceMatch.frameRate
+ ? ` · ${sourceMatch.frameRate} fps`
+ : ""}
+ {" · MP4 · "}
+ {sourceMatch.sourceName}
+ </div>
+ {matchSourceWebAdjustment?.wasAdjusted && (
+ <div className="mt-1 flex items-center gap-1.5 text-[11px] text-status-warning">
+ <AlertTriangle
+ size={11}
+ className="shrink-0"
+ aria-hidden
+ />
+ Browser limit: exports at{" "}
+ {matchSourceWebAdjustment.settings.width}×
+ {matchSourceWebAdjustment.settings.height} ·{" "}
+ {matchSourceWebAdjustment.settings.frameRate} fps
+ </div>
+ )}
+ </div>
</div>
- <span className="text-[10px] text-text-muted mt-0.5 ml-5">
- {getAspectRatioLabel(aspectType)}
- </span>
- </SelectableCard>
- <div className="h-px bg-border my-1" />
- {platforms.map((platform) => {
- const PlatformIcon = PLATFORM_ICONS[platform] ?? Globe;
- return (
- <SelectableCard
- key={platform}
- label={platform}
- isSelected={selectedPlatform === platform}
- onClick={() => setSelectedPlatform(platform)}
- onChange={() => setSelectedPlatform(platform)}
- padding={3}
- variant={selectedPlatform === platform ? "green" : "muted"}
- className={`w-full flex items-center gap-2 p-3 text-sm transition-colors ${
- selectedPlatform === platform
- ? "bg-primary/10 text-primary border-r-2 border-primary"
- : "text-text-secondary hover:bg-background-tertiary"
- }`}
- >
- <PlatformIcon size={14} />
- {platform}
- </SelectableCard>
- );
- })}
- </div>
+ <Button
+ label="Quick Export"
+ icon={<Download size={14} aria-hidden />}
+ variant="primary"
+ size="sm"
+ onClick={handleMatchSourceExport}
+ className="shrink-0"
+ />
+ </div>
+ )}
+ </div>
- <div className="flex-1 overflow-y-auto p-4">
- <div className="grid grid-cols-2 gap-3">
- {filteredPresets.map((preset) => {
- const PlatformIcon = PLATFORM_ICONS[preset.platform] ?? Globe;
+ {activeTab === "presets" && (
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="w-52 shrink-0 overflow-y-auto border-r border-border bg-bg-1 p-3">
+ <div className="px-2 pb-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-fg-muted">
+ Browse presets
+ </div>
+ <SelectableCard
+ label="For Your Video"
+ isSelected={selectedPlatform === "recommended"}
+ onClick={() => setSelectedPlatform("recommended")}
+ onChange={() => setSelectedPlatform("recommended")}
+ padding={0}
+ variant="transparent"
+ className={`mb-2 flex w-full flex-col items-start px-3 py-2.5 text-[12px] transition-colors ${
+ selectedPlatform === "recommended"
+ ? "border-accent/30 bg-selected text-fg shadow-none"
+ : "text-fg-2"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <Zap size={14} className="text-accent" />
+ <span className="font-semibold">Recommended</span>
+ </div>
+ <span className="ml-5 mt-1 text-[10px] leading-4 text-fg-muted">
+ {getAspectRatioLabel(aspectType)}
+ </span>
+ </SelectableCard>
+ <div className="mb-2 h-px bg-border" />
+ {platforms.map((platform) => {
+ const PlatformIcon = PLATFORM_ICONS[platform] ?? Globe;
return (
<SelectableCard
- key={preset.id}
- label={preset.name}
- isSelected={selectedPreset?.id === preset.id}
- onClick={() => setSelectedPreset(preset)}
- onChange={() => setSelectedPreset(preset)}
- padding={4}
- variant={selectedPreset?.id === preset.id ? "green" : "muted"}
- className={`p-4 rounded-lg border text-left transition-colors ${
- selectedPreset?.id === preset.id
- ? "border-primary bg-primary/10"
- : "border-border hover:border-primary/50"
+ key={platform}
+ label={platform}
+ isSelected={selectedPlatform === platform}
+ onClick={() => setSelectedPlatform(platform)}
+ onChange={() => setSelectedPlatform(platform)}
+ padding={0}
+ variant="transparent"
+ className={`mb-1 flex w-full items-center gap-2.5 px-3 py-2 text-[12px] transition-colors ${
+ selectedPlatform === platform
+ ? "border-accent/30 bg-selected text-fg shadow-none"
+ : "text-fg-2"
}`}
>
- <div className="flex items-start justify-between mb-2">
- <div className="flex items-center gap-2">
- <PlatformIcon size={16} />
- <span className="font-medium text-text-primary">
- {preset.name}
- </span>
- </div>
- {preset.recommended && (
- <Star
- size={12}
- className="text-yellow-500 fill-yellow-500"
- />
- )}
- </div>
- <Text type="supporting" color="secondary" display="block" className="mb-2 text-[10px]">
- {preset.description}
- </Text>
- {"width" in preset.settings && (
- <div className="flex items-center gap-3 text-[10px] text-text-secondary">
- <span>
- {(preset.settings as VideoExportSettings).width}x
- {(preset.settings as VideoExportSettings).height}
- </span>
- <span>
- {(preset.settings as VideoExportSettings).frameRate}
- fps
- </span>
- <span>{preset.aspectRatio}</span>
- </div>
- )}
- {preset.maxDuration && (
- <div className="flex items-center gap-1 mt-1 text-[10px] text-yellow-500">
- <Clock size={10} />
- Max {preset.maxDuration}s
- </div>
- )}
+ <PlatformIcon
+ size={14}
+ className={
+ selectedPlatform === platform
+ ? "text-accent"
+ : "text-fg-muted"
+ }
+ />
+ {platform}
</SelectableCard>
);
})}
- </div>
- </div>
- </div>
- )}
-
- {activeTab === "reduce" && (
- <div className="flex-1 overflow-y-auto p-4">
- <div className="max-w-xl mx-auto space-y-5">
- <div className="flex items-start gap-2.5 p-3 rounded-lg border border-border bg-background-tertiary/40">
- <Minimize2 size={16} className="text-primary shrink-0 mt-0.5" />
- <Text type="supporting" color="secondary" display="block" className="text-xs">
- Re-encode your project to a smaller file. Pick a quality tier,
- or a target size for sharing on email, WhatsApp, or Discord.
- </Text>
- </div>
-
- <div>
- <Text type="label" color="secondary" weight="bold" display="block" className="mb-2 text-xs">
- Reduce by
- </Text>
- <div className="flex gap-2">
- {(
- [
- ["quality", "Quality"],
- ["size", "Target size"],
- ] as const
- ).map(([value, label]) => (
- <SelectableCard
- key={value}
- label={label}
- isSelected={reduceMode === value}
- onClick={() => setReduceMode(value)}
- onChange={() => setReduceMode(value)}
- padding={2}
- variant={reduceMode === value ? "green" : "muted"}
- className={`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-colors ${
- reduceMode === value
- ? "border-primary bg-primary/10 text-primary"
- : "border-border text-text-secondary hover:border-primary/50"
- }`}
- >
- {label}
- </SelectableCard>
- ))}
- </div>
- </div>
-
- {reduceMode === "quality" ? (
- <div>
- <Text type="label" color="secondary" weight="bold" display="block" className="mb-2 text-xs">
- Quality
- </Text>
- <div className="grid grid-cols-3 gap-2">
- {(
- [
- ["light", "Light", "Trim a little"],
- ["balanced", "Balanced", "Best of both"],
- ["strong", "Strong", "Smallest file"],
- ] as const
- ).map(([value, label, hint]) => (
- <SelectableCard
- key={value}
- label={label}
- isSelected={reduceQuality === value}
- onClick={() => setReduceQuality(value)}
- onChange={() => setReduceQuality(value)}
- padding={2}
- variant={reduceQuality === value ? "green" : "muted"}
- className={`px-3 py-2.5 text-left rounded-md border transition-colors ${
- reduceQuality === value
- ? "border-primary bg-primary/10"
- : "border-border hover:border-primary/50"
- }`}
- >
- <div
- className={`text-xs font-semibold ${
- reduceQuality === value
- ? "text-primary"
- : "text-text-primary"
- }`}
- >
- {label}
- </div>
- <div className="text-[10px] text-text-muted mt-0.5">
- {hint}
- </div>
- </SelectableCard>
- ))}
- </div>
- </div>
- ) : (
- <div>
- <Text type="label" color="secondary" weight="bold" display="block" className="mb-2 text-xs">
- Target size
- </Text>
- <div className="grid grid-cols-3 gap-2">
- {COMPRESSION_SIZE_PRESETS.map((preset) => (
- <SelectableCard
- key={preset.id}
- label={preset.label}
- isSelected={reduceSizePresetId === preset.id}
- onClick={() => setReduceSizePresetId(preset.id)}
- onChange={() => setReduceSizePresetId(preset.id)}
- padding={2}
- variant={reduceSizePresetId === preset.id ? "green" : "muted"}
- className={`px-3 py-2.5 rounded-md border text-xs font-medium capitalize transition-colors ${
- reduceSizePresetId === preset.id
- ? "border-primary bg-primary/10 text-primary"
- : "border-border text-text-secondary hover:border-primary/50"
- }`}
- >
- {preset.label}
- </SelectableCard>
- ))}
- </div>
- </div>
- )}
-
- {reducePlan ? (
- <div className="rounded-lg border border-border bg-background-tertiary/40 p-4 space-y-2.5">
- <div className="flex items-center justify-between">
- <span className="text-xs text-text-secondary">
- Estimated output
- </span>
- <span className="text-sm font-semibold text-text-primary">
- {reducePlan.width}×{reducePlan.height} · ~
- {formatBytes(reduceEstimatedBytes)}
+ </aside>
+
+ <main className="min-w-0 flex-1 overflow-y-auto p-5">
+ <div className="mb-4 flex items-end justify-between gap-4">
+ <div>
+ <h3 className="text-[14px] font-semibold text-fg">
+ {selectedPlatform === "recommended"
+ ? "Recommended for this video"
+ : selectedPlatform}
+ </h3>
+ <p className="mt-1 text-[11px] text-fg-muted">
+ Select a preset to see its estimated size and export
+ time.
+ </p>
+ </div>
+ <span className="shrink-0 rounded-full bg-bg-2 px-2.5 py-1 text-[10px] font-medium text-fg-muted">
+ {filteredPresets.length} options
</span>
</div>
- <div className="flex items-center justify-between text-[11px]">
- <span className="text-text-muted">
- {reducePlan.videoBitrateKbps.toLocaleString()} kbps video
- {reducePlan.audioBitrateKbps > 0
- ? ` · ${reducePlan.audioBitrateKbps} kbps audio`
- : ""}{" "}
- · {reducePlan.frameRate}fps
- </span>
- {reduceSavingsPercent > 0 && (
- <span className="font-bold text-primary">
- −{reduceSavingsPercent}% vs source
- </span>
- )}
+ <div className="grid grid-cols-2 gap-3">
+ {filteredPresets.map((preset) => {
+ const PlatformIcon =
+ PLATFORM_ICONS[preset.platform] ?? Globe;
+ const isSelected = selectedPreset?.id === preset.id;
+ return (
+ <SelectableCard
+ key={preset.id}
+ label={preset.name}
+ isSelected={selectedPreset?.id === preset.id}
+ onClick={() => setSelectedPreset(preset)}
+ onChange={() => setSelectedPreset(preset)}
+ padding={0}
+ variant="default"
+ className={`min-h-[118px] rounded-[10px] p-4 text-left ${
+ isSelected
+ ? "border-accent bg-selected shadow-[0_0_0_1px_var(--accent)]"
+ : "border-border bg-bg-1 hover:border-accent/40 hover:bg-bg-2"
+ }`}
+ >
+ <div className="mb-2.5 flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-bg-2 text-fg-2">
+ <PlatformIcon size={14} />
+ </span>
+ <span className="truncate text-[12px] font-semibold text-fg">
+ {preset.name}
+ </span>
+ </div>
+ {isSelected ? (
+ <CheckCircle
+ size={15}
+ className="shrink-0 text-accent"
+ aria-hidden
+ />
+ ) : preset.recommended ? (
+ <Star
+ size={13}
+ className="shrink-0 fill-status-warning text-status-warning"
+ />
+ ) : null}
+ </div>
+ <Text
+ type="supporting"
+ color="secondary"
+ display="block"
+ className="mb-3 line-clamp-2 min-h-8 text-[11px] leading-4"
+ >
+ {preset.description}
+ </Text>
+ {"width" in preset.settings && (
+ <div className="flex flex-wrap items-center gap-1.5 text-[10px] text-fg-muted">
+ <span className="rounded bg-bg-2 px-1.5 py-0.5">
+ {(preset.settings as VideoExportSettings).width}
+ x
+ {
+ (preset.settings as VideoExportSettings)
+ .height
+ }
+ </span>
+ <span className="rounded bg-bg-2 px-1.5 py-0.5">
+ {
+ (preset.settings as VideoExportSettings)
+ .frameRate
+ }
+ {" fps"}
+ </span>
+ <span className="rounded bg-bg-2 px-1.5 py-0.5">
+ {preset.aspectRatio}
+ </span>
+ </div>
+ )}
+ {preset.maxDuration && (
+ <div className="mt-2 flex items-center gap-1 text-[10px] text-status-warning">
+ <Clock size={10} />
+ Max {preset.maxDuration}s
+ </div>
+ )}
+ </SelectableCard>
+ );
+ })}
</div>
- </div>
- ) : (
- <div className="rounded-lg border border-border bg-background-tertiary/40 p-4 text-xs text-text-muted">
- Add clips to the timeline to estimate a compressed size.
- </div>
- )}
- </div>
- </div>
- )}
-
- {activeTab === "custom" && (
- <div className="flex-1 overflow-y-auto p-4">
- <div className="grid grid-cols-2 gap-4">
- <div>
- <Selector
- label="Format"
- value={customSettings.format}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- format: value as "mp4" | "webm" | "mov",
- })
- }
- options={[
- { value: "mp4", label: "MP4" },
- { value: "webm", label: "WebM" },
- { value: "mov", label: "MOV" },
- ]}
- width="100%"
- />
- </div>
-
- <div>
- <Selector
- label="Codec"
- value={customSettings.codec}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- codec: value as VideoExportSettings["codec"],
- })
- }
- options={[
- { value: "h264", label: "H.264" },
- { value: "h265", label: "H.265 (HEVC)" },
- { value: "prores", label: "ProRes" },
- { value: "vp9", label: "VP9" },
- { value: "av1", label: "AV1" },
- ]}
- width="100%"
- />
- </div>
-
- <div>
- <Selector
- label="Resolution"
- value={`${customSettings.width}x${customSettings.height}`}
- onChange={(value) => {
- const [w, h] = value.split("x").map(Number);
- setCustomSettings({
- ...customSettings,
- width: w,
- height: h,
- });
- }}
- options={[
- ...(sourceMatch &&
- ![
- "3840x2160",
- "2560x1440",
- "1920x1080",
- "1280x720",
- "854x480",
- "1080x1920",
- "1080x1080",
- ].includes(`${sourceMatch.width}x${sourceMatch.height}`)
- ? [
- {
- value: `${sourceMatch.width}x${sourceMatch.height}`,
- label: `Original (${sourceMatch.width}x${sourceMatch.height})`,
- },
- ]
- : []),
- { value: "3840x2160", label: "4K (3840x2160)" },
- { value: "2560x1440", label: "2K (2560x1440)" },
- { value: "1920x1080", label: "1080p (1920x1080)" },
- { value: "1280x720", label: "720p (1280x720)" },
- { value: "854x480", label: "480p (854x480)" },
- { value: "1080x1920", label: "Vertical 1080p" },
- { value: "1080x1080", label: "Square 1080" },
- ]}
- width="100%"
- />
- </div>
-
- <div>
- <Selector
- label="Frame Rate"
- value={String(customSettings.frameRate)}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- frameRate: Number(value),
- })
- }
- options={[
- { value: "24", label: "24 fps" },
- { value: "25", label: "25 fps" },
- { value: "30", label: "30 fps" },
- { value: "50", label: "50 fps" },
- { value: "60", label: "60 fps" },
- ]}
- width="100%"
- />
- </div>
-
- <div>
- <ToolcraftNumberInputControl
- label="Bitrate (kbps)"
- value={customSettings.bitrate}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- bitrate: value || 0,
- })
- }
- min={1000}
- max={150000}
- step={1000}
- width="100%"
- />
- </div>
+ </main>
+ </div>
+ )}
- <div>
- <ToolcraftSliderControl
- label="Quality"
- value={customSettings.quality}
- onChange={(quality: number) =>
- setCustomSettings({
- ...customSettings,
- quality,
- })
- }
- min={50}
- max={100}
- step={1}
- valueDisplay="none"
- />
- <div className="flex justify-between text-[10px] text-text-muted mt-1">
- <span>Smaller</span>
- <span>{customSettings.quality}%</span>
- <span>Better</span>
+ {activeTab === "reduce" && (
+ <div className="flex-1 overflow-y-auto p-4">
+ <div className="max-w-xl mx-auto space-y-5">
+ <div className="flex items-start gap-2.5 p-3 rounded-lg border border-border bg-background-tertiary/40">
+ <Minimize2
+ size={16}
+ className="text-primary shrink-0 mt-0.5"
+ />
+ <Text
+ type="supporting"
+ color="secondary"
+ display="block"
+ className="text-xs"
+ >
+ Re-encode your project to a smaller file. Pick a quality
+ tier, or a target size for sharing on email, WhatsApp, or
+ Discord.
+ </Text>
</div>
- </div>
- {isDesktop && (
- <div className="col-span-2">
- <Text type="supporting" color="secondary" weight="bold" display="block" className="mb-2 text-xs">
- Export mode
+ <div>
+ <Text
+ type="label"
+ color="secondary"
+ weight="bold"
+ display="block"
+ className="mb-2 text-xs"
+ >
+ Reduce by
</Text>
<div className="flex gap-2">
{(
[
- ["fast", "Fast", "Hardware, quickest"],
- ["balanced", "Balanced", "Hardware, great quality + small"],
- ["smallest", "Smallest", "Software, tiniest files (slow)"],
- ] as const
+ ["quality", "Quality"],
+ ["size", "Target size"],
+ ] as const
).map(([value, label]) => (
<SelectableCard
key={value}
label={label}
- isSelected={customSettings.encodeMode === value}
- onChange={() =>
- setCustomSettings({ ...customSettings, encodeMode: value })
- }
+ isSelected={reduceMode === value}
+ onClick={() => setReduceMode(value)}
+ onChange={() => setReduceMode(value)}
padding={2}
- variant={customSettings.encodeMode === value ? "green" : "muted"}
- className="flex-1 text-center text-[10px]"
+ variant={reduceMode === value ? "green" : "muted"}
+ className={`flex-1 px-3 py-2 text-xs font-medium rounded-md border transition-colors ${
+ reduceMode === value
+ ? "border-primary bg-primary/10 text-primary"
+ : "border-border text-text-secondary hover:border-primary/50"
+ }`}
>
{label}
</SelectableCard>
))}
</div>
</div>
- )}
- <div className="col-span-2">
- <Text type="supporting" color="secondary" weight="bold" display="block" className="mb-2 text-xs">
- Audio Settings
- </Text>
- <div className="grid grid-cols-3 gap-2">
- <Selector
- label="Audio format"
- isLabelHidden
- value={customSettings.audioSettings.format}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- audioSettings: {
- ...customSettings.audioSettings,
- format: value as
- | "mp3"
- | "wav"
- | "aac"
- | "flac"
- | "ogg",
- },
- })
- }
- options={[
- { value: "aac", label: "AAC" },
- { value: "mp3", label: "MP3" },
- { value: "wav", label: "WAV" },
- ]}
- size="sm"
- width="100%"
- />
- <Selector
- label="Sample rate"
- isLabelHidden
- value={String(customSettings.audioSettings.sampleRate)}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- audioSettings: {
- ...customSettings.audioSettings,
- sampleRate: Number(value) as
- | 44100
- | 48000
- | 96000,
- },
- })
- }
- options={[
- { value: "44100", label: "44.1 kHz" },
- { value: "48000", label: "48 kHz" },
- { value: "96000", label: "96 kHz" },
- ]}
- size="sm"
- width="100%"
- />
- <Selector
- label="Audio bitrate"
- isLabelHidden
- value={String(customSettings.audioSettings.bitrate)}
- onChange={(value) =>
- setCustomSettings({
- ...customSettings,
- audioSettings: {
- ...customSettings.audioSettings,
- bitrate: Number(value),
- },
- })
- }
- options={[
- { value: "128", label: "128 kbps" },
- { value: "192", label: "192 kbps" },
- { value: "256", label: "256 kbps" },
- { value: "320", label: "320 kbps" },
- ]}
- size="sm"
- width="100%"
- />
- </div>
- </div>
-
- <div className="col-span-2 border-t border-border pt-4 mt-2">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Zap size={14} className="text-primary" />
- <Text type="supporting" color="secondary" weight="bold" className="text-xs">
- Enhance Quality (Upscaling)
+ {reduceMode === "quality" ? (
+ <div>
+ <Text
+ type="label"
+ color="secondary"
+ weight="bold"
+ display="block"
+ className="mb-2 text-xs"
+ >
+ Quality
</Text>
+ <div className="grid grid-cols-3 gap-2">
+ {(
+ [
+ ["light", "Light", "Trim a little"],
+ ["balanced", "Balanced", "Best of both"],
+ ["strong", "Strong", "Smallest file"],
+ ] as const
+ ).map(([value, label, hint]) => (
+ <SelectableCard
+ key={value}
+ label={label}
+ isSelected={reduceQuality === value}
+ onClick={() => setReduceQuality(value)}
+ onChange={() => setReduceQuality(value)}
+ padding={2}
+ variant={
+ reduceQuality === value ? "green" : "muted"
+ }
+ className={`px-3 py-2.5 text-left rounded-md border transition-colors ${
+ reduceQuality === value
+ ? "border-primary bg-primary/10"
+ : "border-border hover:border-primary/50"
+ }`}
+ >
+ <div
+ className={`text-xs font-semibold ${
+ reduceQuality === value
+ ? "text-primary"
+ : "text-text-primary"
+ }`}
+ >
+ {label}
+ </div>
+ <div className="text-[10px] text-text-muted mt-0.5">
+ {hint}
+ </div>
+ </SelectableCard>
+ ))}
+ </div>
</div>
- <ToolcraftSwitchControl
- ariaLabel="Enhance Quality (Upscaling)"
- checked={customSettings.upscaling?.enabled ?? false}
- showLabel={false}
- onCheckedChange={(checked) =>
- setCustomSettings({
- ...customSettings,
- upscaling: {
- ...customSettings.upscaling!,
- enabled: checked,
- },
- })
- }
- />
+ ) : (
+ <div>
+ <Text
+ type="label"
+ color="secondary"
+ weight="bold"
+ display="block"
+ className="mb-2 text-xs"
+ >
+ Target size
+ </Text>
+ <div className="grid grid-cols-3 gap-2">
+ {COMPRESSION_SIZE_PRESETS.map((preset) => (
+ <SelectableCard
+ key={preset.id}
+ label={preset.label}
+ isSelected={reduceSizePresetId === preset.id}
+ onClick={() => setReduceSizePresetId(preset.id)}
+ onChange={() => setReduceSizePresetId(preset.id)}
+ padding={2}
+ variant={
+ reduceSizePresetId === preset.id
+ ? "green"
+ : "muted"
+ }
+ className={`px-3 py-2.5 rounded-md border text-xs font-medium capitalize transition-colors ${
+ reduceSizePresetId === preset.id
+ ? "border-primary bg-primary/10 text-primary"
+ : "border-border text-text-secondary hover:border-primary/50"
+ }`}
+ >
+ {preset.label}
+ </SelectableCard>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {reducePlan ? (
+ <div className="rounded-lg border border-border bg-background-tertiary/40 p-4 space-y-2.5">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-text-secondary">
+ Estimated output
+ </span>
+ <span className="text-sm font-semibold text-text-primary">
+ {reducePlan.width}×{reducePlan.height} · ~
+ {formatBytes(reduceEstimatedBytes)}
+ </span>
+ </div>
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-text-muted">
+ {reducePlan.videoBitrateKbps.toLocaleString()} kbps
+ video
+ {reducePlan.audioBitrateKbps > 0
+ ? ` · ${reducePlan.audioBitrateKbps} kbps audio`
+ : ""}{" "}
+ · {reducePlan.frameRate}fps
+ </span>
+ {reduceSavingsPercent > 0 && (
+ <span className="font-bold text-primary">
+ −{reduceSavingsPercent}% vs source
+ </span>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-lg border border-border bg-background-tertiary/40 p-4 text-xs text-text-muted">
+ Add clips to the timeline to estimate a compressed size.
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {activeTab === "custom" && (
+ <div className="min-h-0 flex-1 overflow-y-auto p-5">
+ <div className="mx-auto max-w-[760px] space-y-4">
+ <div>
+ <h3 className="text-[14px] font-semibold text-fg">
+ Custom export
+ </h3>
+ <p className="mt-1 text-[11px] text-fg-muted">
+ Control the video, encoding, and audio settings for this
+ file.
+ </p>
</div>
- {customSettings.upscaling?.enabled && (
- <div className="space-y-3 pl-6">
+ <section className="rounded-[10px] border border-border bg-bg-1 p-4">
+ <div className="mb-4 flex items-center gap-2.5">
+ <span className="flex h-7 w-7 items-center justify-center rounded-md bg-bg-2 text-fg-2">
+ <Video size={14} aria-hidden />
+ </span>
<div>
- <Text type="supporting" color="secondary" display="block" className="mb-1.5 text-[10px]">
- Quality Mode
- </Text>
- <div className="flex gap-2">
- {(["fast", "balanced", "quality"] as const).map(
- (mode) => (
- <SelectableCard
- key={mode}
- label={mode}
- isSelected={customSettings.upscaling?.quality === mode}
- onChange={() =>
- setCustomSettings({
- ...customSettings,
- upscaling: {
- ...customSettings.upscaling!,
- quality: mode as UpscaleQuality,
- },
- })
- }
- padding={2}
- variant={customSettings.upscaling?.quality === mode ? "green" : "muted"}
- className="flex-1 text-center text-[10px]"
- >
- {mode.charAt(0).toUpperCase() + mode.slice(1)}
- </SelectableCard>
- ),
- )}
- </div>
+ <h4 className="text-[12px] font-semibold text-fg">
+ Video
+ </h4>
+ <p className="text-[10px] text-fg-muted">
+ Container, codec, resolution, and frame rate
+ </p>
</div>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <Selector
+ label="Format"
+ value={customSettings.format}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ format: value as "mp4" | "webm" | "mov",
+ })
+ }
+ options={[
+ { value: "mp4", label: "MP4" },
+ { value: "webm", label: "WebM" },
+ { value: "mov", label: "MOV" },
+ ]}
+ width="100%"
+ />
+
+ <Selector
+ label="Codec"
+ value={customSettings.codec}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ codec: value as VideoExportSettings["codec"],
+ })
+ }
+ options={[
+ { value: "h264", label: "H.264" },
+ { value: "h265", label: "H.265 (HEVC)" },
+ { value: "prores", label: "ProRes" },
+ { value: "vp9", label: "VP9" },
+ { value: "av1", label: "AV1" },
+ ]}
+ width="100%"
+ />
+
+ <Selector
+ label="Resolution"
+ value={`${customSettings.width}x${customSettings.height}`}
+ onChange={(value) => {
+ const [w, h] = value.split("x").map(Number);
+ setCustomSettings({
+ ...customSettings,
+ width: w,
+ height: h,
+ });
+ }}
+ options={[
+ ...(sourceMatch &&
+ ![
+ "3840x2160",
+ "2560x1440",
+ "1920x1080",
+ "1280x720",
+ "854x480",
+ "1080x1920",
+ "1080x1080",
+ ].includes(
+ `${sourceMatch.width}x${sourceMatch.height}`,
+ )
+ ? [
+ {
+ value: `${sourceMatch.width}x${sourceMatch.height}`,
+ label: `Original (${sourceMatch.width}x${sourceMatch.height})`,
+ },
+ ]
+ : []),
+ { value: "3840x2160", label: "4K (3840x2160)" },
+ { value: "2560x1440", label: "2K (2560x1440)" },
+ { value: "1920x1080", label: "1080p (1920x1080)" },
+ { value: "1280x720", label: "720p (1280x720)" },
+ { value: "854x480", label: "480p (854x480)" },
+ { value: "1080x1920", label: "Vertical 1080p" },
+ { value: "1080x1080", label: "Square 1080" },
+ ]}
+ width="100%"
+ />
+
+ <Selector
+ label="Frame rate"
+ value={String(customSettings.frameRate)}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ frameRate: Number(value),
+ })
+ }
+ options={EDITING_FRAME_RATE_OPTIONS.map((option) => ({
+ value: String(option.value),
+ label: option.label,
+ }))}
+ width="100%"
+ />
+ </div>
+ </section>
+
+ <section className="rounded-[10px] border border-border bg-bg-1 p-4">
+ <div className="mb-4 flex items-center gap-2.5">
+ <span className="flex h-7 w-7 items-center justify-center rounded-md bg-bg-2 text-fg-2">
+ <Gauge size={14} aria-hidden />
+ </span>
+ <div>
+ <h4 className="text-[12px] font-semibold text-fg">
+ Quality & encoding
+ </h4>
+ <p className="text-[10px] text-fg-muted">
+ Balance output quality, speed, and file size
+ </p>
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <ToolcraftNumberInputControl
+ label="Bitrate (kbps)"
+ value={customSettings.bitrate}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ bitrate: value || 0,
+ })
+ }
+ min={1000}
+ max={150000}
+ step={1000}
+ width="100%"
+ />
<div>
<ToolcraftSliderControl
- label="Sharpening"
- value={Math.round((customSettings.upscaling?.sharpening ?? 0.3) * 100)}
- onChange={(value: number) =>
+ label="Quality"
+ value={customSettings.quality}
+ onChange={(quality: number) =>
setCustomSettings({
...customSettings,
- upscaling: {
- ...customSettings.upscaling!,
- sharpening: value / 100,
- },
+ quality,
})
}
- min={0}
+ min={50}
max={100}
step={1}
valueDisplay="none"
/>
- <div className="flex justify-between text-[10px] text-text-muted mt-1">
- <span>None</span>
- <span>
- {Math.round(
- (customSettings.upscaling?.sharpening ?? 0.3) *
- 100,
- )}
- %
+ <div className="mt-1 flex justify-between text-[10px] text-fg-muted">
+ <span>Smaller</span>
+ <span className="font-semibold text-fg-2">
+ {customSettings.quality}%
</span>
- <span>Max</span>
+ <span>Better</span>
</div>
</div>
- <Text type="supporting" color="secondary" display="block" className="text-[10px]">
- Enhance quality when exporting to higher resolutions
- than source. Uses edge-directed interpolation for
- sharper details.
- </Text>
+ {isDesktop && (
+ <div className="col-span-2 border-t border-border pt-4">
+ <Text
+ type="supporting"
+ color="secondary"
+ weight="bold"
+ display="block"
+ className="mb-2 text-[11px]"
+ >
+ Export mode
+ </Text>
+ <div className="grid grid-cols-3 gap-2">
+ {(
+ [
+ ["fast", "Fast", "Hardware, quickest"],
+ [
+ "balanced",
+ "Balanced",
+ "Hardware, great quality + small",
+ ],
+ [
+ "smallest",
+ "Smallest",
+ "Software, smallest file",
+ ],
+ ] as const
+ ).map(([value, label, hint]) => (
+ <SelectableCard
+ key={value}
+ label={label}
+ isSelected={customSettings.encodeMode === value}
+ onChange={() =>
+ setCustomSettings({
+ ...customSettings,
+ encodeMode: value,
+ })
+ }
+ padding={0}
+ variant="default"
+ className="min-h-[58px] px-3 py-2.5 text-left"
+ >
+ <span className="block text-[11px] font-semibold text-fg">
+ {label}
+ </span>
+ <span className="mt-0.5 block text-[9px] leading-3 text-fg-muted">
+ {hint}
+ </span>
+ </SelectableCard>
+ ))}
+ </div>
+ </div>
+ )}
</div>
- )}
+ </section>
+
+ <section className="rounded-[10px] border border-border bg-bg-1 p-4">
+ <div className="mb-4 flex items-center gap-2.5">
+ <span className="flex h-7 w-7 items-center justify-center rounded-md bg-bg-2 text-fg-2">
+ <Music size={14} aria-hidden />
+ </span>
+ <div>
+ <h4 className="text-[12px] font-semibold text-fg">
+ Audio
+ </h4>
+ <p className="text-[10px] text-fg-muted">
+ Format, sample rate, and bitrate
+ </p>
+ </div>
+ </div>
+ <div className="grid grid-cols-3 gap-2">
+ <Selector
+ label="Audio format"
+ value={customSettings.audioSettings.format}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ audioSettings: {
+ ...customSettings.audioSettings,
+ format: value as
+ | "mp3"
+ | "wav"
+ | "aac"
+ | "flac"
+ | "ogg",
+ },
+ })
+ }
+ options={[
+ { value: "aac", label: "AAC" },
+ { value: "mp3", label: "MP3" },
+ { value: "wav", label: "WAV" },
+ ]}
+ size="sm"
+ width="100%"
+ />
+ <Selector
+ label="Sample rate"
+ value={String(customSettings.audioSettings.sampleRate)}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ audioSettings: {
+ ...customSettings.audioSettings,
+ sampleRate: Number(value) as
+ | 44100
+ | 48000
+ | 96000,
+ },
+ })
+ }
+ options={[
+ { value: "44100", label: "44.1 kHz" },
+ { value: "48000", label: "48 kHz" },
+ { value: "96000", label: "96 kHz" },
+ ]}
+ size="sm"
+ width="100%"
+ />
+ <Selector
+ label="Audio bitrate"
+ value={String(customSettings.audioSettings.bitrate)}
+ onChange={(value) =>
+ setCustomSettings({
+ ...customSettings,
+ audioSettings: {
+ ...customSettings.audioSettings,
+ bitrate: Number(value),
+ },
+ })
+ }
+ options={[
+ { value: "128", label: "128 kbps" },
+ { value: "192", label: "192 kbps" },
+ { value: "256", label: "256 kbps" },
+ { value: "320", label: "320 kbps" },
+ ]}
+ size="sm"
+ width="100%"
+ />
+ </div>
+ </section>
+
+ <section className="rounded-[10px] border border-border bg-bg-1 p-4">
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex items-center gap-2.5">
+ <span className="flex h-7 w-7 items-center justify-center rounded-md bg-accent/10 text-accent">
+ <Zap size={14} aria-hidden />
+ </span>
+ <div>
+ <h4 className="text-[12px] font-semibold text-fg">
+ Enhance quality
+ </h4>
+ <p className="text-[10px] text-fg-muted">
+ Sharpen exports above the source resolution
+ </p>
+ </div>
+ </div>
+ <ToolcraftSwitchControl
+ ariaLabel="Enhance quality with upscaling"
+ checked={customSettings.upscaling?.enabled ?? false}
+ showLabel={false}
+ onCheckedChange={(checked) =>
+ setCustomSettings({
+ ...customSettings,
+ upscaling: {
+ ...customSettings.upscaling!,
+ enabled: checked,
+ },
+ })
+ }
+ />
+ </div>
+
+ {customSettings.upscaling?.enabled && (
+ <div className="mt-4 space-y-4 border-t border-border pt-4">
+ <div>
+ <Text
+ type="supporting"
+ color="secondary"
+ display="block"
+ className="mb-2 text-[10px] font-semibold"
+ >
+ Quality Mode
+ </Text>
+ <div className="grid grid-cols-3 gap-2">
+ {(["fast", "balanced", "quality"] as const).map(
+ (mode) => (
+ <SelectableCard
+ key={mode}
+ label={mode}
+ isSelected={
+ customSettings.upscaling?.quality === mode
+ }
+ onChange={() =>
+ setCustomSettings({
+ ...customSettings,
+ upscaling: {
+ ...customSettings.upscaling!,
+ quality: mode as UpscaleQuality,
+ },
+ })
+ }
+ padding={0}
+ variant="default"
+ className="px-3 py-2 text-center text-[10px] font-semibold"
+ >
+ {mode.charAt(0).toUpperCase() + mode.slice(1)}
+ </SelectableCard>
+ ),
+ )}
+ </div>
+ </div>
+
+ <div>
+ <ToolcraftSliderControl
+ label="Sharpening"
+ value={Math.round(
+ (customSettings.upscaling?.sharpening ?? 0.3) *
+ 100,
+ )}
+ onChange={(value: number) =>
+ setCustomSettings({
+ ...customSettings,
+ upscaling: {
+ ...customSettings.upscaling!,
+ sharpening: value / 100,
+ },
+ })
+ }
+ min={0}
+ max={100}
+ step={1}
+ valueDisplay="none"
+ />
+ <div className="mt-1 flex justify-between text-[10px] text-fg-muted">
+ <span>None</span>
+ <span className="font-semibold text-fg-2">
+ {Math.round(
+ (customSettings.upscaling?.sharpening ?? 0.3) *
+ 100,
+ )}
+ %
+ </span>
+ <span>Max</span>
+ </div>
+ </div>
+
+ <p className="rounded-md bg-bg-2 px-3 py-2 text-[10px] leading-4 text-fg-muted">
+ Best used when exporting above the project resolution.
+ It adds processing time.
+ </p>
+ </div>
+ )}
+ </section>
</div>
</div>
- </div>
- )}
-
- {deviceProfile && (
- <div className="px-4 py-3 border-t border-border bg-background-tertiary/50">
- <div className="flex items-center justify-between">
- <Button
- label="Show device export estimate details"
- variant="ghost"
- onClick={() => setShowDeviceInfo(!showDeviceInfo)}
- className="flex items-center gap-2 text-xs text-text-secondary hover:text-text-primary transition-colors"
- >
- <Cpu size={12} />
- <span>{formatDeviceSummary(deviceProfile)}</span>
- <Info size={10} className="text-text-muted" />
- </Button>
-
- {timeEstimate && (
- <div className="flex items-center gap-3">
- <div className="flex items-center gap-1.5 text-xs">
- {timeEstimate.confidence === "measured" ? (
- <CheckCircle size={12} className="text-green-500" />
- ) : (
- <Gauge size={12} className="text-yellow-500" />
- )}
- <span className="text-text-secondary">Est. time:</span>
- <span className="font-medium text-text-primary">
- {timeEstimate.formatted}
- </span>
- </div>
-
- {shouldRecommendBenchmark(deviceProfile) && !isBenchmarking && (
- <Button
- label="Get accurate estimate"
- variant="ghost"
- onClick={handleRunBenchmark}
- className="flex items-center gap-1 px-2 py-1 text-[10px] text-primary bg-primary/10 rounded hover:bg-primary/20 transition-colors"
- >
- <Zap size={10} />
- Get accurate estimate
- </Button>
- )}
+ )}
- {isBenchmarking && benchmarkProgress && (
- <div className="flex items-center gap-2 text-[10px] text-text-muted">
- <div className="w-16 h-1 bg-background-tertiary rounded-full overflow-hidden">
- <div
- className="h-full bg-primary transition-all"
- style={{ width: `${benchmarkProgress.progress * 100}%` }}
- />
+ {deviceProfile && (
+ <div className="shrink-0 border-t border-border bg-bg-1 px-5 py-2.5">
+ <div className="flex items-center justify-between gap-4">
+ <Button
+ label="Show device export estimate details"
+ variant="ghost"
+ size="sm"
+ onClick={() => setShowDeviceInfo(!showDeviceInfo)}
+ className="-ml-2 text-[11px] text-fg-muted"
+ >
+ <Cpu size={12} />
+ <span>{formatDeviceSummary(deviceProfile)}</span>
+ <Info size={10} className="text-fg-muted" />
+ </Button>
+
+ {timeEstimate && (
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-1.5 rounded-full bg-bg-2 px-2.5 py-1 text-[11px]">
+ {timeEstimate.confidence === "measured" ? (
+ <CheckCircle
+ size={12}
+ className="text-status-success"
+ />
+ ) : (
+ <Gauge size={12} className="text-status-warning" />
+ )}
+ <span className="text-fg-muted">Estimate</span>
+ <span className="font-semibold text-fg">
+ {timeEstimate.formatted}
+ </span>
</div>
- <span>Testing...</span>
+
+ {shouldRecommendBenchmark(deviceProfile) &&
+ !isBenchmarking && (
+ <Button
+ label="Get accurate estimate"
+ variant="ghost"
+ size="sm"
+ onClick={handleRunBenchmark}
+ className="text-[10px] text-accent"
+ >
+ <Zap size={10} />
+ Get accurate estimate
+ </Button>
+ )}
+
+ {isBenchmarking && benchmarkProgress && (
+ <div className="flex items-center gap-2 text-[10px] text-fg-muted">
+ <div className="h-1 w-16 overflow-hidden rounded-full bg-bg-3">
+ <div
+ className="h-full bg-accent transition-all"
+ style={{
+ width: `${benchmarkProgress.progress * 100}%`,
+ }}
+ />
+ </div>
+ <span>Testing...</span>
+ </div>
+ )}
</div>
)}
</div>
- )}
- </div>
- {showDeviceInfo && (
- <div className="mt-3 pt-3 border-t border-border/50 grid grid-cols-3 gap-4 text-[10px]">
- <div>
- <span className="text-text-muted">CPU</span>
- <Text type="supporting" weight="bold" display="block" className="text-text-primary">
- {deviceProfile.cpu.cores} cores
- </Text>
- </div>
- <div>
- <span className="text-text-muted">GPU</span>
- <Text type="supporting" weight="bold" display="block" className="truncate text-text-primary">
- {deviceProfile.gpu.renderer !== "Unknown"
- ? deviceProfile.gpu.renderer.replace(/ANGLE \(|, .*\)/g, "").replace(/Direct3D11.*$/g, "").trim()
- : "Unknown"}
- </Text>
- <Text type="supporting" color="secondary" display="block" className="text-[9px]">
- {deviceProfile.gpu.hasHardwareEncoding ? "HW Encode" : "Software only"}
- </Text>
- </div>
- <div>
- <span className="text-text-muted">Codecs</span>
- <div className="flex gap-1 flex-wrap">
- {codecRecommendations.slice(0, 3).map((rec) => (
- <span
- key={rec.codec}
- className={`px-1 py-0.5 rounded text-[9px] ${
- rec.speedRating === "fast"
- ? "bg-green-500/20 text-green-400"
- : rec.speedRating === "medium"
- ? "bg-yellow-500/20 text-yellow-400"
- : "bg-red-500/20 text-red-400"
- }`}
+ {showDeviceInfo && (
+ <div className="mt-2 grid grid-cols-3 gap-4 rounded-lg bg-bg-2 px-3 py-2.5 text-[10px]">
+ <div>
+ <span className="text-fg-muted">CPU</span>
+ <Text
+ type="supporting"
+ weight="bold"
+ display="block"
+ className="text-fg"
>
- {rec.codec.toUpperCase()}
- </span>
- ))}
+ {deviceProfile.cpu.cores} cores
+ </Text>
+ </div>
+ <div>
+ <span className="text-fg-muted">GPU</span>
+ <Text
+ type="supporting"
+ weight="bold"
+ display="block"
+ className="truncate text-fg"
+ >
+ {deviceProfile.gpu.renderer !== "Unknown"
+ ? deviceProfile.gpu.renderer
+ .replace(/ANGLE \(|, .*\)/g, "")
+ .replace(/Direct3D11.*$/g, "")
+ .trim()
+ : "Unknown"}
+ </Text>
+ <Text
+ type="supporting"
+ color="secondary"
+ display="block"
+ className="text-[9px]"
+ >
+ {deviceProfile.gpu.hasHardwareEncoding
+ ? "HW Encode"
+ : "Software only"}
+ </Text>
+ </div>
+ <div>
+ <span className="text-fg-muted">Codecs</span>
+ <div className="flex flex-wrap gap-1">
+ {codecRecommendations.slice(0, 3).map((rec) => (
+ <span
+ key={rec.codec}
+ className={`px-1 py-0.5 rounded text-[9px] ${
+ rec.speedRating === "fast"
+ ? "bg-status-success/15 text-status-success"
+ : rec.speedRating === "medium"
+ ? "bg-status-warning/15 text-status-warning"
+ : "bg-status-error/15 text-status-error"
+ }`}
+ >
+ {rec.codec.toUpperCase()}
+ </span>
+ ))}
+ </div>
+ </div>
</div>
- </div>
+ )}
</div>
)}
- </div>
- )}
-
</LayoutContent>
}
footer={
- <LayoutFooter hasDivider>
- {guardrailActive && (
- <div
- role="alert"
- className="mb-3 flex flex-col gap-2 rounded-md border border-yellow-500/40 bg-yellow-500/10 p-3"
+ <LayoutFooter
+ hasDivider
+ className="flex-col items-stretch gap-3 px-5 py-3"
>
- <span className="flex items-start gap-2 text-xs leading-snug text-yellow-500">
- <AlertTriangle size={14} className="mt-0.5 shrink-0" aria-hidden />
- {WEB_EXPORT_GUARDRAIL_MESSAGE}
- </span>
- {h264FallbackAcknowledged ? (
- <span className="text-[11px] text-text-muted">
- Will encode H.264 without transparency.
- </span>
- ) : (
- <div>
- <Button
- label="Export as H.264 anyway"
- variant="secondary"
- onClick={() => setH264FallbackAcknowledged(true)}
+ {webExportAdjustment?.wasAdjusted && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-md border border-status-warning/30 bg-status-warning/10 px-3 py-2 text-[11px] leading-4 text-status-warning"
+ >
+ <AlertTriangle
+ size={14}
+ className="mt-0.5 shrink-0"
+ aria-hidden
/>
+ Browser safety limits will export this video at{" "}
+ {webExportAdjustment.settings.width}×
+ {webExportAdjustment.settings.height} •{" "}
+ {webExportAdjustment.settings.frameRate}fps.
</div>
)}
- </div>
- )}
- <div className="flex items-center justify-between gap-4">
- <div className="flex items-center gap-4 text-xs text-text-muted">
- {duration > 0 && (
- <>
- <div className="flex items-center gap-1">
- <Clock size={12} />
- {formatDuration(duration)}
- </div>
- <div className="flex items-center gap-1">
- <HardDrive size={12} />~
- {activeTab === "reduce" && reducePlan
- ? formatBytes(reduceEstimatedBytes)
- : formatFileSize(
- activeTab === "presets" && selectedPreset
- ? (selectedPreset.settings as VideoExportSettings)
- .bitrate || 8000
- : customSettings.bitrate,
- duration,
- )}
- </div>
- {timeEstimate && deviceProfile?.encoding[customSettings.codec as keyof typeof deviceProfile.encoding]?.hardware && (
- <div className="flex items-center gap-1 text-green-500">
- <Zap size={12} />
- Hardware accelerated
+ {guardrailActive && (
+ <div
+ role="alert"
+ className="flex flex-col gap-2 rounded-md border border-status-warning/30 bg-status-warning/10 px-3 py-2"
+ >
+ <span className="flex items-start gap-2 text-[11px] leading-4 text-status-warning">
+ <AlertTriangle
+ size={14}
+ className="mt-0.5 shrink-0"
+ aria-hidden
+ />
+ {WEB_EXPORT_GUARDRAIL_MESSAGE}
+ </span>
+ {h264FallbackAcknowledged ? (
+ <span className="text-[11px] text-fg-muted">
+ Will encode H.264 without transparency.
+ </span>
+ ) : (
+ <div>
+ <Button
+ label="Export as H.264 anyway"
+ variant="secondary"
+ onClick={() => setH264FallbackAcknowledged(true)}
+ />
</div>
)}
- </>
+ </div>
)}
- </div>
- <div className="flex items-center gap-2">
- <Button label="Cancel" variant="ghost" onClick={onClose} />
- <Button
- label={activeTab === "reduce" ? "Compress & Export" : "Start Export"}
- icon={
- activeTab === "reduce" ? (
- <Minimize2 size={16} aria-hidden />
- ) : (
- <Play size={16} aria-hidden />
- )
- }
- variant="primary"
- onClick={handleExport}
- isDisabled={
- (activeTab === "presets" && !selectedPreset) ||
- (activeTab === "reduce" && !reducePlan) ||
- guardrailBlocking
- }
- />
- </div>
- </div>
- </LayoutFooter>
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex min-w-0 flex-wrap items-center gap-2 text-[11px] text-fg-muted">
+ {duration > 0 && (
+ <>
+ <div className="flex items-center gap-1 rounded-full bg-bg-2 px-2.5 py-1">
+ <Clock size={12} />
+ {formatDuration(duration)}
+ </div>
+ <div className="flex items-center gap-1 rounded-full bg-bg-2 px-2.5 py-1">
+ <HardDrive size={12} />~
+ {activeTab === "reduce" && reducePlan
+ ? formatBytes(reduceEstimatedBytes)
+ : formatFileSize(
+ activeTab === "presets" && selectedPreset
+ ? (selectedPreset.settings as VideoExportSettings)
+ .bitrate || 8000
+ : customSettings.bitrate,
+ duration,
+ )}
+ </div>
+ {timeEstimate &&
+ deviceProfile?.encoding[
+ customSettings.codec as keyof typeof deviceProfile.encoding
+ ]?.hardware && (
+ <div className="flex items-center gap-1 text-green-500">
+ <Zap size={12} />
+ Hardware accelerated
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button label="Cancel" variant="ghost" onClick={onClose} />
+ <Button
+ label={
+ activeTab === "reduce"
+ ? "Compress & Export"
+ : "Export Video"
+ }
+ icon={
+ activeTab === "reduce" ? (
+ <Minimize2 size={16} aria-hidden />
+ ) : (
+ <Play size={16} aria-hidden />
+ )
+ }
+ variant="primary"
+ onClick={handleExport}
+ isDisabled={
+ (activeTab === "presets" && !selectedPreset) ||
+ (activeTab === "reduce" && !reducePlan) ||
+ guardrailBlocking
+ }
+ />
+ </div>
+ </div>
+ </LayoutFooter>
}
/>
</Dialog>
diff --git a/apps/web/src/components/editor/InspectorPanel.tabs.test.tsx b/apps/web/src/components/editor/InspectorPanel.tabs.test.tsx
index cfd9f88f..81245b98 100644
--- a/apps/web/src/components/editor/InspectorPanel.tabs.test.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tabs.test.tsx
@@ -15,8 +15,32 @@ function seedClip(opts: {
trackType: "video" | "audio" | "image";
}): Project {
const project = createEmptyProject("Inspector Sections Test");
+ const mediaType = opts.trackType;
const seeded: Project = {
...project,
+ mediaLibrary: {
+ items: [
+ {
+ id: opts.mediaId,
+ name: opts.mediaId,
+ type: mediaType,
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 10,
+ width: mediaType === "audio" ? 0 : 1920,
+ height: mediaType === "audio" ? 0 : 1080,
+ frameRate: mediaType === "audio" ? 0 : 30,
+ codec: mediaType === "audio" ? "aac" : "h264",
+ sampleRate: mediaType === "image" ? 0 : 48_000,
+ channels: mediaType === "image" ? 0 : 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ ],
+ },
timeline: {
...project.timeline,
duration: 10,
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 47c61b6b..61d86d0d 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -7,13 +7,11 @@ import { useEngineStore } from "../../stores/engine-store";
import type { Transform, EditingTemplatePrimitive } from "@openreel/core";
import {
ChromaKeyEngine,
- initializeTranscriptionService,
- type WhisperTranscriptionProgress,
+ getMediaItemCapabilities,
type CaptionAnimationStyle,
CAPTION_ANIMATION_STYLES,
getAnimationStyleDisplayName,
} from "@openreel/core";
-import { OPENREEL_TRANSCRIBE_URL } from "../../config/api-endpoints";
import { mergeEditingTemplateControlValues } from "./panels/EditingTemplateControls";
import {
getAudioBridgeEffects,
@@ -123,8 +121,6 @@ export const InspectorPanel: React.FC = () => {
getClipTransition,
updateClipTransition,
removeClipTransition,
- getMediaItem,
- addSubtitle,
importSRT,
updateSubtitle,
getSubtitle,
@@ -151,13 +147,6 @@ export const InspectorPanel: React.FC = () => {
const getTitleEngine = useEngineStore((state) => state.getTitleEngine);
const getGraphicsEngine = useEngineStore((state) => state.getGraphicsEngine);
- // Transcription state
- const [transcriptionProgress, setTranscriptionProgress] =
- useState<WhisperTranscriptionProgress | null>(null);
- const [isTranscribing, setIsTranscribing] = useState(false);
- const [targetLanguage, setTargetLanguage] = useState("none");
- const [defaultAnimationStyle, setDefaultAnimationStyle] =
- useState<CaptionAnimationStyle>("word-highlight");
const [expandedRecipeApplicationId, setExpandedRecipeApplicationId] =
useState<string | null>(null);
const [captionWordsPerLine, setCaptionWordsPerLine] = useState(5);
@@ -571,79 +560,6 @@ export const InspectorPanel: React.FC = () => {
updateVideoEffect,
]);
- const handleGenerateSubtitles = useCallback(async () => {
- if (!selectedClip || isTranscribing) return;
-
- const mediaItem = getMediaItem(selectedClip.mediaId);
- if (!mediaItem) {
- console.error("[Subtitles] No media item found for clip");
- return;
- }
-
- setIsTranscribing(true);
- setTranscriptionProgress({
- phase: "extracting",
- progress: 0,
- message: "Preparing audio...",
- });
-
- try {
- const transcriptionService = initializeTranscriptionService({
- apiEndpoint: `${OPENREEL_TRANSCRIBE_URL}/transcribe`,
- targetLanguage: targetLanguage !== "none" ? targetLanguage : undefined,
- });
-
- const regularClip = getClip(selectedClip.id);
- if (!regularClip) {
- throw new Error("Could not find clip data");
- }
-
- const subtitles = await transcriptionService.transcribeClip(
- regularClip,
- mediaItem,
- setTranscriptionProgress,
- );
-
- for (const subtitle of subtitles) {
- addSubtitle({
- ...subtitle,
- animationStyle: defaultAnimationStyle,
- });
- }
-
- setTranscriptionProgress({
- phase: "complete",
- progress: 100,
- message: `Added ${subtitles.length} subtitles`,
- });
-
- setTimeout(() => {
- setTranscriptionProgress(null);
- setIsTranscribing(false);
- }, 2000);
- } catch (error) {
- console.error("[Subtitles] Transcription failed:", error);
- setTranscriptionProgress({
- phase: "error",
- progress: 0,
- message:
- error instanceof Error ? error.message : "Transcription failed",
- });
- setTimeout(() => {
- setTranscriptionProgress(null);
- setIsTranscribing(false);
- }, 3000);
- }
- }, [
- selectedClip,
- isTranscribing,
- getMediaItem,
- getClip,
- addSubtitle,
- defaultAnimationStyle,
- targetLanguage,
- ]);
-
const handleSRTImport = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
@@ -724,9 +640,7 @@ export const InspectorPanel: React.FC = () => {
: "#00ff00";
const tolerance = (chromaKeySettings?.tolerance || 0.3) * 100;
- /**
- * Detect clip type based on track type and clip properties
- */
+ /** Detect clip type from the selected item itself, not its owning track. */
const clipType = useMemo(() => {
if (!selectedClip) return null;
@@ -750,29 +664,20 @@ export const InspectorPanel: React.FC = () => {
return "sticker";
}
- // Find the track this clip belongs to
- const track = project.timeline.tracks.find((t) =>
- t.clips.some((c) => c.id === selectedClip.id),
- );
-
- if (!track) return "video";
-
- // Check for clip types based on track type and media
const mediaItem = project.mediaLibrary.items.find(
(item) => item.id === selectedClip.mediaId,
);
- if (track.type === "audio") {
+ if (mediaItem?.type === "audio") {
return "audio";
}
- if (track.type === "image" || mediaItem?.type === "image") {
+ if (mediaItem?.type === "image") {
return "image";
}
- // Default to video for video tracks
return "video";
- }, [selectedClip, project.timeline.tracks, project.mediaLibrary.items]);
+ }, [selectedClip, project.mediaLibrary.items]);
/**
* Determine which sections to show based on clip type
@@ -785,7 +690,15 @@ export const InspectorPanel: React.FC = () => {
clipType === "svg" ||
clipType === "sticker";
const showColorGrading = clipType === "video" || clipType === "image";
- const showAudioEffects = clipType === "video" || clipType === "audio";
+ const selectedMediaCapabilities = getMediaItemCapabilities(
+ selectedTimelineClip
+ ? project.mediaLibrary.items.find(
+ (item) => item.id === selectedTimelineClip.mediaId,
+ )
+ : undefined,
+ );
+ const showAudioEffects =
+ clipType === "audio" || selectedMediaCapabilities.audio;
const showTextSection = clipType === "text";
const showShapeSection = clipType === "shape";
const showSVGSection = clipType === "svg";
@@ -1017,13 +930,6 @@ export const InspectorPanel: React.FC = () => {
showVideoControls={showVideoControls}
showAudioEffects={showAudioEffects}
showVideoEffects={showVideoEffects}
- transcriptionProgress={transcriptionProgress}
- isTranscribing={isTranscribing}
- targetLanguage={targetLanguage}
- setTargetLanguage={setTargetLanguage}
- defaultAnimationStyle={defaultAnimationStyle}
- setDefaultAnimationStyle={setDefaultAnimationStyle}
- handleGenerateSubtitles={handleGenerateSubtitles}
handleSRTImport={handleSRTImport}
srtInputRef={srtInputRef}
handleRemoveBackground={handleRemoveBackground}
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index d65ff7fb..0111ce7c 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -57,7 +57,12 @@ import {
type Mask,
type AdjustmentLayer,
type BlendMode,
+ type MediaItem,
getTrackTransitionAudioFades,
+ resolveCanvasFitDimensions,
+ getMediaItemCapabilities,
+ getVisibleTrackRenderOrder,
+ trackHasAudioItems,
} from "@openreel/core";
import { useEngineStore } from "../../stores/engine-store";
import {
@@ -91,7 +96,9 @@ import {
PREVIEW_QUALITY_OPTIONS,
} from "./preview/index";
import { snapCanvasPosition } from "./preview/canvas-snapping";
+import { captureNativeVideoFrame } from "./preview/video-frame";
import { ProcessingOverlay } from "./ProcessingOverlay";
+import { editingFrameDurationMs } from "./editing-frame-rate";
import {
getPersonSegmentationEngine,
getBackgroundRemovalEngine,
@@ -316,38 +323,21 @@ const computeFitScale = (
sourceHeight: number,
canvasWidth: number,
canvasHeight: number,
+ crop?: ClipTransform["crop"],
): { x: number; y: number } => {
- const mode = !fitMode || fitMode === "none" ? "contain" : fitMode;
- if (
- mode === "stretch" ||
- sourceWidth <= 0 ||
- sourceHeight <= 0 ||
- canvasWidth <= 0 ||
- canvasHeight <= 0
- ) {
+ if (canvasWidth <= 0 || canvasHeight <= 0) {
return { x: 1, y: 1 };
}
- const sourceAspect = sourceWidth / sourceHeight;
- const canvasAspect = canvasWidth / canvasHeight;
- let drawWidth: number;
- let drawHeight: number;
- if (mode === "cover") {
- if (sourceAspect > canvasAspect) {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- } else {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- }
- } else {
- if (sourceAspect > canvasAspect) {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- } else {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- }
- }
+ const visibleSourceWidth = crop ? crop.width * sourceWidth : sourceWidth;
+ const visibleSourceHeight = crop ? crop.height * sourceHeight : sourceHeight;
+ const { width: drawWidth, height: drawHeight } =
+ resolveCanvasFitDimensions(
+ fitMode,
+ visibleSourceWidth,
+ visibleSourceHeight,
+ canvasWidth,
+ canvasHeight,
+ );
return { x: drawWidth / canvasWidth, y: drawHeight / canvasHeight };
};
@@ -434,6 +424,7 @@ const renderFrameWithGPU = async (
frame.height,
canvasWidth,
canvasHeight,
+ transform.crop,
);
const gpuTransform = {
position: transform.position,
@@ -445,6 +436,7 @@ const renderFrameWithGPU = async (
anchor: transform.anchor,
opacity: transform.opacity,
borderRadius: transform.borderRadius,
+ crop: transform.crop,
};
renderer.renderLayer({
@@ -493,6 +485,7 @@ const renderAllLayersWithGPU = async (
layer.bitmap.height,
canvasWidth,
canvasHeight,
+ layer.transform.crop,
);
const gpuTransform = {
position: layer.transform.position,
@@ -504,6 +497,7 @@ const renderAllLayersWithGPU = async (
anchor: layer.transform.anchor,
opacity: layer.transform.opacity,
borderRadius: layer.transform.borderRadius,
+ crop: layer.transform.crop,
};
renderer.renderLayer({
@@ -534,17 +528,17 @@ const hasBehindSubjectText = (textClips: TextClip[]): boolean =>
const getBehindSubjectStreamId = (
tracks: readonly Track[],
time: number,
+ getMediaItem: (mediaId: string) => MediaItem | undefined,
): string => {
const activeSourceIds = tracks
- .filter(
- (track) =>
- (track.type === "video" || track.type === "image") && !track.hidden,
- )
+ .filter((track) => !track.hidden)
.flatMap((track) =>
track.clips
.filter(
(clip) =>
- time >= clip.startTime && time < clip.startTime + clip.duration,
+ time >= clip.startTime &&
+ time < clip.startTime + clip.duration &&
+ getMediaItemCapabilities(getMediaItem(clip.mediaId)).visual,
)
.map((clip) => clip.id),
)
@@ -1043,12 +1037,10 @@ export const Preview: React.FC = () => {
// Throttle store updates during interaction (update at most every 32ms ~30fps)
const lastStoreUpdateRef = useRef<number>(0);
const STORE_UPDATE_THROTTLE_MS = 32;
- // Throttle playhead updates during playback to reduce React re-renders
+ // Throttle playhead updates during playback to reduce React re-renders.
+ // The interval follows the project timebase so 60 fps projects publish a
+ // 60 Hz playhead instead of being capped at 30 Hz.
const lastPlayheadUpdateRef = useRef<number>(0);
- // Keep React/timeline updates from competing with continuous media playback.
- // The video canvas still renders on every animation frame; only the heavier
- // editor-wide playhead state update is capped to roughly 30fps.
- const PLAYHEAD_UPDATE_THROTTLE_MS = 33;
// Live transform state for immediate visual feedback during interaction
const [liveTransform, setLiveTransform] = useState<{
position: { x: number; y: number };
@@ -1186,22 +1178,55 @@ export const Preview: React.FC = () => {
// when any part of the project changes (including clips)
const project = useProjectStore((state) => state.project);
const getMediaItem = useProjectStore((state) => state.getMediaItem);
+ const mediaClipHasVisual = useCallback(
+ (clip: PreviewClip) =>
+ getMediaItemCapabilities(getMediaItem(clip.mediaId)).visual,
+ [getMediaItem],
+ );
+ const mediaClipHasAudio = useCallback(
+ (clip: PreviewClip) =>
+ getMediaItemCapabilities(getMediaItem(clip.mediaId)).audio,
+ [getMediaItem],
+ );
+
+ useEffect(() => {
+ const cachedFrame = lastGoodFrameRef.current;
+ lastGoodFrameRef.current = null;
+ cachedFrame?.close();
+ }, [project]);
// Get text clips from TitleEngine
const getTitleEngine = useEngineStore((state) => state.getTitleEngine);
const allTextClips = useMemo(() => {
+ if (project.textClips) return project.textClips;
const titleEngine = getTitleEngine();
return titleEngine?.getAllTextClips() || [];
- }, [getTitleEngine, project.modifiedAt]);
+ }, [getTitleEngine, project.textClips]);
const getGraphicsEngine = useEngineStore((state) => state.getGraphicsEngine);
const allShapeClips = useMemo(() => {
+ if (
+ project.shapeClips ||
+ project.svgClips ||
+ project.stickerClips
+ ) {
+ return [
+ ...(project.shapeClips ?? []),
+ ...(project.svgClips ?? []),
+ ...(project.stickerClips ?? []),
+ ];
+ }
const graphicsEngine = getGraphicsEngine();
const shapes = graphicsEngine?.getAllShapeClips() || [];
const svgs = graphicsEngine?.getAllSVGClips() || [];
const stickers = graphicsEngine?.getAllStickerClips() || [];
return [...shapes, ...svgs, ...stickers];
- }, [getGraphicsEngine, project.modifiedAt]);
+ }, [
+ getGraphicsEngine,
+ project.shapeClips,
+ project.stickerClips,
+ project.svgClips,
+ ]);
const getMaskEngine = useEngineStore((state) => state.getMaskEngine);
const clipMasksById = useMemo(() => {
@@ -1284,6 +1309,7 @@ export const Preview: React.FC = () => {
const updateSettings = useProjectStore((state) => state.updateSettings);
const timelineTracks = project.timeline.tracks;
const settings = project.settings;
+ const editingFrameDuration = editingFrameDurationMs(settings.frameRate);
const canvasFillMode = project.timeline.backgroundFillMode;
const canvasFillColor = project.timeline.layoutBackgroundColor;
@@ -1877,12 +1903,22 @@ export const Preview: React.FC = () => {
mode: "below-video" | "above-video" | "all" = "all",
subjectFrame: ImageBitmap | null = null,
) => {
- const subjectStreamId = getBehindSubjectStreamId(tracks, time);
+ const subjectStreamId = getBehindSubjectStreamId(
+ tracks,
+ time,
+ getMediaItem,
+ );
const videoImageTrackIndices = tracks
.map((t, idx) => ({ track: t, originalIndex: idx }))
.filter(
({ track }) =>
- (track.type === "video" || track.type === "image") && !track.hidden,
+ !track.hidden &&
+ track.clips.some(
+ (clip) =>
+ time >= clip.startTime &&
+ time < clip.startTime + clip.duration &&
+ mediaClipHasVisual(clip),
+ ),
)
.map(({ originalIndex }) => originalIndex);
@@ -1895,13 +1931,7 @@ export const Preview: React.FC = () => {
? Math.max(...videoImageTrackIndices)
: -1;
- const overlayTracksWithIndex = tracks
- .map((t, idx) => ({ track: t, originalIndex: idx }))
- .filter(
- ({ track }) =>
- (track.type === "text" || track.type === "graphics") &&
- !track.hidden,
- );
+ const overlayTracksWithIndex = getVisibleTrackRenderOrder(tracks);
const tracksToRender = overlayTracksWithIndex.filter(
({ originalIndex }) => {
@@ -1914,49 +1944,44 @@ export const Preview: React.FC = () => {
},
);
- tracksToRender.sort((a, b) => b.originalIndex - a.originalIndex);
-
for (const { track } of tracksToRender) {
- if (track.type === "graphics") {
- const trackShapeClips = shapeClips.filter(
- (sc) => sc.trackId === track.id,
- );
- for (const shapeClip of trackShapeClips) {
- await renderShapeClipWithEffects(
- ctx,
- shapeClip,
- canvasWidth,
- canvasHeight,
- time,
- );
- }
- await renderMotionInstancesForTrack(
+ const trackShapeClips = shapeClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const shapeClip of trackShapeClips) {
+ await renderShapeClipWithEffects(
ctx,
- track,
- time,
+ shapeClip,
canvasWidth,
canvasHeight,
+ time,
);
- } else if (track.type === "text") {
- const trackTextClips = textClips.filter(
- (tc) => tc.trackId === track.id,
+ }
+ await renderMotionInstancesForTrack(
+ ctx,
+ track,
+ time,
+ canvasWidth,
+ canvasHeight,
+ );
+ const trackTextClips = textClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const textClip of trackTextClips) {
+ await renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ canvasWidth,
+ canvasHeight,
+ time,
+ subjectFrame,
+ isPlaying,
+ subjectStreamId,
);
- for (const textClip of trackTextClips) {
- await renderTextClipWithSubjectMask(
- ctx,
- textClip,
- canvasWidth,
- canvasHeight,
- time,
- subjectFrame,
- isPlaying,
- subjectStreamId,
- );
- }
}
}
},
- [isPlaying, renderMotionInstancesForTrack],
+ [getMediaItem, isPlaying, mediaClipHasVisual, renderMotionInstancesForTrack],
);
/**
@@ -1972,7 +1997,9 @@ export const Preview: React.FC = () => {
const setupAudioFromAudioTrack = useCallback(
async (timelinePosition: number): Promise<void> => {
const tracks = timelineTracksRef.current;
- const audioTracks = tracks.filter((t) => t.type === "audio" && !t.hidden);
+ const audioTracks = tracks.filter(
+ (track) => !track.hidden && trackHasAudioItems(project, track.id),
+ );
if (!audioGraphRef.current) {
audioGraphRef.current = getRealtimeAudioGraph();
@@ -1998,6 +2025,9 @@ export const Preview: React.FC = () => {
}
for (const audioClip of audioTrack.clips) {
+ if (!mediaClipHasAudio(audioClip)) {
+ continue;
+ }
const clipEnd = audioClip.startTime + audioClip.duration;
if (
@@ -2102,15 +2132,14 @@ export const Preview: React.FC = () => {
getResolvedClipAudioEffects,
getResolvedClipVolumeAutomation,
isMuted,
+ mediaClipHasAudio,
+ project,
],
);
const preDecodeAllAudioBuffers = useCallback(async (): Promise<void> => {
const tracks = timelineTracksRef.current;
- const audioTracks = tracks.filter((t) => t.type === "audio" && !t.hidden);
- const videoTracks = tracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
- );
+ const audioTracks = tracks.filter((track) => !track.hidden);
if (!audioGraphRef.current) {
audioGraphRef.current = getRealtimeAudioGraph();
@@ -2118,10 +2147,11 @@ export const Preview: React.FC = () => {
const audioGraph = audioGraphRef.current;
const audioContext = audioGraph.getAudioContext();
- const allTracks = [...audioTracks, ...videoTracks];
-
- for (const track of allTracks) {
+ for (const track of audioTracks) {
for (const clip of track.clips) {
+ if (!mediaClipHasAudio(clip)) {
+ continue;
+ }
const cacheKey = getAudioBufferCacheKey(clip.mediaId, clip.audioTrackIndex);
let audioBuffer: AudioBuffer | null | undefined =
audioBufferCacheRef.current.get(cacheKey);
@@ -2169,7 +2199,12 @@ export const Preview: React.FC = () => {
}
}
}
- }, [getMediaItem, getPreviewAudioBufferForEffects, getResolvedClipAudioEffects]);
+ }, [
+ getMediaItem,
+ getPreviewAudioBufferForEffects,
+ getResolvedClipAudioEffects,
+ mediaClipHasAudio,
+ ]);
// Pre-warm audio decode caches when the timeline settles after an edit (e.g.
// moving/adding a clip), so the realtime scheduler finds decoded buffers ready
@@ -2226,12 +2261,15 @@ export const Preview: React.FC = () => {
(time: number): AudioClipSchedule[] => {
const tracks = timelineTracksRef.current;
const tracksWithAudio = tracks.filter(
- (t) => (t.type === "audio" || t.type === "video") && !t.hidden && !t.muted,
+ (track) => !track.hidden && !track.muted,
);
const schedules: AudioClipSchedule[] = [];
for (const track of tracksWithAudio) {
for (const clip of track.clips) {
+ if (!mediaClipHasAudio(clip)) {
+ continue;
+ }
const clipEnd = clip.startTime + clip.duration;
if (clipEnd <= time || clip.startTime > time + 1) {
continue;
@@ -2298,6 +2336,7 @@ export const Preview: React.FC = () => {
getAudioEffectSignature,
getResolvedClipAudioEffects,
getResolvedClipVolumeAutomation,
+ mediaClipHasAudio,
],
);
@@ -2314,8 +2353,6 @@ export const Preview: React.FC = () => {
inPoint?: number;
},
time: number,
- canvasWidth: number,
- canvasHeight: number,
): Promise<ImageBitmap | null> => {
const mediaItem = getMediaItem(clip.mediaId);
if (!mediaItem?.blob) return null;
@@ -2498,50 +2535,7 @@ export const Preview: React.FC = () => {
return;
}
- const tempCanvas = document.createElement("canvas");
- tempCanvas.width = canvasWidth;
- tempCanvas.height = canvasHeight;
- const tempCtx = tempCanvas.getContext("2d");
- if (!tempCtx) {
- resolve(null);
- return;
- }
-
- const videoAspect = video.videoWidth / video.videoHeight;
- const canvasAspect = canvasWidth / canvasHeight;
- let drawWidth = canvasWidth;
- let drawHeight = canvasHeight;
- let offsetX = 0;
- let offsetY = 0;
-
- if (videoAspect > canvasAspect) {
- drawHeight = canvasWidth / videoAspect;
- offsetY = (canvasHeight - drawHeight) / 2;
- } else {
- drawWidth = canvasHeight * videoAspect;
- offsetX = (canvasWidth - drawWidth) / 2;
- }
-
- if (
- canvasFillModeRef.current === "blur" &&
- video.videoWidth > 0 &&
- video.videoHeight > 0
- ) {
- drawBlurredBackdrop(
- tempCtx,
- video,
- video.videoWidth,
- video.videoHeight,
- canvasWidth,
- canvasHeight,
- );
- } else {
- tempCtx.fillStyle = previewBgRef.current;
- tempCtx.fillRect(0, 0, canvasWidth, canvasHeight);
- }
- tempCtx.drawImage(video, offsetX, offsetY, drawWidth, drawHeight);
-
- const frame = await createImageBitmap(tempCanvas);
+ const frame = await captureNativeVideoFrame(video);
if (isStaleRequest()) {
frame.close();
resolve(null);
@@ -2645,22 +2639,13 @@ export const Preview: React.FC = () => {
if (!ctx) return false;
const videoTracks = timelineTracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
+ (track) =>
+ !track.hidden && track.clips.some((clip) => mediaClipHasVisual(clip)),
);
let hasRenderedFrame = false;
let shouldClearCanvas = true;
- const hadBackground = Boolean(lastGoodFrameRef.current);
- if (lastGoodFrameRef.current) {
- ctx.drawImage(
- lastGoodFrameRef.current,
- 0,
- 0,
- canvas.width,
- canvas.height,
- );
- shouldClearCanvas = false;
- }
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
const activeShapeClips = getActiveShapeClips(allShapeClips, time);
const activeTextClips = getActiveTextClips(allTextClips, time);
@@ -2680,23 +2665,17 @@ export const Preview: React.FC = () => {
shouldClearCanvas = false;
}
- const transitionInfo = getTransitionAtTime(time, timelineTracks);
+ const transitionInfo = getTransitionAtTime(
+ time,
+ timelineTracks,
+ mediaClipHasVisual,
+ );
if (transitionInfo) {
try {
- const clipAFrame = await decodeClipFrame(
- transitionInfo.clipA,
- time,
- canvas.width,
- canvas.height,
- );
+ const clipAFrame = await decodeClipFrame(transitionInfo.clipA, time);
const clipBFrame = transitionInfo.clipB
- ? await decodeClipFrame(
- transitionInfo.clipB,
- time,
- canvas.width,
- canvas.height,
- )
+ ? await decodeClipFrame(transitionInfo.clipB, time)
: null;
const blankFrame = transitionInfo.clipB
? null
@@ -2766,7 +2745,13 @@ export const Preview: React.FC = () => {
canvas.height,
"below-video",
);
- ctx.drawImage(blendedFrame, 0, 0);
+ drawFrameWithTransform(
+ ctx,
+ blendedFrame,
+ DEFAULT_TRANSFORM,
+ canvas.width,
+ canvas.height,
+ );
await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
@@ -2828,7 +2813,13 @@ export const Preview: React.FC = () => {
canvas.height,
"below-video",
);
- ctx.drawImage(validFrame, 0, 0);
+ drawFrameWithTransform(
+ ctx,
+ validFrame,
+ DEFAULT_TRANSFORM,
+ canvas.width,
+ canvas.height,
+ );
await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
@@ -2868,7 +2859,13 @@ export const Preview: React.FC = () => {
canvas.height,
"below-video",
);
- ctx.drawImage(validFrame, 0, 0);
+ drawFrameWithTransform(
+ ctx,
+ validFrame,
+ DEFAULT_TRANSFORM,
+ canvas.width,
+ canvas.height,
+ );
await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
@@ -2896,7 +2893,9 @@ export const Preview: React.FC = () => {
const hasVideoContent = videoTracks.some((track) =>
track.clips.some(
(clip) =>
- time >= clip.startTime && time < clip.startTime + clip.duration,
+ mediaClipHasVisual(clip) &&
+ time >= clip.startTime &&
+ time < clip.startTime + clip.duration,
),
);
const hasMotionContent = hasActiveMotionInstances(time);
@@ -2919,46 +2918,29 @@ export const Preview: React.FC = () => {
// Render ALL tracks in layer order using painter's algorithm
// Higher index = rendered first (appears behind), Lower index = rendered last (appears on top)
- const allRenderableTracks = timelineTracks
- .map((track, idx) => ({ track, originalIndex: idx }))
- .filter(
- ({ track }) =>
- (track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics") &&
- !track.hidden,
- )
- .sort((a, b) => b.originalIndex - a.originalIndex);
+ const allRenderableTracks = getVisibleTrackRenderOrder(timelineTracks);
let subjectFrame: ImageBitmap | null = null;
const shouldCompositeSubject = hasBehindSubjectText(activeTextClips);
let blurBackdropDrawn = false;
for (const { track } of allRenderableTracks) {
- if (track.type === "video" || track.type === "image") {
+ {
for (const clip of track.clips) {
+ if (!mediaClipHasVisual(clip)) continue;
const clipStart = clip.startTime;
const clipEnd = clip.startTime + clip.duration;
if (time >= clipStart && time < clipEnd) {
- const frame = await decodeClipFrame(
- clip,
- time,
- canvas.width,
- canvas.height,
- );
+ const frame = await decodeClipFrame(clip, time);
if (frame) {
- // Blur canvas fill for images: decodeClipFrame returns a raw
- // (un-letterboxed) bitmap for images, so paint it cover-fit +
- // blurred behind everything before the contained clip is drawn
- // on top. Video frames are canvas-sized and already carry the
- // blurred backdrop baked in by decodeClipFrame.
+ // The decoder returns native, un-letterboxed frames for both
+ // images and videos. Paint the first visible layer cover-fit
+ // behind the composition when the project uses blur fill.
if (
canvasFillModeRef.current === "blur" &&
- !blurBackdropDrawn &&
- getMediaItem(clip.mediaId)?.type === "image"
+ !blurBackdropDrawn
) {
drawBlurredBackdrop(
ctx,
@@ -3104,49 +3086,47 @@ export const Preview: React.FC = () => {
}
}
}
- } else if (track.type === "graphics") {
- const trackShapeClips = activeShapeClips.filter(
- (sc) => sc.trackId === track.id,
+ }
+ const trackShapeClips = activeShapeClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const shapeClip of trackShapeClips) {
+ await renderShapeClipWithEffects(
+ ctx,
+ shapeClip,
+ canvas.width,
+ canvas.height,
+ time,
);
- for (const shapeClip of trackShapeClips) {
- await renderShapeClipWithEffects(
- ctx,
- shapeClip,
- canvas.width,
- canvas.height,
- time,
- );
- hasRenderedFrame = true;
- }
- if (
- await renderMotionInstancesForTrack(
- ctx,
- track,
- time,
- canvas.width,
- canvas.height,
- )
- ) {
- hasRenderedFrame = true;
- }
- } else if (track.type === "text") {
- const trackTextClips = activeTextClips.filter(
- (tc) => tc.trackId === track.id,
+ hasRenderedFrame = true;
+ }
+ if (
+ await renderMotionInstancesForTrack(
+ ctx,
+ track,
+ time,
+ canvas.width,
+ canvas.height,
+ )
+ ) {
+ hasRenderedFrame = true;
+ }
+ const trackTextClips = activeTextClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const textClip of trackTextClips) {
+ await renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ canvas.width,
+ canvas.height,
+ time,
+ subjectFrame,
+ isPlaying,
+ getBehindSubjectStreamId(timelineTracks, time, getMediaItem),
);
- for (const textClip of trackTextClips) {
- await renderTextClipWithSubjectMask(
- ctx,
- textClip,
- canvas.width,
- canvas.height,
- time,
- subjectFrame,
- isPlaying,
- getBehindSubjectStreamId(timelineTracks, time),
- );
- hasRenderedFrame = true;
- }
+ hasRenderedFrame = true;
}
}
subjectFrame?.close();
@@ -3187,23 +3167,6 @@ export const Preview: React.FC = () => {
return true;
}
- const hasActiveContent =
- videoTracks.some((track) =>
- track.clips.some(
- (clip) =>
- time >= clip.startTime && time < clip.startTime + clip.duration,
- ),
- ) ||
- hasActiveMotionInstances(time) ||
- activeShapeClips.length > 0 ||
- activeTextClips.length > 0;
-
- if (hadBackground && hasActiveContent && offscreenCanvasRef.current) {
- mainCtx.clearRect(0, 0, canvas.width, canvas.height);
- mainCtx.drawImage(offscreenCanvasRef.current, 0, 0);
- return true;
- }
-
return hasRenderedFrame;
},
[
@@ -3225,6 +3188,7 @@ export const Preview: React.FC = () => {
isDark,
isPlaying,
project.adjustmentLayers,
+ mediaClipHasVisual,
],
);
@@ -3274,13 +3238,16 @@ export const Preview: React.FC = () => {
const activeTextClips = getActiveTextClips(allTextClips, time);
const videoTracks = timelineTracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
+ (track) =>
+ !track.hidden && track.clips.some((clip) => mediaClipHasVisual(clip)),
);
const hasVideoContent = videoTracks.some((track) =>
track.clips.some(
(clip) =>
- time >= clip.startTime && time < clip.startTime + clip.duration,
+ mediaClipHasVisual(clip) &&
+ time >= clip.startTime &&
+ time < clip.startTime + clip.duration,
),
);
@@ -3293,21 +3260,12 @@ export const Preview: React.FC = () => {
let hasRenderedContent = false;
- const allRenderableTracks = timelineTracks
- .map((track, idx) => ({ track, originalIndex: idx }))
- .filter(
- ({ track }) =>
- (track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics") &&
- !track.hidden,
- )
- .sort((a, b) => b.originalIndex - a.originalIndex);
+ const allRenderableTracks = getVisibleTrackRenderOrder(timelineTracks);
for (const { track } of allRenderableTracks) {
- if (track.type === "video" || track.type === "image") {
+ {
for (const clip of track.clips) {
+ if (!mediaClipHasVisual(clip)) continue;
const clipStart = clip.startTime;
const clipEnd = clip.startTime + clip.duration;
@@ -3350,37 +3308,35 @@ export const Preview: React.FC = () => {
}
}
}
- } else if (track.type === "graphics") {
- const trackShapeClips = activeShapeClips.filter(
- (sc) => sc.trackId === track.id,
+ }
+ const trackShapeClips = activeShapeClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const shapeClip of trackShapeClips) {
+ await renderShapeClipWithEffects(
+ ctx,
+ shapeClip,
+ canvas.width,
+ canvas.height,
+ time,
);
- for (const shapeClip of trackShapeClips) {
- await renderShapeClipWithEffects(
- ctx,
- shapeClip,
- canvas.width,
- canvas.height,
- time,
- );
- hasRenderedContent = true;
- }
- } else if (track.type === "text") {
- const trackTextClips = activeTextClips.filter(
- (tc) => tc.trackId === track.id,
+ hasRenderedContent = true;
+ }
+ const trackTextClips = activeTextClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const textClip of trackTextClips) {
+ await renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ canvas.width,
+ canvas.height,
+ time,
+ null,
+ isPlaying,
+ getBehindSubjectStreamId(timelineTracks, time, getMediaItem),
);
- for (const textClip of trackTextClips) {
- await renderTextClipWithSubjectMask(
- ctx,
- textClip,
- canvas.width,
- canvas.height,
- time,
- null,
- isPlaying,
- getBehindSubjectStreamId(timelineTracks, time),
- );
- hasRenderedContent = true;
- }
+ hasRenderedContent = true;
}
}
@@ -3395,12 +3351,11 @@ export const Preview: React.FC = () => {
);
}
- const audioTracks = timelineTracks.filter(
- (t) => t.type === "audio" && !t.hidden,
- );
+ const audioTracks = timelineTracks.filter((track) => !track.hidden);
const hasActiveAudioClip = audioTracks.some((track) =>
track.clips.some(
(clip) =>
+ mediaClipHasAudio(clip) &&
time >= clip.startTime && time < clip.startTime + clip.duration,
),
);
@@ -3433,6 +3388,8 @@ export const Preview: React.FC = () => {
hasActiveMotionInstances,
isDark,
isPlaying,
+ mediaClipHasAudio,
+ mediaClipHasVisual,
],
);
@@ -3465,7 +3422,7 @@ export const Preview: React.FC = () => {
) {
return { canUse: false, clips: [] };
}
- const videoTracks = tracks.filter((t) => t.type === "video" && !t.hidden);
+ const videoTracks = tracks.filter((track) => !track.hidden);
const allVideoClips: Array<{
clip: (typeof tracks)[0]["clips"][0];
@@ -3499,12 +3456,12 @@ export const Preview: React.FC = () => {
const hasActiveAudioEffects = tracks.some(
(track) =>
- (track.type === "audio" || track.type === "video") &&
!track.hidden &&
track.clips.some((clip) => {
if (clip.startTime + clip.duration <= startPosition) {
return false;
}
+ if (!mediaClipHasAudio(clip)) return false;
return getPreviewAudioEffects(
getResolvedClipAudioEffects(clip),
@@ -3536,7 +3493,7 @@ export const Preview: React.FC = () => {
// They are rendered using CPU canvas2D after the video frame
// Collect image clips for background compositing (don't disable native playback)
- const imageTracks = tracks.filter((t) => t.type === "image" && !t.hidden);
+ const imageTracks = tracks.filter((track) => !track.hidden);
const imageClips: Array<{
clip: (typeof tracks)[0]["clips"][0];
trackIndex: number;
@@ -3544,7 +3501,9 @@ export const Preview: React.FC = () => {
imageTracks.forEach((track) => {
const trackIndex = tracks.indexOf(track);
for (const clip of track.clips) {
- imageClips.push({ clip, trackIndex });
+ if (getMediaItem(clip.mediaId)?.type === "image") {
+ imageClips.push({ clip, trackIndex });
+ }
}
});
@@ -3561,6 +3520,7 @@ export const Preview: React.FC = () => {
allShapeClips,
getResolvedClipAudioEffects,
clipMasksById,
+ mediaClipHasAudio,
],
);
@@ -3708,7 +3668,7 @@ export const Preview: React.FC = () => {
audioGraph.setPreviewMuted(isMuted);
const tracksWithAudio = timelineTracks.filter(
- (t) => (t.type === "audio" || t.type === "video") && !t.hidden,
+ (track) => !track.hidden && trackHasAudioItems(project, track.id),
);
for (const audioTrack of tracksWithAudio) {
audioGraph.createTrack({
@@ -3858,7 +3818,7 @@ export const Preview: React.FC = () => {
// is scheduled from this same clock, so delaying this update until the
// end of a heavy render makes sound appear to start ahead of the playhead.
const nowPlayhead = performance.now();
- if (nowPlayhead - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
+ if (nowPlayhead - lastPlayheadUpdateRef.current >= editingFrameDuration) {
lastPlayheadUpdateRef.current = nowPlayhead;
setPlayheadPosition(currentPlayhead);
}
@@ -3866,6 +3826,7 @@ export const Preview: React.FC = () => {
const transitionInfo = getTransitionAtTime(
currentPlayhead,
timelineTracksRef.current,
+ mediaClipHasVisual,
);
if (transitionInfo) {
const clipARecord = findNativeClipById(transitionInfo.clipA.id);
@@ -4014,7 +3975,7 @@ export const Preview: React.FC = () => {
const nowTransition = performance.now();
if (
nowTransition - lastPlayheadUpdateRef.current >=
- PLAYHEAD_UPDATE_THROTTLE_MS
+ editingFrameDuration
) {
lastPlayheadUpdateRef.current = nowTransition;
setPlayheadPosition(currentPlayhead);
@@ -4116,7 +4077,7 @@ export const Preview: React.FC = () => {
}
const nowNoClip = performance.now();
- if (nowNoClip - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
+ if (nowNoClip - lastPlayheadUpdateRef.current >= editingFrameDuration) {
lastPlayheadUpdateRef.current = nowNoClip;
setPlayheadPosition(currentPlayhead);
}
@@ -4134,7 +4095,7 @@ export const Preview: React.FC = () => {
await loadVideoForClip(clip, mediaItem);
if (!isActive || !nativePlaybackActiveRef.current) return;
const nowNoCached = performance.now();
- if (nowNoCached - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
+ if (nowNoCached - lastPlayheadUpdateRef.current >= editingFrameDuration) {
lastPlayheadUpdateRef.current = nowNoCached;
setPlayheadPosition(currentPlayhead);
}
@@ -4441,6 +4402,7 @@ export const Preview: React.FC = () => {
},
[
actualEndTime,
+ editingFrameDuration,
allSubtitles,
getMediaItem,
getAudioClipsForScheduler,
@@ -4452,6 +4414,9 @@ export const Preview: React.FC = () => {
fillPreviewBackground,
setPlayheadPosition,
timelineTracks,
+ project,
+ mediaClipHasVisual,
+ previewRes.scale,
],
);
@@ -4498,12 +4463,10 @@ export const Preview: React.FC = () => {
}> = [];
tracks.forEach((track, originalIndex) => {
- if (
- (track.type === "video" || track.type === "image") &&
- !track.hidden
- ) {
+ if (!track.hidden) {
for (const clip of track.clips) {
if (
+ mediaClipHasVisual(clip) &&
time >= clip.startTime &&
time < clip.startTime + clip.duration
) {
@@ -4587,11 +4550,12 @@ export const Preview: React.FC = () => {
// If video clip has default speed, check for linked audio clip's speed
if (currentSpeed === 1 && !isReverse) {
const tracks = timelineTracksRef.current;
- const audioTracks = tracks.filter((t) => t.type === "audio");
+ const audioTracks = tracks;
for (const audioTrack of audioTracks) {
for (const audioClip of audioTrack.clips) {
if (
+ mediaClipHasAudio(audioClip) &&
audioClip.mediaId === clip.mediaId &&
Math.abs(audioClip.startTime - clip.startTime) < 0.01
) {
@@ -4630,7 +4594,7 @@ export const Preview: React.FC = () => {
return;
}
- const frameDuration = 1000 / 30;
+ const frameDuration = editingFrameDuration;
let currentMediaTime = mediaStartTime;
let currentPlayheadTime = timelinePosition;
@@ -4838,7 +4802,7 @@ export const Preview: React.FC = () => {
preparedFrame.cleanup();
const nowPh = performance.now();
- if (nowPh - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
+ if (nowPh - lastPlayheadUpdateRef.current >= editingFrameDuration) {
lastPlayheadUpdateRef.current = nowPh;
setPlayheadPosition(currentPlayhead);
}
@@ -4948,9 +4912,7 @@ export const Preview: React.FC = () => {
const preCacheAllImageBitmaps = async () => {
const tracks = timelineTracksRef.current;
- const visualTracks = tracks.filter(
- (t) => (t.type === "image" || t.type === "video") && !t.hidden,
- );
+ const visualTracks = tracks.filter((track) => !track.hidden);
for (const track of visualTracks) {
for (const clip of track.clips) {
@@ -4984,11 +4946,12 @@ export const Preview: React.FC = () => {
);
const audioTracks = timelineTracksRef.current.filter(
- (t) => t.type === "audio" && !t.hidden,
+ (track) => !track.hidden,
);
const hasActiveAudioClip = audioTracks.some((track) =>
track.clips.some(
(clip) =>
+ mediaClipHasAudio(clip) &&
playbackStartPosition >= clip.startTime &&
playbackStartPosition < clip.startTime + clip.duration,
),
@@ -5044,7 +5007,7 @@ export const Preview: React.FC = () => {
audioGraph.setPreviewMuted(isMuted);
const tracksWithAudio = timelineTracksRef.current.filter(
- (t) => (t.type === "audio" || t.type === "video") && !t.hidden,
+ (track) => !track.hidden && trackHasAudioItems(project, track.id),
);
for (const track of tracksWithAudio) {
audioGraph.createTrack({
@@ -5095,7 +5058,7 @@ export const Preview: React.FC = () => {
await masterClock.play();
audioGraph.startScheduler(getAudioClipsForScheduler);
- const frameDuration = 1000 / 30;
+ const frameDuration = editingFrameDuration;
let lastFrameTimestamp = performance.now();
let frameCount = 0;
let isProcessingFrame = false;
@@ -5139,7 +5102,7 @@ export const Preview: React.FC = () => {
// Keep the timeline UI clock-aligned with audio even when decoding or
// effects make the current visual frame expensive to produce.
const nowPlayhead = performance.now();
- if (nowPlayhead - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
+ if (nowPlayhead - lastPlayheadUpdateRef.current >= editingFrameDuration) {
lastPlayheadUpdateRef.current = nowPlayhead;
setPlayheadPosition(currentPlayhead);
}
@@ -5155,11 +5118,12 @@ export const Preview: React.FC = () => {
);
const audioTracksForFrame = timelineTracksRef.current.filter(
- (t) => t.type === "audio" && !t.hidden,
+ (track) => !track.hidden,
);
const hasCurrentAudioClip = audioTracksForFrame.some((track) =>
track.clips.some(
(clip) =>
+ mediaClipHasAudio(clip) &&
currentPlayhead >= clip.startTime &&
currentPlayhead < clip.startTime + clip.duration,
),
@@ -5252,6 +5216,7 @@ export const Preview: React.FC = () => {
const transitionInfoMulti = getTransitionAtTime(
currentPlayhead,
timelineTracksRef.current,
+ mediaClipHasVisual,
);
// Compute these here so they're visible in both the transition path
@@ -5399,6 +5364,7 @@ export const Preview: React.FC = () => {
getBehindSubjectStreamId(
timelineTracksRef.current,
currentPlayhead,
+ getMediaItem,
),
);
}
@@ -5426,7 +5392,7 @@ export const Preview: React.FC = () => {
const nowTr = performance.now();
if (
nowTr - lastPlayheadUpdateRef.current >=
- PLAYHEAD_UPDATE_THROTTLE_MS
+ editingFrameDuration
) {
lastPlayheadUpdateRef.current = nowTr;
setPlayheadPosition(currentPlayhead);
@@ -5492,7 +5458,7 @@ export const Preview: React.FC = () => {
} | null>
> = [];
- for (const { clip, track } of sortedClips) {
+ for (const { clip } of sortedClips) {
if (!isActive) continue;
const clipLocalTime = currentPlayhead - clip.startTime;
@@ -5539,7 +5505,7 @@ export const Preview: React.FC = () => {
}
const clipMedia = getMediaItem(clip.mediaId);
- if (track.type === "image" || clipMedia?.type === "image") {
+ if (clipMedia?.type === "image") {
let cachedBitmap = imageBitmapCacheRef.current.get(clip.id);
if (
!cachedBitmap &&
@@ -5657,31 +5623,19 @@ export const Preview: React.FC = () => {
const clipToTrackIndex = new Map<string, number>();
tracks.forEach((track, idx) => {
- if (
- (track.type === "video" || track.type === "image") &&
- !track.hidden
- ) {
+ if (!track.hidden) {
for (const clip of track.clips) {
- clipToTrackIndex.set(clip.id, idx);
+ if (mediaClipHasVisual(clip)) {
+ clipToTrackIndex.set(clip.id, idx);
+ }
}
}
});
- const allRenderableTracks = tracks
- .map((track, idx) => ({ track, originalIndex: idx }))
- .filter(
- ({ track }) =>
- (track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics") &&
- !track.hidden,
- )
- .sort((a, b) => b.originalIndex - a.originalIndex);
+ const allRenderableTracks = getVisibleTrackRenderOrder(tracks);
if (canvasFillModeRef.current === "blur") {
- for (const { track, originalIndex } of allRenderableTracks) {
- if (track.type !== "video") continue;
+ for (const { originalIndex } of allRenderableTracks) {
const baseFrame = validFrames.find(
(f) => clipToTrackIndex.get(f.clip.id) === originalIndex,
);
@@ -5707,96 +5661,30 @@ export const Preview: React.FC = () => {
rendererRef.current &&
rendererRef.current.type === "webgpu" &&
!activeTextNeedsSubject &&
+ currentTextClips.length === 0 &&
+ currentShapeClips.length === 0 &&
+ !hasActiveMotionInstances(currentPlayhead) &&
!validFrames.some(({ clip }) => clipMasksById.has(clip.id));
if (useGPU) {
const gpuLayers: GPULayer[] = [];
const tempBitmaps: ImageBitmap[] = [];
- for (const { track, originalIndex } of allRenderableTracks) {
- if (track.type === "video") {
- const trackFrames = validFrames.filter(
- (f) => clipToTrackIndex.get(f.clip.id) === originalIndex,
- );
- for (const { transform, frame } of trackFrames) {
- if (frame instanceof ImageBitmap) {
- gpuLayers.push({
- bitmap: frame,
- transform,
- });
- }
- }
- } else if (track.type === "image") {
- const trackFrames = validFrames.filter(
- (f) => clipToTrackIndex.get(f.clip.id) === originalIndex,
- );
- for (const { transform, frame } of trackFrames) {
- drawFrameWithTransform(
- ctx,
- frame,
+ for (const { originalIndex } of allRenderableTracks) {
+ const trackFrames = validFrames.filter(
+ (frame) =>
+ clipToTrackIndex.get(frame.clip.id) === originalIndex,
+ );
+ for (const { transform, frame } of trackFrames) {
+ if (frame instanceof ImageBitmap) {
+ gpuLayers.push({
+ bitmap: frame,
transform,
- canvas.width,
- canvas.height,
- );
- }
- } else if (track.type === "graphics") {
- const trackShapeClips = activeShapeClips.filter(
- (sc) => sc.trackId === track.id,
- );
- for (const shapeClip of trackShapeClips) {
- await renderShapeClipWithEffects(
- ctx,
- shapeClip,
- canvas.width,
- canvas.height,
- currentPlayhead,
- );
- }
- await renderMotionInstancesForTrack(
- ctx,
- track,
- currentPlayhead,
- canvas.width,
- canvas.height,
- );
- } else if (track.type === "text") {
- const trackTextClips = activeTextClips.filter(
- (tc) => tc.trackId === track.id,
- );
- for (const textClip of trackTextClips) {
- const offscreen = new OffscreenCanvas(
- canvas.width,
- canvas.height,
- );
- const offCtx = offscreen.getContext("2d");
- if (offCtx) {
- renderTextClipToCanvas(
- offCtx as unknown as CanvasRenderingContext2D,
- textClip,
- canvas.width,
- canvas.height,
- currentPlayhead,
- );
- const prepared = await preparePreviewFrame(
- textClip.id,
- offscreen,
- true,
- true,
- );
- const bitmap = await createImageBitmap(prepared.frame);
- prepared.cleanup();
- tempBitmaps.push(bitmap);
- gpuLayers.push({
- bitmap,
- transform: {
- ...DEFAULT_TRANSFORM,
- opacity: 1,
- scale: { x: 1, y: 1 },
- position: { x: 0, y: 0 },
- anchor: { x: 0, y: 0 },
- },
- });
- }
+ });
+ } else {
+ const bitmap = await createImageBitmap(frame);
+ tempBitmaps.push(bitmap);
+ gpuLayers.push({ bitmap, transform });
}
}
}
@@ -5830,68 +5718,66 @@ export const Preview: React.FC = () => {
} else {
let subjectFrame: ImageBitmap | null = null;
for (const { track, originalIndex } of allRenderableTracks) {
- if (track.type === "video" || track.type === "image") {
- const trackFrames = validFrames.filter(
- (f) => clipToTrackIndex.get(f.clip.id) === originalIndex,
- );
- for (const { clip, transform, frame } of trackFrames) {
- await drawClipFrame(
- ctx,
- clip.id,
- frame,
- transform,
- canvas.width,
- canvas.height,
- currentPlayhead,
- );
- if (activeTextNeedsSubject) {
- subjectFrame?.close();
- subjectFrame = await captureSubjectFrame(
- ctx,
- canvas.width,
- canvas.height,
- );
- }
- }
- } else if (track.type === "graphics") {
- const trackShapeClips = activeShapeClips.filter(
- (sc) => sc.trackId === track.id,
+ const trackFrames = validFrames.filter(
+ (frame) =>
+ clipToTrackIndex.get(frame.clip.id) === originalIndex,
+ );
+ for (const { clip, transform, frame } of trackFrames) {
+ await drawClipFrame(
+ ctx,
+ clip.id,
+ frame,
+ transform,
+ canvas.width,
+ canvas.height,
+ currentPlayhead,
);
- for (const shapeClip of trackShapeClips) {
- await renderShapeClipWithEffects(
+ if (activeTextNeedsSubject) {
+ subjectFrame?.close();
+ subjectFrame = await captureSubjectFrame(
ctx,
- shapeClip,
canvas.width,
canvas.height,
- currentPlayhead,
);
}
- await renderMotionInstancesForTrack(
+ }
+ const trackShapeClips = activeShapeClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const shapeClip of trackShapeClips) {
+ await renderShapeClipWithEffects(
ctx,
- track,
- currentPlayhead,
+ shapeClip,
canvas.width,
canvas.height,
+ currentPlayhead,
);
- } else if (track.type === "text") {
- const trackTextClips = activeTextClips.filter(
- (tc) => tc.trackId === track.id,
- );
- for (const textClip of trackTextClips) {
- await renderTextClipWithSubjectMask(
- ctx,
- textClip,
- canvas.width,
- canvas.height,
+ }
+ await renderMotionInstancesForTrack(
+ ctx,
+ track,
+ currentPlayhead,
+ canvas.width,
+ canvas.height,
+ );
+ const trackTextClips = activeTextClips.filter(
+ (clip) => clip.trackId === track.id,
+ );
+ for (const textClip of trackTextClips) {
+ await renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ canvas.width,
+ canvas.height,
+ currentPlayhead,
+ subjectFrame,
+ true,
+ getBehindSubjectStreamId(
+ timelineTracksRef.current,
currentPlayhead,
- subjectFrame,
- true,
- getBehindSubjectStreamId(
- timelineTracksRef.current,
- currentPlayhead,
- ),
- );
- }
+ getMediaItem,
+ ),
+ );
}
}
subjectFrame?.close();
@@ -5986,14 +5872,12 @@ export const Preview: React.FC = () => {
const findNextClipStartTime = (afterTime: number): number | null => {
const tracks = timelineTracksRef.current;
- const videoTracks = tracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
- );
+ const videoTracks = tracks.filter((track) => !track.hidden);
let nextStart: number | null = null;
for (const track of videoTracks) {
for (const clip of track.clips) {
- if (clip.startTime > afterTime) {
+ if (mediaClipHasVisual(clip) && clip.startTime > afterTime) {
if (nextStart === null || clip.startTime < nextStart) {
nextStart = clip.startTime;
}
@@ -6048,12 +5932,12 @@ export const Preview: React.FC = () => {
const findNextAudioClipStartTime = (afterTime: number): number | null => {
const tracks = timelineTracksRef.current;
- const audioTracks = tracks.filter((t) => t.type === "audio" && !t.hidden);
+ const audioTracks = tracks.filter((track) => !track.hidden);
let nextStart: number | null = null;
for (const track of audioTracks) {
for (const clip of track.clips) {
- if (clip.startTime > afterTime) {
+ if (mediaClipHasAudio(clip) && clip.startTime > afterTime) {
if (nextStart === null || clip.startTime < nextStart) {
nextStart = clip.startTime;
}
@@ -6137,15 +6021,18 @@ export const Preview: React.FC = () => {
previewRes.width,
previewRes.height,
previewRes.scale,
+ editingFrameDuration,
hasActiveMotionInstances,
renderMotionInstancesForTrack,
- project.motionInstances,
+ project,
+ mediaClipHasAudio,
+ mediaClipHasVisual,
clipMasksById,
drawClipFrame,
fillPreviewBackground,
]);
- const lastModifiedAtRef = useRef<number>(project.modifiedAt);
+ const lastProjectForRenderRef = useRef(project);
const lastPlayheadForRenderRef = useRef<number>(playheadPosition);
const modifiedRenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const renderInFlightRef = useRef<boolean>(false);
@@ -6155,7 +6042,7 @@ export const Preview: React.FC = () => {
if (isPlaying) return;
if (isInteractingRef.current) {
- lastModifiedAtRef.current = project.modifiedAt;
+ lastProjectForRenderRef.current = project;
return;
}
@@ -6163,9 +6050,9 @@ export const Preview: React.FC = () => {
if (!canvas) return;
const playheadChanged = playheadPosition !== lastPlayheadForRenderRef.current;
- const modifiedChanged = project.modifiedAt !== lastModifiedAtRef.current;
+ const projectChanged = project !== lastProjectForRenderRef.current;
- lastModifiedAtRef.current = project.modifiedAt;
+ lastProjectForRenderRef.current = project;
lastPlayheadForRenderRef.current = playheadPosition;
const previousRenderTime = lastPreviewRenderTimeRef.current;
@@ -6205,7 +6092,7 @@ export const Preview: React.FC = () => {
if (playheadChanged) {
doRender(playheadPosition);
- } else if (modifiedChanged) {
+ } else if (projectChanged) {
if (modifiedRenderTimerRef.current) {
clearTimeout(modifiedRenderTimerRef.current);
}
@@ -6228,7 +6115,7 @@ export const Preview: React.FC = () => {
renderFrameDirectly,
renderFallbackFrame,
releaseScrubVideoElements,
- project.modifiedAt,
+ project,
isDark,
]);
@@ -6267,11 +6154,12 @@ export const Preview: React.FC = () => {
}, [selectedClipId, timelineTracks]);
const clipAtPlayhead = useMemo(() => {
- const videoTracks = timelineTracks.filter(
- (t) => (t.type === "video" || t.type === "image") && !t.hidden,
- );
+ const videoTracks = timelineTracks.filter((track) => !track.hidden);
for (const track of videoTracks) {
for (const clip of track.clips) {
+ if (!mediaClipHasVisual(clip)) {
+ continue;
+ }
const clipStart = clip.startTime;
const clipEnd = clip.startTime + clip.duration;
if (playheadPosition >= clipStart && playheadPosition < clipEnd) {
@@ -6280,7 +6168,7 @@ export const Preview: React.FC = () => {
}
}
return null;
- }, [timelineTracks, playheadPosition]);
+ }, [timelineTracks, playheadPosition, mediaClipHasVisual]);
const selectedTextClipId = useMemo(() => {
const textClipSelection = selectedItems.find(
@@ -7451,8 +7339,9 @@ export const Preview: React.FC = () => {
);
const handleMouseUp = useCallback(() => {
+ let transformCommit: ReturnType<typeof updateClipTransform> | null = null;
if (pendingTransformRef.current) {
- updateClipTransform(
+ transformCommit = updateClipTransform(
pendingTransformRef.current.clipId,
pendingTransformRef.current.transform,
);
@@ -7474,7 +7363,11 @@ export const Preview: React.FC = () => {
setCanvasSnapGuides({ x: null, y: null });
if (wasInteracting) {
- renderFrameDirectly(playheadPosition);
+ if (transformCommit) {
+ void transformCommit.then(() => renderFrameDirectly(playheadPosition));
+ } else {
+ void renderFrameDirectly(playheadPosition);
+ }
}
}, [updateClipTransform, renderFrameDirectly, playheadPosition]);
@@ -7498,8 +7391,11 @@ export const Preview: React.FC = () => {
useEffect(() => {
if (interactionMode !== "none") {
const handleGlobalMouseUp = () => {
+ let transformCommit: ReturnType<
+ typeof updateClipTransform
+ > | null = null;
if (pendingTransformRef.current) {
- updateClipTransform(
+ transformCommit = updateClipTransform(
pendingTransformRef.current.clipId,
pendingTransformRef.current.transform,
);
@@ -7518,7 +7414,13 @@ export const Preview: React.FC = () => {
setLiveTransform(null);
if (wasInteracting) {
- renderFrameDirectly(playheadPosition);
+ if (transformCommit) {
+ void transformCommit.then(() =>
+ renderFrameDirectly(playheadPosition),
+ );
+ } else {
+ void renderFrameDirectly(playheadPosition);
+ }
}
};
diff --git a/apps/web/src/components/editor/Timeline.tsx b/apps/web/src/components/editor/Timeline.tsx
index 474c957a..d338a733 100644
--- a/apps/web/src/components/editor/Timeline.tsx
+++ b/apps/web/src/components/editor/Timeline.tsx
@@ -11,11 +11,8 @@ import {
Layers,
Maximize2,
Minimize2,
- Film,
Music,
- Image,
Type,
- Shapes,
Scissors,
Copy,
Delete,
@@ -52,6 +49,7 @@ import { useUIStore } from "../../stores/ui-store";
import { toast } from "../../stores/notification-store";
import { useEngineStore } from "../../stores/engine-store";
import { getPlaybackBridge } from "../../bridges/playback-bridge";
+import { trackHasAudioItems, trackHasVisualItems } from "@openreel/core";
import {
deleteTimelineItem,
duplicateTimelineItem,
@@ -737,42 +735,37 @@ export const Timeline: React.FC = () => {
const handleDropMedia = useCallback(
async (trackId: string, mediaId: string, startTime: number) => {
- const { addClip, addClipToNewTrack } = useProjectStore.getState();
- if (trackId) {
- await addClip(trackId, mediaId, startTime);
- } else {
- await addClipToNewTrack(mediaId, startTime);
- }
+ await useProjectStore
+ .getState()
+ .placeMediaClip(mediaId, trackId || undefined, startTime);
},
[],
);
- const { moveClip } = useProjectStore();
const handleMoveClip = useCallback(
async (clipId: string, newStartTime: number, targetTrackId?: string) => {
const store = useProjectStore.getState();
- const isGraphic = Boolean(
- store.getShapeClip(clipId) ||
+ const sourceClip = store.getClip(clipId);
+ const isOverlay = Boolean(
+ store.getTextClip(clipId) ||
+ store.getShapeClip(clipId) ||
store.getSVGClip(clipId) ||
store.getStickerClip(clipId),
);
- if (isGraphic) {
- store.updateOverlayClipTiming(clipId, {
- startTime: newStartTime,
- });
- } else {
- const sourceClip = store.getClip(clipId);
- const result = await moveClip(clipId, newStartTime, targetTrackId);
- if (result.success && sourceClip) {
- moveLinkedCaptions(
- useProjectStore.getState(),
- sourceClip,
- newStartTime,
- );
- }
+ const result = targetTrackId
+ ? await store.moveTimelineItem(clipId, newStartTime, targetTrackId)
+ : isOverlay
+ ? store.updateOverlayClipTiming(clipId, {
+ startTime: newStartTime,
+ })
+ ? { success: true as const }
+ : { success: false as const }
+ : await store.moveClip(clipId, newStartTime);
+ if (result.success && sourceClip) {
+ moveLinkedCaptions(useProjectStore.getState(), sourceClip, newStartTime);
}
},
- [moveClip],
+ [],
);
const [snapIndicatorTime, setSnapIndicatorTime] = React.useState<
@@ -801,12 +794,10 @@ export const Timeline: React.FC = () => {
);
const handleMoveTextClip = useCallback(
- (clipId: string, newStartTime: number) => {
- useProjectStore.getState().updateOverlayClipTiming(clipId, {
- startTime: Math.max(0, newStartTime),
- });
+ async (clipId: string, newStartTime: number, targetTrackId?: string) => {
+ await handleMoveClip(clipId, Math.max(0, newStartTime), targetTrackId);
},
- [],
+ [handleMoveClip],
);
const handleTrimShapeClip = useCallback(
@@ -894,30 +885,39 @@ export const Timeline: React.FC = () => {
const addTrackItems: DropdownMenuOption[] = useMemo(
() => [
{
- label: "Video Track",
- icon: <Film size={16} className="text-clip-video" aria-hidden />,
- onClick: () => addTrack("video"),
+ label: "Track",
+ icon: <Layers size={16} className="text-foreground" aria-hidden />,
+ onClick: () => addTrack("video", undefined, { mode: "standard" }),
},
{
- label: "Audio Track",
+ label: "Dialogue",
icon: <Music size={16} className="text-clip-audio" aria-hidden />,
- onClick: () => addTrack("audio"),
+ onClick: () =>
+ addTrack("video", undefined, {
+ mode: "standard",
+ role: "dialogue",
+ name: "Dialogue",
+ }),
},
- { type: "divider" },
{
- label: "Image Track",
- icon: <Image size={16} className="text-clip-music" aria-hidden />,
- onClick: () => addTrack("image"),
+ label: "Music",
+ icon: <Music size={16} className="text-clip-audio" aria-hidden />,
+ onClick: () =>
+ addTrack("video", undefined, {
+ mode: "standard",
+ role: "music",
+ name: "Music",
+ }),
},
{
- label: "Text Track",
+ label: "Captions",
icon: <Type size={16} className="text-clip-text" aria-hidden />,
- onClick: () => addTrack("text"),
- },
- {
- label: "Graphics Track",
- icon: <Shapes size={16} className="text-clip-music" aria-hidden />,
- onClick: () => addTrack("graphics"),
+ onClick: () =>
+ addTrack("video", undefined, {
+ mode: "standard",
+ role: "captions",
+ name: "Captions",
+ }),
},
],
[addTrack],
@@ -1140,11 +1140,8 @@ export const Timeline: React.FC = () => {
{filteredTrackEntries.map(({ track, index }) => {
const info = getTrackInfo(track, index);
const name = track.name || info.label;
- const isVisual =
- track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics";
+ const isVisual = trackHasVisualItems(project, track.id);
+ const isAudio = trackHasAudioItems(project, track.id);
return (
<div
key={track.id}
@@ -1191,16 +1188,13 @@ export const Timeline: React.FC = () => {
variant="ghost"
onClick={() => startTrackRename(track.id, name)}
/>
- {track.type !== "text" &&
- track.type !== "graphics" ? (
- <IconButton
- label={`Duplicate ${name}`}
- icon={<Copy size={12} aria-hidden />}
- size="sm"
- variant="ghost"
- onClick={() => void duplicateTrack(track.id)}
- />
- ) : null}
+ <IconButton
+ label={`Duplicate ${name}`}
+ icon={<Copy size={12} aria-hidden />}
+ size="sm"
+ variant="ghost"
+ onClick={() => void duplicateTrack(track.id)}
+ />
<IconButton
label={`Delete ${name}`}
icon={<Trash2 size={12} aria-hidden />}
@@ -1224,7 +1218,7 @@ export const Timeline: React.FC = () => {
onClick={() => void hideTrack(track.id, !track.hidden)}
/>
) : null}
- {track.type === "audio" ? (
+ {isAudio ? (
<>
<IconButton
label={`Mute ${name}`}
@@ -1497,7 +1491,9 @@ export const Timeline: React.FC = () => {
})}
<button
type="button"
- onClick={() => addTrack("video")}
+ onClick={() =>
+ addTrack("video", undefined, { mode: "standard" })
+ }
className="mx-3 my-1 h-7 flex items-center justify-center gap-1.5 rounded-[7px] border border-dashed border-border-strong text-fg-muted hover:text-fg-2 hover:border-fg-3 transition-colors"
aria-label="Add track"
>
@@ -1590,7 +1586,7 @@ export const Timeline: React.FC = () => {
// External OS file drop (e.g. from Windows Explorer)
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
- const { importMedia, addClipToNewTrack } = useProjectStore.getState();
+ const { importMedia, placeMediaClip } = useProjectStore.getState();
for (const file of Array.from(e.dataTransfer.files)) {
try {
const beforeIds = new Set(
@@ -1602,7 +1598,7 @@ export const Timeline: React.FC = () => {
.getState()
.project.mediaLibrary.items.find(i => !beforeIds.has(i.id));
if (newItem) {
- await addClipToNewTrack(newItem.id, snappedTime);
+ await placeMediaClip(newItem.id, undefined, snappedTime);
const track = useProjectStore
.getState()
.project.timeline.tracks.find(t =>
@@ -1651,13 +1647,7 @@ export const Timeline: React.FC = () => {
onDropMedia={handleDropMedia}
onMoveClip={handleMoveClip}
onSnapIndicator={handleSnapIndicator}
- onTrimClip={
- track.type === "video" ||
- track.type === "image" ||
- track.type === "audio"
- ? handleTrimClip
- : undefined
- }
+ onTrimClip={handleTrimClip}
onTrimTextClip={handleTrimTextClip}
onMoveTextClip={handleMoveTextClip}
onTrimShapeClip={handleTrimShapeClip}
diff --git a/apps/web/src/components/editor/ai-panel/AIJobList.tsx b/apps/web/src/components/editor/ai-panel/AIJobList.tsx
deleted file mode 100644
index b1e5686c..00000000
--- a/apps/web/src/components/editor/ai-panel/AIJobList.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { JSX } from "react";
-import { ToolcraftButton as Button } from "@openreel/ui";
-import { useGpuJobStore } from "../../../stores/gpu-job-store";
-import { useProjectStore } from "../../../stores/project-store";
-import { getWebGpuClient } from "../../../services/gpu-web-client";
-
-export function AIJobList(): JSX.Element | null {
- const jobs = useGpuJobStore((s) => s.jobs);
- const projectId = useProjectStore((s) => s.project?.id);
- const mine = jobs.filter((job) => job.projectId === projectId);
-
- if (mine.length === 0) return null;
-
- return (
- <div className="flex flex-col gap-2 p-2">
- {mine.map((job) => (
- <div
- key={job.jobID}
- className="flex items-center justify-between gap-2 rounded bg-background-secondary px-3 py-2 text-[11px] border border-border"
- >
- <span className="truncate text-text-primary">{job.suggestedName}</span>
- <span className="ml-2 shrink-0 text-[10px] text-text-muted">
- {job.failed ? "Failed" : "Running…"}
- </span>
- {job.failed ? (
- <Button
- label="Retry"
- variant="ghost"
- size="sm"
- className="ml-2 shrink-0 text-[10px] text-primary hover:text-primary/80"
- onClick={() => {
- useGpuJobStore.getState().retryJob(job.jobID);
- useProjectStore.getState().setKieAIItemState(job.mediaId, true, false);
- }}
- />
- ) : (
- <Button
- label="Cancel"
- variant="ghost"
- size="sm"
- className="ml-2 shrink-0 text-[10px] text-text-muted hover:text-text-primary"
- onClick={() => {
- // Best-effort server cancel; the job may already be gone (404)
- // — never let that surface as an uncaught rejection.
- const cancel = window.openreel?.gpu
- ? window.openreel.gpu.cancelJob(job.jobID)
- : getWebGpuClient().cancelJob(job.jobID);
- void cancel.catch(() => undefined);
- useGpuJobStore.getState().removeJob(job.jobID);
- }}
- />
- )}
- </div>
- ))}
- </div>
- );
-}
diff --git a/apps/web/src/components/editor/ai-panel/AIPanel.tsx b/apps/web/src/components/editor/ai-panel/AIPanel.tsx
deleted file mode 100644
index 6aae82fd..00000000
--- a/apps/web/src/components/editor/ai-panel/AIPanel.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import type { JSX } from "react";
-import { useMemo, useState } from "react";
-import { ToolcraftButton as Button } from "@openreel/ui";
-import { ToolcraftText as Text } from "@openreel/ui";
-import {
- AI_KINDS,
- AI_KIND_GROUPS,
- kindMatchesClipType,
- isWebSupported,
- type AiKindDef,
- type ClipMediaType,
-} from "./ai-kinds.config";
-import { AIJobList } from "./AIJobList";
-import { PhotoToolsEditor } from "./photo-tools/PhotoToolsEditor";
-import { ObjectTrackingEditor } from "./tracking/ObjectTrackingEditor";
-import { isGpuAvailable } from "../../../services/gpu-jobs";
-import { submitSelectedClipJob } from "../../../services/gpu-clip-submit";
-
-export interface AIPanelProps {
- clipTypeFilter?: ClipMediaType | null;
- embedded?: boolean;
-}
-
-export function AIPanel({ clipTypeFilter = null, embedded = false }: AIPanelProps = {}): JSX.Element {
- const [busyKind, setBusyKind] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const [editorKind, setEditorKind] = useState<string | null>(null);
-
- const visibleKinds: AiKindDef[] = useMemo(
- () =>
- AI_KINDS.filter(
- (k) => isWebSupported(k) && (!clipTypeFilter || kindMatchesClipType(k, clipTypeFilter)),
- ),
- [clipTypeFilter],
- );
- const visibleGroups = useMemo(
- () => AI_KIND_GROUPS.filter((group) => visibleKinds.some((k) => k.group === group)),
- [visibleKinds],
- );
-
- const runKind = async (kind: string, requiresClip: boolean): Promise<void> => {
- setError(null);
- setBusyKind(kind);
- try {
- const def = AI_KINDS.find((k) => k.kind === kind);
- await submitSelectedClipJob({
- kind,
- requiresClip,
- suggestedName: `${def?.label ?? kind} result`,
- });
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- } finally {
- setBusyKind(null);
- }
- };
-
- if (!isGpuAvailable()) {
- return <div className="p-3 text-[11px] text-text-muted">AI cloud jobs are unavailable in this environment.</div>;
- }
-
- return (
- <div className={embedded ? "flex flex-col" : "flex h-full flex-col overflow-y-auto"}>
- {error && (
- <div className="m-2 rounded bg-red-900/50 px-3 py-2 text-[10px] text-red-200">{error}</div>
- )}
- {visibleGroups.map((group) => (
- <div key={group} className={embedded ? "py-1.5" : "p-2"}>
- <Text type="label" color="secondary" weight="semibold" className="mb-1 text-[10px] uppercase tracking-wide text-text-muted">{group}</Text>
- <div className="grid grid-cols-2 gap-2">
- {visibleKinds
- .filter((k) => k.group === group)
- .map((k) => (
- <Button
- key={k.kind}
- label={busyKind === k.kind ? "Submitting" : k.label}
- variant="ghost"
- isDisabled={busyKind !== null}
- className="rounded bg-background-tertiary px-3 py-2 text-left text-[11px] text-text-primary transition-colors hover:bg-background-secondary disabled:opacity-50"
- onClick={() =>
- k.interactive ? setEditorKind(k.kind) : void runKind(k.kind, k.requiresClip)
- }
- >
- {busyKind === k.kind ? "Submitting…" : k.label}
- </Button>
- ))}
- </div>
- </div>
- ))}
- <AIJobList />
- {editorKind === "object_removal" && <PhotoToolsEditor onClose={() => setEditorKind(null)} />}
- {editorKind === "object_tracking" && <ObjectTrackingEditor onClose={() => setEditorKind(null)} />}
- </div>
- );
-}
diff --git a/apps/web/src/components/editor/ai-panel/ai-kinds.config.test.ts b/apps/web/src/components/editor/ai-panel/ai-kinds.config.test.ts
deleted file mode 100644
index 72e9077f..00000000
--- a/apps/web/src/components/editor/ai-panel/ai-kinds.config.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- AI_KINDS,
- AI_KIND_GROUPS,
- kindsForClipType,
- kindMatchesClipType,
- isWebSupported,
- outputForKind,
- type ClipMediaType,
-} from "./ai-kinds.config";
-import { AI_CLOUD_JOB_KINDS } from "@openreel/core";
-
-const kindByLabel = (label: string) => AI_KINDS.find((k) => k.label === label)!;
-
-describe("ai-kinds output classification", () => {
- it("classifies the data-output kinds correctly", () => {
- expect(outputForKind(AI_CLOUD_JOB_KINDS.transcription)).toBe("subtitles");
- expect(outputForKind(AI_CLOUD_JOB_KINDS.autoCaptions)).toBe("subtitles");
- expect(outputForKind(AI_CLOUD_JOB_KINDS.sceneDetection)).toBe("scenes");
- expect(outputForKind(AI_CLOUD_JOB_KINDS.aiHighlight)).toBe("highlights");
- expect(outputForKind(AI_CLOUD_JOB_KINDS.objectTracking)).toBe("tracking");
- expect(outputForKind(AI_CLOUD_JOB_KINDS.upscale)).toBe("media");
- });
-
- it("hides kinds with no web consumer yet", () => {
- const hidden = ["Person Matte", "Stabilize", "Auto Reframe", "Face Analysis", "Remove Silence", "Translate"];
- for (const label of hidden) expect(isWebSupported(kindByLabel(label))).toBe(false);
- });
-
- it("keeps the wired data kinds web-supported", () => {
- const supported = ["Transcribe", "Auto Captions", "Scene Detection", "AI Highlights", "Object Tracking"];
- for (const label of supported) expect(isWebSupported(kindByLabel(label))).toBe(true);
- });
-
- it("marks the interactive editors", () => {
- expect(kindByLabel("Object Removal").interactive).toBe(true);
- expect(kindByLabel("Object Tracking").interactive).toBe(true);
- });
-});
-
-describe("ai-kinds.config", () => {
- it("covers all 25 job kinds exactly once", () => {
- const kinds = AI_KINDS.map((k) => k.kind).sort();
- const all = Object.values(AI_CLOUD_JOB_KINDS).sort();
- expect(kinds).toEqual(all);
- });
- it("only music_generation and translation are clip-optional", () => {
- const optional = AI_KINDS.filter((k) => !k.requiresClip).map((k) => k.kind).sort();
- expect(optional).toEqual(["music_generation", "translation"]);
- });
- it("every kind's group is a known group", () => {
- for (const k of AI_KINDS) expect(AI_KIND_GROUPS).toContain(k.group);
- });
- it("clip-optional kinds have no media relevance; clip-requiring kinds have at least one", () => {
- for (const k of AI_KINDS) {
- if (k.requiresClip) expect(k.media.length).toBeGreaterThan(0);
- else expect(k.media).toEqual([]);
- }
- });
-});
-
-describe("ai-kinds clip-type relevance", () => {
- const labelsFor = (clipType: ClipMediaType): string[] =>
- kindsForClipType(clipType).map((k) => k.label);
-
- it("never includes clip-free Generate kinds in a clip-scoped view", () => {
- for (const clipType of ["video", "image", "audio"] as const) {
- const kinds = kindsForClipType(clipType);
- expect(kinds.every((k) => k.requiresClip)).toBe(true);
- expect(kinds.some((k) => k.group === "Generate")).toBe(false);
- expect(kinds.every((k) => kindMatchesClipType(k, clipType))).toBe(true);
- }
- });
-
- it("image hides motion/temporal/video-only kinds but keeps stills tools", () => {
- const image = labelsFor("image");
- expect(kindsForClipType("image").some((k) => k.group === "Audio")).toBe(false);
- expect(image).not.toContain("Stabilize");
- expect(image).not.toContain("Auto Reframe");
- expect(image).not.toContain("Smooth (Interpolate)");
- expect(image).not.toContain("Person Matte");
- expect(image).not.toContain("Face Analysis");
- expect(image).toContain("Upscale");
- expect(image).toContain("Denoise");
- expect(image).toContain("Face Restore");
- expect(image).toContain("Color Match");
- expect(image).toContain("Photo Enhance");
- expect(image).toContain("Colorize");
- expect(image).toContain("Remove Background");
- expect(image).toContain("Object Removal");
- expect(image).toContain("Portrait Bokeh");
- });
-
- it("audio shows only audio-relevant kinds", () => {
- const audio = labelsFor("audio");
- expect(audio).toContain("Separate Audio");
- expect(audio).toContain("Enhance Voice");
- expect(audio).toContain("Transcribe");
- expect(audio).not.toContain("Upscale");
- expect(audio).not.toContain("Stabilize");
- });
-
- it("video shows motion + analyze + audio kinds but not image-only enhancers", () => {
- const video = labelsFor("video");
- expect(video).toContain("Smooth (Interpolate)");
- expect(video).toContain("Stabilize");
- expect(video).toContain("Person Matte");
- expect(video).toContain("Separate Audio");
- expect(video).toContain("Scene Detection");
- expect(video).not.toContain("Remove Background");
- expect(video).not.toContain("Upscale");
- expect(video).not.toContain("Denoise");
- expect(video).not.toContain("Face Restore");
- expect(video).not.toContain("Color Match");
- });
-
- it("kindMatchesClipType reflects the media array (upscale is image-only)", () => {
- const upscale = AI_KINDS.find((k) => k.label === "Upscale");
- expect(upscale).toBeDefined();
- expect(kindMatchesClipType(upscale!, "image")).toBe(true);
- expect(kindMatchesClipType(upscale!, "video")).toBe(false);
- expect(kindMatchesClipType(upscale!, "audio")).toBe(false);
- });
-
- it("worker-accurate filters: frame-output enhancers are image-only, AI Highlights is video-only", () => {
- for (const label of ["Upscale", "Denoise", "Face Restore", "Color Match"]) {
- const kind = AI_KINDS.find((k) => k.label === label);
- expect(kind, label).toBeDefined();
- expect(kind!.media).toEqual(["image"]);
- }
- const highlights = AI_KINDS.find((k) => k.label === "AI Highlights");
- expect(highlights!.media).toEqual(["video"]);
- });
-});
diff --git a/apps/web/src/components/editor/ai-panel/ai-kinds.config.ts b/apps/web/src/components/editor/ai-panel/ai-kinds.config.ts
deleted file mode 100644
index 1f15c752..00000000
--- a/apps/web/src/components/editor/ai-panel/ai-kinds.config.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { AI_CLOUD_JOB_KINDS } from "@openreel/core";
-
-export type ClipMediaType = "video" | "image" | "audio";
-
-export type AiKindOutput = "media" | "subtitles" | "scenes" | "highlights" | "tracking";
-
-/**
- * For output:"media" kinds, how the result is applied:
- * - "replace": the result IS the clip's transformed media → replace the clip's
- * source media in place (no new library tile).
- * - "newAsset": the result is genuinely new content (generated music, audio
- * stems, thumbnails) → add it to the media library as a new item.
- */
-export type AiKindApply = "replace" | "newAsset";
-
-export interface AiKindDef {
- kind: string;
- label: string;
- group: "Enhance" | "Cut-out" | "Motion" | "Analyze" | "Audio" | "Generate";
- requiresClip: boolean;
- media: ClipMediaType[];
- output: AiKindOutput;
- apply?: AiKindApply;
- webSupported?: boolean;
- interactive?: boolean;
- /**
- * The worker emits multiple distinct media artifacts that should each become
- * their own library item (e.g. audio_separation -> vocals/drums/bass/other
- * stems). Without this, only the single primaryArtifact is imported — which
- * for demucs is the alphabetically-first (bass) stem, often near-silent.
- */
- multiAsset?: boolean;
-}
-
-export const AI_KINDS: AiKindDef[] = [
- { kind: AI_CLOUD_JOB_KINDS.upscale, label: "Upscale", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.denoise, label: "Denoise", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.faceRestore, label: "Face Restore", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.photoEnhance, label: "Photo Enhance", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.colorize, label: "Colorize", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.colorMatch, label: "Color Match", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.backgroundRemoval, label: "Remove Background", group: "Cut-out", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.personMatting, label: "Person Matte", group: "Cut-out", requiresClip: true, media: ["video"], output: "media", webSupported: false },
- { kind: AI_CLOUD_JOB_KINDS.objectRemoval, label: "Object Removal", group: "Cut-out", requiresClip: true, media: ["image"], output: "media", interactive: true },
- { kind: AI_CLOUD_JOB_KINDS.stabilization, label: "Stabilize", group: "Motion", requiresClip: true, media: ["video"], output: "tracking", webSupported: false },
- { kind: AI_CLOUD_JOB_KINDS.autoReframe, label: "Auto Reframe", group: "Motion", requiresClip: true, media: ["video"], output: "tracking", webSupported: false },
- { kind: AI_CLOUD_JOB_KINDS.frameInterpolation, label: "Smooth (Interpolate)", group: "Motion", requiresClip: true, media: ["video"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.portraitBokeh, label: "Portrait Bokeh", group: "Enhance", requiresClip: true, media: ["image"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.transcription, label: "Transcribe", group: "Analyze", requiresClip: true, media: ["video", "audio"], output: "subtitles" },
- { kind: AI_CLOUD_JOB_KINDS.autoCaptions, label: "Auto Captions", group: "Analyze", requiresClip: true, media: ["video", "audio"], output: "subtitles" },
- { kind: AI_CLOUD_JOB_KINDS.sceneDetection, label: "Scene Detection", group: "Analyze", requiresClip: true, media: ["video"], output: "scenes" },
- { kind: AI_CLOUD_JOB_KINDS.faceAnalysis, label: "Face Analysis", group: "Analyze", requiresClip: true, media: ["video"], output: "tracking", webSupported: false },
- { kind: AI_CLOUD_JOB_KINDS.objectTracking, label: "Object Tracking", group: "Analyze", requiresClip: true, media: ["video"], output: "tracking", interactive: true },
- { kind: AI_CLOUD_JOB_KINDS.smartThumbnail, label: "Smart Thumbnail", group: "Analyze", requiresClip: true, media: ["video"], output: "media", apply: "newAsset" },
- { kind: AI_CLOUD_JOB_KINDS.aiHighlight, label: "AI Highlights", group: "Analyze", requiresClip: true, media: ["video"], output: "highlights" },
- { kind: AI_CLOUD_JOB_KINDS.audioSeparation, label: "Separate Audio", group: "Audio", requiresClip: true, media: ["video", "audio"], output: "media", apply: "newAsset", multiAsset: true },
- { kind: AI_CLOUD_JOB_KINDS.voiceEnhance, label: "Enhance Voice", group: "Audio", requiresClip: true, media: ["video", "audio"], output: "media" },
- { kind: AI_CLOUD_JOB_KINDS.silenceRemoval, label: "Remove Silence", group: "Audio", requiresClip: true, media: ["video", "audio"], output: "highlights", webSupported: false },
- { kind: AI_CLOUD_JOB_KINDS.musicGeneration, label: "Generate Music", group: "Generate", requiresClip: false, media: [], output: "media", apply: "newAsset" },
- { kind: AI_CLOUD_JOB_KINDS.translation, label: "Translate", group: "Generate", requiresClip: false, media: [], output: "subtitles", webSupported: false },
-];
-
-export const AI_KIND_GROUPS = ["Enhance", "Cut-out", "Motion", "Analyze", "Audio", "Generate"] as const;
-
-export function kindMatchesClipType(kind: AiKindDef, clipType: ClipMediaType): boolean {
- return kind.media.includes(clipType);
-}
-
-export function isWebSupported(kind: AiKindDef): boolean {
- return kind.webSupported !== false;
-}
-
-export function kindsForClipType(clipType: ClipMediaType): AiKindDef[] {
- return AI_KINDS.filter((kind) => kindMatchesClipType(kind, clipType));
-}
-
-export function outputForKind(kind: string): AiKindOutput {
- return AI_KINDS.find((k) => k.kind === kind)?.output ?? "media";
-}
-
-export function applyModeForKind(kind: string): AiKindApply {
- return AI_KINDS.find((k) => k.kind === kind)?.apply ?? "replace";
-}
-
-export function isMultiAssetKind(kind: string): boolean {
- return AI_KINDS.find((k) => k.kind === kind)?.multiAsset === true;
-}
diff --git a/apps/web/src/components/editor/ai-panel/photo-tools/PhotoToolsEditor.tsx b/apps/web/src/components/editor/ai-panel/photo-tools/PhotoToolsEditor.tsx
deleted file mode 100644
index afd149ca..00000000
--- a/apps/web/src/components/editor/ai-panel/photo-tools/PhotoToolsEditor.tsx
+++ /dev/null
@@ -1,251 +0,0 @@
-import type { JSX } from "react";
-import { useEffect, useState } from "react";
-import { ToolcraftSegmentedControl } from "@openreel/ui";
-import { ToolcraftButton as Button } from "@openreel/ui";
-import { ToolcraftCard as Card } from "@openreel/ui";
-import { ToolcraftDialog as Dialog, ToolcraftDialogHeader as DialogHeader } from "@openreel/ui";
-import { ToolcraftLayout as Layout, ToolcraftLayoutContent as LayoutContent, ToolcraftLayoutFooter as LayoutFooter } from "@openreel/ui";
-import { ToolcraftSliderControl } from "@openreel/ui";
-import { ToolcraftText as Text } from "@openreel/ui";
-import { ToolcraftTextInputControl } from "@openreel/ui";
-import { useProjectStore } from "../../../../stores/project-store";
-import { useUIStore } from "../../../../stores/ui-store";
-import { loadMediaBlob } from "../../../../services/media-storage";
-import { submitSelectedClipJob } from "../../../../services/gpu-clip-submit";
-import { SelectionCanvas } from "./SelectionCanvas";
-import {
- buildObjectRemovalParams,
- type ObjectMode,
- type MaskTool,
- type BBox,
- type NormPoint,
-} from "./object-removal-params";
-
-interface PhotoToolsEditorProps {
- onClose: () => void;
-}
-
-export function PhotoToolsEditor({ onClose }: PhotoToolsEditorProps): JSX.Element {
- const [imageUrl, setImageUrl] = useState<string | null>(null);
- const [loadError, setLoadError] = useState<string | null>(null);
-
- const [mode, setMode] = useState<ObjectMode>("erase");
- const [tool, setTool] = useState<MaskTool>("box");
- const [bbox, setBBox] = useState<BBox | null>(null);
- const [points, setPoints] = useState<NormPoint[]>([]);
- const [prompt, setPrompt] = useState("");
- const [expand, setExpand] = useState(0.25);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- let objectUrl: string | null = null;
- let cancelled = false;
- void (async () => {
- try {
- const selected = useUIStore.getState().getSelectedClipIds();
- if (selected.length !== 1) throw new Error("Select a single photo clip first");
- const clip = useProjectStore.getState().getClip(selected[0]);
- const mediaId = clip?.mediaId;
- if (!mediaId) throw new Error("Select a photo clip first");
- const item = useProjectStore.getState().getMediaItem(mediaId);
- let blob = item?.blob ?? null;
- if (!blob) blob = await loadMediaBlob(mediaId);
- if (!blob) throw new Error("Could not load the photo");
- if (cancelled) return;
- objectUrl = URL.createObjectURL(blob);
- setImageUrl(objectUrl);
- } catch (e) {
- if (!cancelled) setLoadError(e instanceof Error ? e.message : String(e));
- }
- })();
- return () => {
- cancelled = true;
- if (objectUrl) URL.revokeObjectURL(objectUrl);
- };
- }, []);
-
- const clearSelection = (): void => {
- setBBox(null);
- setPoints([]);
- };
-
- const submit = async (): Promise<void> => {
- setError(null);
- const result = buildObjectRemovalParams({ mode, tool, bbox, points, prompt, expand, expandSides: null });
- if (!result.ok) {
- setError(result.error);
- return;
- }
- setBusy(true);
- try {
- await submitSelectedClipJob({
- kind: "object_removal",
- params: result.params,
- suggestedName: `Object ${mode} result`,
- });
- onClose();
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- setBusy(false);
- }
- };
-
- const needsMask = mode === "erase" || mode === "replace";
-
- return (
- <Dialog isOpen onOpenChange={(open) => !open && onClose()} width={672} purpose="form">
- <Layout
- header={
- <DialogHeader
- title="Object Removal"
- onOpenChange={(open) => !open && onClose()}
- />
- }
- content={
- <LayoutContent className="space-y-4">
- <ToolcraftSegmentedControl<ObjectMode>
- ariaLabel="Object removal mode"
- value={mode}
- onChange={(value) => {
- setMode(value);
- setError(null);
- }}
- options={[
- { value: "erase", label: "Erase" },
- { value: "replace", label: "Replace" },
- { value: "outpaint", label: "Expand" },
- ]}
- />
-
- <Text type="supporting" color="secondary" display="block" className="text-[11px]">
- {mode === "erase"
- ? "Removes the object and fills the background in automatically - no prompt needed."
- : mode === "replace"
- ? "Generates new content inside the box from the description you type below."
- : "Extends the photo outward, generating new surroundings."}
- </Text>
-
- {loadError ? (
- <Text type="supporting" display="block" className="py-8 text-center text-red-300">
- {loadError}
- </Text>
- ) : !imageUrl ? (
- <Text type="supporting" color="secondary" display="block" className="py-8 text-center">
- Loading photo...
- </Text>
- ) : (
- <div className="space-y-3">
- {needsMask ? (
- <>
- <div className="flex items-center justify-between">
- <ToolcraftSegmentedControl<MaskTool>
- ariaLabel="Mask tool"
- className="w-48"
- value={tool}
- onChange={(value) => {
- setTool(value);
- clearSelection();
- }}
- options={[
- { value: "box", label: "Box" },
- { value: "points", label: "Points" },
- ]}
- />
- <Button label="Clear" variant="ghost" size="sm" onClick={clearSelection} />
- </div>
- <SelectionCanvas
- imageUrl={imageUrl}
- tool={tool}
- bbox={bbox}
- points={points}
- onBBoxChange={setBBox}
- onPointsChange={setPoints}
- />
- <Text type="supporting" color="secondary" display="block" className="text-[11px]">
- {tool === "box"
- ? "Drag a box around the object to remove."
- : "Tap each part of the object to remove."}
- </Text>
- </>
- ) : (
- <>
- <div className="flex justify-center">
- <div
- className="relative rounded border border-dashed border-primary/40 bg-primary/5"
- style={{ padding: `${expand * 100}%` }}
- >
- <img src={imageUrl} alt="Selected photo" className="block max-h-[46vh] max-w-full rounded" />
- </div>
- </div>
- <div className="space-y-1">
- <div className="flex justify-between">
- <Text type="supporting" color="secondary" className="text-[11px]">
- Expand each side
- </Text>
- <Text type="supporting" color="secondary" className="text-[11px]">
- {Math.round(expand * 100)}%
- </Text>
- </div>
- <ToolcraftSliderControl
- label="Expand each side"
- isLabelHidden
- value={expand}
- onChange={(nextExpand: number) => setExpand(nextExpand)}
- min={0.05}
- max={0.5}
- step={0.05}
- valueDisplay="none"
- />
- </div>
- </>
- )}
-
- {(mode === "replace" || mode === "outpaint") && (
- <ToolcraftTextInputControl
- label={mode === "replace" ? "Replacement prompt" : "Expansion prompt"}
- isLabelHidden
- value={prompt}
- onChange={setPrompt}
- placeholder={
- mode === "replace"
- ? "Describe what to put there"
- : "Optional: describe the extended scene"
- }
- width="100%"
- />
- )}
-
- {error && (
- <Card variant="muted" padding={2} className="border border-red-500/30 bg-red-500/10">
- <Text type="supporting" className="text-red-200">
- {error}
- </Text>
- </Card>
- )}
- </div>
- )}
- </LayoutContent>
- }
- footer={
- <LayoutFooter hasDivider>
- <div className="flex justify-end gap-2">
- <Button
- label="Cancel"
- variant="ghost"
- onClick={onClose}
- isDisabled={busy}
- />
- <Button
- label={busy ? "Submitting..." : "Apply"}
- variant="primary"
- onClick={() => void submit()}
- isDisabled={busy || !imageUrl || Boolean(loadError)}
- />
- </div>
- </LayoutFooter>
- }
- />
- </Dialog>
- );
-}
diff --git a/apps/web/src/components/editor/ai-panel/photo-tools/SelectionCanvas.tsx b/apps/web/src/components/editor/ai-panel/photo-tools/SelectionCanvas.tsx
deleted file mode 100644
index 17194fcb..00000000
--- a/apps/web/src/components/editor/ai-panel/photo-tools/SelectionCanvas.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import type { JSX } from "react";
-import { useRef, useState } from "react";
-import type { BBox, MaskTool, NormPoint } from "./object-removal-params";
-
-interface SelectionCanvasProps {
- imageUrl: string;
- tool: MaskTool;
- bbox: BBox | null;
- points: NormPoint[];
- onBBoxChange: (bbox: BBox | null) => void;
- onPointsChange: (points: NormPoint[]) => void;
-}
-
-interface NormXY {
- x: number;
- y: number;
-}
-
-export function SelectionCanvas({
- imageUrl,
- tool,
- bbox,
- points,
- onBBoxChange,
- onPointsChange,
-}: SelectionCanvasProps): JSX.Element {
- const ref = useRef<HTMLDivElement>(null);
- const [dragStart, setDragStart] = useState<NormXY | null>(null);
- const [dragNow, setDragNow] = useState<NormXY | null>(null);
-
- const normalize = (clientX: number, clientY: number): NormXY => {
- const el = ref.current;
- if (!el) return { x: 0, y: 0 };
- const rect = el.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) return { x: 0, y: 0 };
- return {
- x: Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)),
- y: Math.max(0, Math.min(1, (clientY - rect.top) / rect.height)),
- };
- };
-
- const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>): void => {
- if (tool !== "box") return;
- const p = normalize(e.clientX, e.clientY);
- setDragStart(p);
- setDragNow(p);
- };
-
- const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>): void => {
- if (tool !== "box" || !dragStart) return;
- setDragNow(normalize(e.clientX, e.clientY));
- };
-
- const finishDrag = (): void => {
- if (tool === "box" && dragStart && dragNow) {
- const x = Math.min(dragStart.x, dragNow.x);
- const y = Math.min(dragStart.y, dragNow.y);
- const w = Math.abs(dragNow.x - dragStart.x);
- const h = Math.abs(dragNow.y - dragStart.y);
- if (w > 0.01 && h > 0.01) onBBoxChange({ x, y, w, h });
- }
- setDragStart(null);
- setDragNow(null);
- };
-
- const handleClick = (e: React.MouseEvent<HTMLDivElement>): void => {
- if (tool !== "points") return;
- onPointsChange([...points, normalize(e.clientX, e.clientY)]);
- };
-
- const liveBox: BBox | null =
- dragStart && dragNow
- ? {
- x: Math.min(dragStart.x, dragNow.x),
- y: Math.min(dragStart.y, dragNow.y),
- w: Math.abs(dragNow.x - dragStart.x),
- h: Math.abs(dragNow.y - dragStart.y),
- }
- : bbox;
-
- return (
- <div className="flex justify-center">
- <div
- ref={ref}
- className="relative inline-block select-none"
- style={{ cursor: tool === "box" ? "crosshair" : "copy" }}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={finishDrag}
- onMouseLeave={finishDrag}
- onClick={handleClick}
- >
- <img
- src={imageUrl}
- alt="Selected photo"
- draggable={false}
- className="block max-h-[58vh] max-w-full rounded"
- />
- {tool === "box" && liveBox && (
- <div
- className="pointer-events-none absolute border-2 border-primary bg-primary/15"
- style={{
- left: `${liveBox.x * 100}%`,
- top: `${liveBox.y * 100}%`,
- width: `${liveBox.w * 100}%`,
- height: `${liveBox.h * 100}%`,
- }}
- />
- )}
- {tool === "points" &&
- points.map((p, i) => (
- <div
- key={`${p.x.toFixed(4)}-${p.y.toFixed(4)}-${i}`}
- className="pointer-events-none absolute h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-primary shadow"
- style={{ left: `${p.x * 100}%`, top: `${p.y * 100}%` }}
- />
- ))}
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.test.ts b/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.test.ts
deleted file mode 100644
index f7b03c5b..00000000
--- a/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildObjectRemovalParams, type ObjectRemovalDraft } from "./object-removal-params";
-
-const base: ObjectRemovalDraft = {
- mode: "erase",
- tool: "box",
- bbox: null,
- points: [],
- prompt: "",
- expand: 0.25,
- expandSides: null,
-};
-
-describe("buildObjectRemovalParams", () => {
- it("erase with a box → bbox params", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "erase", bbox: { x: 0.1, y: 0.2, w: 0.3, h: 0.4 } });
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.params).toEqual({ mode: "erase", maskMode: "bbox", bbox: [0.1, 0.2, 0.3, 0.4] });
- });
-
- it("erase with box tool but no box drawn → error", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "erase", bbox: null });
- expect(r.ok).toBe(false);
- });
-
- it("erase with points → points params", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "erase", tool: "points", points: [{ x: 0.5, y: 0.5 }] });
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.params).toEqual({ mode: "erase", maskMode: "points", points: [{ x: 0.5, y: 0.5 }] });
- });
-
- it("points tool with no points → error", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "erase", tool: "points", points: [] });
- expect(r.ok).toBe(false);
- });
-
- it("replace requires a prompt", () => {
- const withBox: ObjectRemovalDraft = { ...base, mode: "replace", bbox: { x: 0, y: 0, w: 0.5, h: 0.5 } };
- expect(buildObjectRemovalParams(withBox).ok).toBe(false);
- const r = buildObjectRemovalParams({ ...withBox, prompt: "a red car" });
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.params).toMatchObject({ mode: "replace", maskMode: "bbox", prompt: "a red car" });
- });
-
- it("outpaint uses expand and optional prompt; no mask", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "outpaint", expand: 0.3 });
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.params).toEqual({ mode: "outpaint", expand: 0.3 });
- const r2 = buildObjectRemovalParams({ ...base, mode: "outpaint", expand: 0.3, prompt: " beach " });
- if (r2.ok) expect(r2.params).toEqual({ mode: "outpaint", expand: 0.3, prompt: "beach" });
- });
-
- it("outpaint with zero expand → error", () => {
- expect(buildObjectRemovalParams({ ...base, mode: "outpaint", expand: 0 }).ok).toBe(false);
- });
-
- it("outpaint with per-side expand → expandLeft/Right/Top/Bottom", () => {
- const r = buildObjectRemovalParams({
- ...base,
- mode: "outpaint",
- expand: 0,
- expandSides: { left: 0.2, right: 0, top: 0.1, bottom: 0 },
- });
- expect(r.ok).toBe(true);
- if (r.ok) {
- expect(r.params).toEqual({ mode: "outpaint", expandLeft: 0.2, expandRight: 0, expandTop: 0.1, expandBottom: 0 });
- }
- });
-
- it("clamps bbox values into 0–1", () => {
- const r = buildObjectRemovalParams({ ...base, mode: "erase", bbox: { x: -0.1, y: 1.5, w: 0.3, h: 0.4 } });
- expect(r.ok).toBe(true);
- if (r.ok) expect(r.params.bbox).toEqual([0, 1, 0.3, 0.4]);
- });
-});
diff --git a/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.ts b/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.ts
deleted file mode 100644
index 8bbcd250..00000000
--- a/apps/web/src/components/editor/ai-panel/photo-tools/object-removal-params.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-export type ObjectMode = "erase" | "replace" | "outpaint";
-export type MaskTool = "box" | "points";
-
-export interface BBox {
- x: number;
- y: number;
- w: number;
- h: number;
-}
-
-export interface NormPoint {
- x: number;
- y: number;
-}
-
-export interface ExpandSides {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-
-export interface ObjectRemovalDraft {
- mode: ObjectMode;
- tool: MaskTool;
- bbox: BBox | null;
- points: NormPoint[];
- prompt: string;
- expand: number;
- expandSides?: ExpandSides | null;
-}
-
-export type BuildResult =
- | { ok: true; params: Record<string, unknown> }
- | { ok: false; error: string };
-
-function clamp01(value: number): number {
- if (!Number.isFinite(value)) return 0;
- return Math.max(0, Math.min(1, value));
-}
-
-export function buildObjectRemovalParams(draft: ObjectRemovalDraft): BuildResult {
- if (draft.mode === "outpaint") {
- const params: Record<string, unknown> = { mode: "outpaint" };
- if (draft.expandSides) {
- params.expandLeft = clamp01(draft.expandSides.left);
- params.expandRight = clamp01(draft.expandSides.right);
- params.expandTop = clamp01(draft.expandSides.top);
- params.expandBottom = clamp01(draft.expandSides.bottom);
- const total =
- (params.expandLeft as number) +
- (params.expandRight as number) +
- (params.expandTop as number) +
- (params.expandBottom as number);
- if (total <= 0) return { ok: false, error: "Set how much to expand" };
- } else {
- const expand = clamp01(draft.expand);
- if (expand <= 0) return { ok: false, error: "Set how much to expand" };
- params.expand = expand;
- }
- if (draft.prompt.trim()) params.prompt = draft.prompt.trim();
- return { ok: true, params };
- }
-
- const maskMode = draft.tool === "box" ? "bbox" : "points";
- const params: Record<string, unknown> = { mode: draft.mode, maskMode };
-
- if (draft.tool === "box") {
- if (!draft.bbox || draft.bbox.w <= 0 || draft.bbox.h <= 0) {
- return { ok: false, error: "Draw a box around the object" };
- }
- params.bbox = [
- clamp01(draft.bbox.x),
- clamp01(draft.bbox.y),
- clamp01(draft.bbox.w),
- clamp01(draft.bbox.h),
- ];
- } else {
- if (draft.points.length === 0) {
- return { ok: false, error: "Tap the object to mark it" };
- }
- params.points = draft.points.map((p) => ({ x: clamp01(p.x), y: clamp01(p.y) }));
- }
-
- if (draft.mode === "replace") {
- if (!draft.prompt.trim()) {
- return { ok: false, error: "Describe what to put there" };
- }
- params.prompt = draft.prompt.trim();
- }
-
- return { ok: true, params };
-}
diff --git a/apps/web/src/components/editor/ai-panel/tracking/ObjectTrackingEditor.tsx b/apps/web/src/components/editor/ai-panel/tracking/ObjectTrackingEditor.tsx
deleted file mode 100644
index c6480864..00000000
--- a/apps/web/src/components/editor/ai-panel/tracking/ObjectTrackingEditor.tsx
+++ /dev/null
@@ -1,197 +0,0 @@
-import type { JSX } from "react";
-import { useEffect, useState } from "react";
-import { ToolcraftButton as Button } from "@openreel/ui";
-import { ToolcraftCard as Card } from "@openreel/ui";
-import { ToolcraftDialog as Dialog, ToolcraftDialogHeader as DialogHeader } from "@openreel/ui";
-import { ToolcraftEmptyState as EmptyState } from "@openreel/ui";
-import { ToolcraftLayout as Layout, ToolcraftLayoutContent as LayoutContent, ToolcraftLayoutFooter as LayoutFooter } from "@openreel/ui";
-import { ToolcraftSpinner as Spinner } from "@openreel/ui";
-import { ToolcraftText as Text } from "@openreel/ui";
-import { useProjectStore } from "../../../../stores/project-store";
-import { useUIStore } from "../../../../stores/ui-store";
-import { loadMediaBlob } from "../../../../services/media-storage";
-import { submitSelectedClipJob } from "../../../../services/gpu-clip-submit";
-import { SelectionCanvas } from "../photo-tools/SelectionCanvas";
-import type { BBox } from "../photo-tools/object-removal-params";
-
-function captureFrame(blob: Blob, time: number): Promise<string> {
- return new Promise((resolve, reject) => {
- const url = URL.createObjectURL(blob);
- const video = document.createElement("video");
- video.muted = true;
- video.preload = "auto";
- video.src = url;
- const cleanup = (): void => URL.revokeObjectURL(url);
-
- video.addEventListener("error", () => {
- cleanup();
- reject(new Error("Could not decode this video in the browser"));
- });
-
- video.addEventListener(
- "loadeddata",
- () => {
- const duration = Number.isFinite(video.duration) ? video.duration : 0;
- const seekTo = Math.min(Math.max(0, time), Math.max(0, duration - 0.05));
- video.addEventListener(
- "seeked",
- () => {
- try {
- const canvas = document.createElement("canvas");
- canvas.width = video.videoWidth;
- canvas.height = video.videoHeight;
- const ctx = canvas.getContext("2d");
- if (!ctx || canvas.width === 0) {
- cleanup();
- reject(new Error("Could not read a video frame"));
- return;
- }
- ctx.drawImage(video, 0, 0);
- const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
- cleanup();
- resolve(dataUrl);
- } catch (e) {
- cleanup();
- reject(e instanceof Error ? e : new Error("Frame capture failed"));
- }
- },
- { once: true },
- );
- video.currentTime = seekTo;
- },
- { once: true },
- );
- });
-}
-
-interface ObjectTrackingEditorProps {
- onClose: () => void;
-}
-
-export function ObjectTrackingEditor({ onClose }: ObjectTrackingEditorProps): JSX.Element {
- const [imageUrl, setImageUrl] = useState<string | null>(null);
- const [loadError, setLoadError] = useState<string | null>(null);
- const [bbox, setBBox] = useState<BBox | null>(null);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- let cancelled = false;
- void (async () => {
- try {
- const selected = useUIStore.getState().getSelectedClipIds();
- if (selected.length !== 1) throw new Error("Select a single video clip first");
- const clip = useProjectStore.getState().getClip(selected[0]);
- const mediaId = clip?.mediaId;
- if (!mediaId) throw new Error("Select a video clip first");
- const item = useProjectStore.getState().getMediaItem(mediaId);
- let blob = item?.blob ?? null;
- if (!blob) blob = await loadMediaBlob(mediaId);
- if (!blob) throw new Error("Could not load the video");
- const url = await captureFrame(blob, clip?.inPoint ?? 0);
- if (!cancelled) setImageUrl(url);
- } catch (e) {
- if (!cancelled) setLoadError(e instanceof Error ? e.message : String(e));
- }
- })();
- return () => {
- cancelled = true;
- };
- }, []);
-
- const submit = async (): Promise<void> => {
- setError(null);
- if (!bbox || bbox.w <= 0 || bbox.h <= 0) {
- setError("Draw a box around the object to track");
- return;
- }
- setBusy(true);
- try {
- await submitSelectedClipJob({
- kind: "object_tracking",
- params: { initialBox: { x: bbox.x, y: bbox.y, width: bbox.w, height: bbox.h } },
- suggestedName: "Object tracking",
- });
- onClose();
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- setBusy(false);
- }
- };
-
- return (
- <Dialog
- isOpen
- onOpenChange={(open) => !open && onClose()}
- width={672}
- purpose="form"
- >
- <Layout
- header={
- <DialogHeader
- title="Object Tracking"
- subtitle="Draw a box around the object to track across the clip."
- onOpenChange={(open) => !open && onClose()}
- />
- }
- content={
- <LayoutContent>
- {loadError ? (
- <Card variant="red" padding={4}>
- <Text type="supporting" className="text-red-300">
- {loadError}
- </Text>
- </Card>
- ) : !imageUrl ? (
- <EmptyState
- title="Loading frame..."
- icon={<Spinner size="md" />}
- isCompact
- />
- ) : (
- <div className="space-y-3">
- <SelectionCanvas
- imageUrl={imageUrl}
- tool="box"
- bbox={bbox}
- points={[]}
- onBBoxChange={setBBox}
- onPointsChange={() => {}}
- />
- <Text type="supporting" color="secondary" display="block" className="text-[11px]">
- Afterward, attach text or graphics to it in the Motion
- Tracking panel.
- </Text>
- {error && (
- <Card variant="red" padding={2}>
- <Text type="supporting" className="text-red-200">
- {error}
- </Text>
- </Card>
- )}
- </div>
- )}
- </LayoutContent>
- }
- footer={
- <LayoutFooter hasDivider>
- <div className="flex justify-end gap-2">
- <Button
- label="Cancel"
- variant="ghost"
- onClick={onClose}
- isDisabled={busy}
- />
- <Button
- label={busy ? "Submitting..." : "Track"}
- variant="primary"
- onClick={() => void submit()}
- isDisabled={busy || !!loadError || !imageUrl}
- />
- </div>
- </LayoutFooter>
- }
- />
- </Dialog>
- );
-}
diff --git a/apps/web/src/components/editor/chat/ChatErrorCard.test.ts b/apps/web/src/components/editor/chat/ChatErrorCard.test.ts
new file mode 100644
index 00000000..7efabc7f
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ChatErrorCard.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { formatChatError } from "./ChatErrorCard";
+
+describe("formatChatError", () => {
+ it("extracts a useful provider message from a raw JSON error", () => {
+ expect(
+ formatChatError(
+ 'openai-compatible 401: {"error":{"message":"The API key is invalid"}}',
+ ),
+ ).toMatchObject({
+ title: "Authentication failed",
+ message: "The API key is invalid",
+ action: "api-keys",
+ });
+ });
+
+ it("turns network and CORS failures into endpoint guidance", () => {
+ expect(
+ formatChatError(
+ "Could not reach the compatible endpoint. Check browser CORS settings.",
+ ),
+ ).toMatchObject({
+ title: "Couldn’t reach the endpoint",
+ action: "general",
+ });
+ });
+
+ it("offers a new chat when the context window is exhausted", () => {
+ expect(formatChatError("maximum context length exceeded")).toMatchObject({
+ title: "Conversation is too long",
+ action: "new-chat",
+ });
+ });
+
+ it("keeps an unknown error readable", () => {
+ expect(formatChatError("provider unavailable")).toEqual({
+ title: "AI request failed",
+ message: "provider unavailable",
+ action: null,
+ details: undefined,
+ });
+ });
+});
diff --git a/apps/web/src/components/editor/chat/ChatErrorCard.tsx b/apps/web/src/components/editor/chat/ChatErrorCard.tsx
new file mode 100644
index 00000000..c4ea9a06
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ChatErrorCard.tsx
@@ -0,0 +1,205 @@
+import type { JSX } from "react";
+import { ToolcraftButton as Button } from "@openreel/ui";
+import { ToolcraftIconButton as IconButton } from "@openreel/ui";
+import { CircleAlert, X } from "@/icons/lucide-compat";
+
+export type ChatErrorAction = "general" | "api-keys" | "new-chat" | null;
+
+export interface ChatErrorPresentation {
+ readonly title: string;
+ readonly message: string;
+ readonly action: ChatErrorAction;
+ readonly actionLabel?: string;
+ readonly details?: string;
+}
+
+function messageFromPayload(value: unknown): string | null {
+ if (typeof value === "string") return value.trim() || null;
+ if (typeof value !== "object" || value === null) return null;
+ const payload = value as Record<string, unknown>;
+ return (
+ messageFromPayload(payload.message) ??
+ messageFromPayload(payload.detail) ??
+ messageFromPayload(payload.error)
+ );
+}
+
+function extractUpstreamMessage(raw: string): string | null {
+ const jsonStart = raw.indexOf("{");
+ if (jsonStart < 0) return null;
+ try {
+ return messageFromPayload(JSON.parse(raw.slice(jsonStart)));
+ } catch {
+ return null;
+ }
+}
+
+export function formatChatError(rawError: string): ChatErrorPresentation {
+ const raw = rawError.trim() || "The AI request failed.";
+ const upstream = extractUpstreamMessage(raw);
+ const status = Number(raw.match(/\b([45]\d{2})\b/)?.[1] ?? 0);
+ const searchable = `${raw} ${upstream ?? ""}`.toLowerCase();
+ const details = upstream && upstream !== raw ? raw : undefined;
+
+ if (
+ status === 401 ||
+ status === 403 ||
+ /unauthori[sz]ed|forbidden|invalid api key|authentication|incorrect api key/.test(
+ searchable,
+ )
+ ) {
+ return {
+ title: "Authentication failed",
+ message:
+ upstream ??
+ "The endpoint rejected the API key. Check the saved key and try again.",
+ action: "api-keys",
+ actionLabel: "Check API key",
+ details,
+ };
+ }
+
+ if (status === 429 || /rate limit|too many requests|quota/.test(searchable)) {
+ return {
+ title: "Rate limit reached",
+ message:
+ upstream ??
+ "The endpoint is receiving too many requests. Wait a moment and try again.",
+ action: null,
+ details,
+ };
+ }
+
+ if (
+ /cors|failed to fetch|network error|could not reach|connection refused|load failed/.test(
+ searchable,
+ )
+ ) {
+ return {
+ title: "Couldn’t reach the endpoint",
+ message:
+ "Check the host URL and confirm the endpoint is online. In a browser, the host must also allow CORS requests from OpenReel.",
+ action: "general",
+ actionLabel: "Check endpoint",
+ details: raw,
+ };
+ }
+
+ if (
+ /context length|context window|maximum context|prompt is too long|token limit/.test(
+ searchable,
+ )
+ ) {
+ return {
+ title: "Conversation is too long",
+ message:
+ upstream ??
+ "This model cannot fit the full conversation. Start a new chat and continue there.",
+ action: "new-chat",
+ actionLabel: "Start new chat",
+ details,
+ };
+ }
+
+ if (status === 404 || /model.+not found|unknown model|does not exist/.test(searchable)) {
+ return {
+ title: "Model or route not found",
+ message:
+ upstream ??
+ "Check that the base URL and model ID match what the endpoint exposes.",
+ action: "general",
+ actionLabel: "Check endpoint",
+ details,
+ };
+ }
+
+ if (
+ /api format|model id|base url|compatible api|endpoint url|secure storage|unlock/.test(
+ searchable,
+ )
+ ) {
+ const keyIssue = /secure storage|unlock|api key/.test(searchable);
+ return {
+ title: "AI setup needed",
+ message: upstream ?? raw,
+ action: keyIssue ? "api-keys" : "general",
+ actionLabel: keyIssue ? "Open API keys" : "Open AI settings",
+ details,
+ };
+ }
+
+ return {
+ title: "AI request failed",
+ message: upstream ?? raw,
+ action: null,
+ details,
+ };
+}
+
+export function ChatErrorCard({
+ error,
+ onDismiss,
+ onOpenSettings,
+ onNewChat,
+}: {
+ readonly error: string;
+ readonly onDismiss: () => void;
+ readonly onOpenSettings: (tab: "general" | "api-keys") => void;
+ readonly onNewChat: () => void;
+}): JSX.Element {
+ const presentation = formatChatError(error);
+
+ return (
+ <div
+ role="alert"
+ className="rounded-xl border border-status-error/35 bg-bg-1 p-3 shadow-sm"
+ >
+ <div className="flex items-start gap-2.5">
+ <div className="mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-status-error/10 text-status-error">
+ <CircleAlert size={15} aria-hidden />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="text-[12px] font-semibold text-fg">
+ {presentation.title}
+ </div>
+ <div className="mt-1 whitespace-pre-wrap break-words text-[11px] leading-relaxed text-fg-2">
+ {presentation.message}
+ </div>
+ </div>
+ <IconButton
+ label="Dismiss error"
+ icon={<X size={13} aria-hidden />}
+ size="sm"
+ variant="ghost"
+ onClick={onDismiss}
+ className="-mr-1 -mt-1 shrink-0 text-fg-muted transition-colors hover:text-fg"
+ />
+ </div>
+
+ {presentation.details && (
+ <details className="group mt-2 rounded-lg bg-bg-2/70 px-2.5 py-2">
+ <summary className="cursor-pointer select-none text-[10px] font-medium text-fg-muted hover:text-fg-2">
+ Technical details
+ </summary>
+ <pre className="mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words font-mono text-[10px] leading-relaxed text-fg-muted">
+ {presentation.details}
+ </pre>
+ </details>
+ )}
+
+ {presentation.action && (
+ <Button
+ label={presentation.actionLabel ?? "Fix issue"}
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ const action = presentation.action;
+ if (action === "new-chat") onNewChat();
+ else if (action) onOpenSettings(action);
+ }}
+ className="mt-2.5 w-full"
+ />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/chat/ChatHistoryPanel.test.tsx b/apps/web/src/components/editor/chat/ChatHistoryPanel.test.tsx
new file mode 100644
index 00000000..81210242
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ChatHistoryPanel.test.tsx
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { useChatHistoryStore } from "../../../stores/chat-history-store";
+import { useChatStore } from "../../../stores/chat-store";
+import { ChatHistoryPanel } from "./ChatHistoryPanel";
+
+describe("ChatHistoryPanel", () => {
+ beforeEach(() => {
+ useChatStore.getState().reset();
+ useChatHistoryStore.getState().clearHistory();
+ useChatStore.setState({ projectId: "project-a" });
+ useChatHistoryStore.getState().saveConversation({
+ id: "chat-1",
+ projectId: "project-a",
+ title: "Fix the opening title",
+ createdAt: 1,
+ updatedAt: 2,
+ messages: [
+ {
+ id: "message-1",
+ role: "user",
+ text: "Fix the opening title",
+ toolCalls: [],
+ },
+ ],
+ usage: { inputTokens: 12, outputTokens: 4 },
+ });
+ });
+
+ it("shows project conversations and opens one", () => {
+ const onClose = vi.fn();
+ render(<ChatHistoryPanel projectId="project-a" onClose={onClose} />);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /^Fix the opening title/ }),
+ );
+
+ expect(useChatStore.getState().currentConversationId).toBe("chat-1");
+ expect(useChatStore.getState().messages[0].text).toBe(
+ "Fix the opening title",
+ );
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("starts a new chat from history", () => {
+ useChatStore.setState({
+ currentConversationId: "chat-1",
+ conversationStartedAt: 1,
+ messages: useChatHistoryStore.getState().conversations[0].messages,
+ });
+ const onClose = vi.fn();
+ render(<ChatHistoryPanel projectId="project-a" onClose={onClose} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));
+
+ expect(useChatStore.getState().messages).toEqual([]);
+ expect(useChatStore.getState().currentConversationId).toBeNull();
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/components/editor/chat/ChatHistoryPanel.tsx b/apps/web/src/components/editor/chat/ChatHistoryPanel.tsx
new file mode 100644
index 00000000..364cb506
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ChatHistoryPanel.tsx
@@ -0,0 +1,131 @@
+import type { JSX, MouseEvent } from "react";
+import { ToolcraftButton as Button } from "@openreel/ui";
+import { ToolcraftIconButton as IconButton } from "@openreel/ui";
+import { MessageSquareText, Plus, Trash2 } from "@/icons/lucide-compat";
+import { useChatHistoryStore } from "../../../stores/chat-history-store";
+import { useChatStore } from "../../../stores/chat-store";
+
+function formatUpdatedAt(timestamp: number): string {
+ const date = new Date(timestamp);
+ const now = new Date();
+ const sameDay = date.toDateString() === now.toDateString();
+ return new Intl.DateTimeFormat(undefined, {
+ ...(sameDay
+ ? { hour: "numeric", minute: "2-digit" }
+ : { month: "short", day: "numeric" }),
+ }).format(date);
+}
+
+export function ChatHistoryPanel({
+ projectId,
+ onClose,
+}: {
+ readonly projectId: string | null;
+ readonly onClose: () => void;
+}): JSX.Element {
+ const conversations = useChatHistoryStore((state) => state.conversations);
+ const activeConversationId = useChatStore(
+ (state) => state.currentConversationId,
+ );
+ const openConversation = useChatStore((state) => state.openConversation);
+ const deleteConversation = useChatStore((state) => state.deleteConversation);
+ const newChat = useChatStore((state) => state.newChat);
+ const visibleConversations = conversations.filter(
+ (conversation) => !projectId || conversation.projectId === projectId,
+ );
+
+ const removeConversation = (
+ event: MouseEvent<HTMLButtonElement>,
+ conversationId: string,
+ ): void => {
+ event.stopPropagation();
+ deleteConversation(conversationId);
+ };
+
+ return (
+ <div className="absolute inset-x-2 top-11 z-30 overflow-hidden rounded-xl border border-border bg-bg-1 shadow-xl">
+ <div className="flex items-center justify-between border-b border-border px-3 py-2.5">
+ <div>
+ <div className="text-[12px] font-semibold text-fg">Conversations</div>
+ <div className="mt-0.5 text-[10px] text-fg-muted">
+ Saved on this device for this project
+ </div>
+ </div>
+ <Button
+ label="New chat"
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ newChat();
+ onClose();
+ }}
+ >
+ <Plus size={12} aria-hidden />
+ </Button>
+ </div>
+
+ <div className="max-h-72 overflow-y-auto p-1.5">
+ {visibleConversations.length === 0 ? (
+ <div className="flex flex-col items-center px-4 py-8 text-center">
+ <div className="grid h-8 w-8 place-items-center rounded-lg bg-bg-2 text-fg-muted">
+ <MessageSquareText size={15} aria-hidden />
+ </div>
+ <div className="mt-2 text-[11px] font-medium text-fg-2">
+ No saved conversations yet
+ </div>
+ <div className="mt-1 max-w-48 text-[10px] leading-relaxed text-fg-muted">
+ Completed chats will appear here automatically.
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-1">
+ {visibleConversations.map((conversation) => {
+ const active = conversation.id === activeConversationId;
+ return (
+ <div
+ key={conversation.id}
+ className={`group flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left transition-colors ${
+ active
+ ? "bg-accent-soft text-fg"
+ : "text-fg-2 hover:bg-hover hover:text-fg"
+ }`}
+ >
+ <button
+ type="button"
+ onClick={() => {
+ openConversation(conversation.id);
+ onClose();
+ }}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ >
+ <MessageSquareText
+ size={13}
+ className={active ? "shrink-0 text-accent" : "shrink-0 text-fg-muted"}
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[11px] font-medium">
+ {conversation.title}
+ </span>
+ <span className="mt-0.5 block text-[9px] text-fg-muted">
+ {conversation.messages.filter((message) => message.role === "user").length} requests · {formatUpdatedAt(conversation.updatedAt)}
+ </span>
+ </span>
+ </button>
+ <IconButton
+ label={`Delete ${conversation.title}`}
+ icon={<Trash2 size={12} aria-hidden />}
+ size="sm"
+ variant="ghost"
+ onClick={(event) => removeConversation(event, conversation.id)}
+ className="shrink-0 text-fg-muted opacity-0 transition-opacity hover:text-status-error focus:opacity-100 group-hover:opacity-100"
+ />
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/chat/ChatMessage.test.tsx b/apps/web/src/components/editor/chat/ChatMessage.test.tsx
new file mode 100644
index 00000000..35a84dc4
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ChatMessage.test.tsx
@@ -0,0 +1,81 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ChatMessage as ChatMessageData } from "../../../stores/chat-store";
+import { ChatMessage } from "./ChatMessage";
+
+const assistantMessage = (text: string): ChatMessageData => ({
+ id: "assistant-1",
+ role: "assistant",
+ text,
+ toolCalls: [],
+});
+
+describe("ChatMessage", () => {
+ const writeText = vi.fn(async () => undefined);
+
+ beforeEach(() => {
+ writeText.mockClear();
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+ });
+
+ it("renders assistant responses as safe GitHub-flavored Markdown", () => {
+ const { container } = render(
+ <ChatMessage
+ message={assistantMessage(
+ [
+ "## Changes",
+ "- Added **title text**",
+ "- Used `fade-in`",
+ "",
+ "| Clip | Result |",
+ "| --- | --- |",
+ "| Intro | Updated |",
+ "",
+ "[Open docs](https://example.com/docs)",
+ "",
+ "<script>window.bad = true</script>",
+ ].join("\n"),
+ )}
+ />,
+ );
+
+ expect(screen.getByRole("heading", { name: "Changes" })).toBeInTheDocument();
+ expect(screen.getByText("title text").tagName).toBe("STRONG");
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ expect(screen.getByText("Updated")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Open docs" })).toHaveAttribute("target", "_blank");
+ expect(screen.getByRole("link", { name: "Open docs" })).toHaveAttribute(
+ "rel",
+ "noreferrer noopener",
+ );
+ expect(container.querySelector("script")).toBeNull();
+ });
+
+ it("copies fenced code blocks", async () => {
+ render(<ChatMessage message={assistantMessage("```json\n{\"ok\":true}\n```")} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
+
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith('{"ok":true}'));
+ });
+
+ it("shows a pending state while waiting for the first response content", () => {
+ render(<ChatMessage message={assistantMessage("")} pending />);
+ expect(screen.getByRole("status")).toHaveTextContent("Thinking…");
+ });
+
+ it("renders application notices separately from model Markdown", () => {
+ render(
+ <ChatMessage
+ message={{
+ ...assistantMessage("Done."),
+ notice: "The model stopped at its response limit.",
+ }}
+ />,
+ );
+ expect(screen.getByText("The model stopped at its response limit.")).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/editor/chat/ChatMessage.tsx b/apps/web/src/components/editor/chat/ChatMessage.tsx
index 30502b23..80bb9cd0 100644
--- a/apps/web/src/components/editor/chat/ChatMessage.tsx
+++ b/apps/web/src/components/editor/chat/ChatMessage.tsx
@@ -1,12 +1,15 @@
import type { JSX } from "react";
import { Bot, User } from "@/icons/lucide-compat";
import type { ChatMessage as ChatMessageData } from "../../../stores/chat-store";
+import { MarkdownMessage } from "./MarkdownMessage";
import { ToolCallCard } from "./ToolCallCard";
export function ChatMessage({
message,
+ pending = false,
}: {
message: ChatMessageData;
+ pending?: boolean;
}): JSX.Element {
const isUser = message.role === "user";
@@ -20,10 +23,18 @@ export function ChatMessage({
{isUser ? <User size={13} /> : <Bot size={13} />}
</div>
<div className="min-w-0 flex-1 space-y-2">
- {message.text && (
+ {message.text && (isUser ? (
<div className="whitespace-pre-wrap break-words text-[13px] leading-relaxed text-fg">
{message.text}
</div>
+ ) : (
+ <MarkdownMessage text={message.text} />
+ ))}
+ {!isUser && pending && !message.text && message.toolCalls.length === 0 && (
+ <div className="flex items-center gap-1.5 py-1 text-[12px] text-fg-muted" role="status">
+ <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-accent" />
+ <span>Thinking…</span>
+ </div>
)}
{message.toolCalls.length > 0 && (
<div className="space-y-1">
@@ -32,6 +43,11 @@ export function ChatMessage({
))}
</div>
)}
+ {!isUser && message.notice && (
+ <div className="rounded-md border border-border bg-bg-2/70 px-2.5 py-2 text-[11px] leading-relaxed text-fg-2">
+ {message.notice}
+ </div>
+ )}
</div>
</div>
);
diff --git a/apps/web/src/components/editor/chat/ChatPanel.tsx b/apps/web/src/components/editor/chat/ChatPanel.tsx
index e11a6a7a..81692a52 100644
--- a/apps/web/src/components/editor/chat/ChatPanel.tsx
+++ b/apps/web/src/components/editor/chat/ChatPanel.tsx
@@ -1,9 +1,9 @@
import type { JSX } from "react";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { ToolcraftButton as Button } from "@openreel/ui";
import { ToolcraftIconButton as IconButton } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
-import { Bot, X, Undo2, Trash2, Sparkles, ShieldCheck, FlaskConical } from "@/icons/lucide-compat";
+import { Bot, X, Undo2, Plus, History, Sparkles, ShieldCheck, FlaskConical } from "@/icons/lucide-compat";
import { useChatStore } from "../../../stores/chat-store";
import { useProjectStore } from "../../../stores/project-store";
import { useSettingsStore } from "../../../stores/settings-store";
@@ -11,6 +11,13 @@ import { ProviderModelPicker } from "./ProviderModelPicker";
import { ChatMessage } from "./ChatMessage";
import { ChatComposer } from "./ChatComposer";
import { InlineConfirmCard } from "./InlineConfirmCard";
+import { ChatErrorCard } from "./ChatErrorCard";
+import { ChatHistoryPanel } from "./ChatHistoryPanel";
+import {
+ hasSecret,
+ isMasterPasswordSet,
+ isSessionUnlocked,
+} from "../../../services/secure-storage";
const SUGGESTIONS: ReadonlyArray<string> = [
"Add a title that says 'Welcome' for the first 3 seconds",
@@ -25,6 +32,55 @@ function EmptyState({
hasOpenProject: boolean;
}): JSX.Element {
const send = useChatStore((s) => s.send);
+ const provider = useSettingsStore((s) => s.defaultLlmProvider);
+ const openSettings = useSettingsStore((s) => s.openSettings);
+ const settingsOpen = useSettingsStore((s) => s.settingsOpen);
+ const configuredServices = useSettingsStore((s) => s.configuredServices);
+ const baseUrl = useSettingsStore((s) => s.llmBaseUrl);
+ const model = useSettingsStore((s) => s.llmModel);
+ const [setup, setSetup] = useState<
+ "loading" | "ready" | "setup" | "locked" | "missing" | "endpoint"
+ >("loading");
+
+ useEffect(() => {
+ let active = true;
+ void (async () => {
+ try {
+ if (!provider || !baseUrl.trim() || !model.trim()) {
+ if (active) setSetup("endpoint");
+ return;
+ }
+ if (!configuredServices.includes(provider)) {
+ if (active) setSetup("ready");
+ return;
+ }
+ if (!(await isMasterPasswordSet())) {
+ if (active) setSetup("setup");
+ return;
+ }
+ if (!isSessionUnlocked()) {
+ if (active) setSetup("locked");
+ return;
+ }
+ if (active) setSetup((await hasSecret(provider)) ? "ready" : "missing");
+ } catch {
+ if (active) setSetup("missing");
+ }
+ })();
+ return () => {
+ active = false;
+ };
+ }, [baseUrl, configuredServices, model, provider, settingsOpen]);
+
+ const setupMessage =
+ setup === "endpoint"
+ ? "Choose an API format, then enter your endpoint URL and model ID."
+ : setup === "setup"
+ ? "Set a master password, then add your provider API key."
+ : setup === "locked"
+ ? "Unlock your encrypted API keys to start the AI editor."
+ : "Add the optional endpoint API key to start editing.";
+
return (
<div className="flex h-full flex-col items-center justify-center px-2 text-center">
<div className="mb-3 grid h-10 w-10 place-items-center rounded-xl bg-accent-soft text-accent">
@@ -36,7 +92,28 @@ function EmptyState({
? "Describe an edit in plain language and the AI will perform it on your timeline."
: "Open or create a project, then describe edits in plain language."}
</Text>
- {hasOpenProject && (
+ {hasOpenProject && setup !== "loading" && setup !== "ready" && (
+ <div className="mt-4 w-full rounded-lg border border-accent/30 bg-accent-soft/50 p-3 text-left">
+ <div className="text-[11px] font-medium text-fg">Connect your model</div>
+ <Text type="supporting" color="secondary" className="mt-1 block text-[10px] leading-relaxed">
+ {setupMessage}
+ </Text>
+ <Button
+ label={
+ setup === "locked"
+ ? "Unlock API keys"
+ : setup === "endpoint"
+ ? "Configure endpoint"
+ : "Set up AI chat"
+ }
+ variant="primary"
+ size="sm"
+ onClick={() => openSettings(setup === "endpoint" ? "general" : "api-keys")}
+ className="mt-2 w-full"
+ />
+ </div>
+ )}
+ {hasOpenProject && setup === "ready" && (
<div className="mt-4 w-full space-y-1.5">
{SUGGESTIONS.map((s) => (
<Button
@@ -66,13 +143,16 @@ export function ChatPanel({
const lastTurnCommitted = useChatStore((s) => s.lastTurnCommitted);
const usage = useChatStore((s) => s.usage);
const undoLastTurn = useChatStore((s) => s.undoLastTurn);
- const reset = useChatStore((s) => s.reset);
+ const newChat = useChatStore((s) => s.newChat);
const clearError = useChatStore((s) => s.clearError);
+ const setProjectContext = useChatStore((s) => s.setProjectContext);
const hasOpenProject = useProjectStore((s) => s.hasOpenProject);
+ const projectId = useProjectStore((s) => (s.hasOpenProject ? s.project.id : null));
const autoConfirm = useSettingsStore((s) => s.agentAutoConfirm);
const setAutoConfirm = useSettingsStore((s) => s.setAgentAutoConfirm);
const dryRun = useSettingsStore((s) => s.agentDryRun);
const setDryRun = useSettingsStore((s) => s.setAgentDryRun);
+ const openSettings = useSettingsStore((s) => s.openSettings);
const totalTokens = usage.inputTokens + usage.outputTokens;
const tokenLabel =
@@ -82,14 +162,19 @@ export function ChatPanel({
const busy = status === "running" || status === "awaiting_confirm";
const scrollRef = useRef<HTMLDivElement>(null);
+ const [historyOpen, setHistoryOpen] = useState(false);
useEffect(() => {
const el = scrollRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [messages, pendingConfirm, error]);
+ useEffect(() => {
+ setProjectContext(projectId);
+ }, [projectId, setProjectContext]);
+
return (
- <div className="flex h-full flex-col bg-bg-1">
+ <div className="relative flex h-full flex-col bg-bg-1">
<header className="flex items-center gap-2 border-b border-border px-3 py-2">
<Bot size={15} className="shrink-0 text-accent" />
<span className="shrink-0 text-[13px] font-medium text-fg">
@@ -141,17 +226,29 @@ export function ChatPanel({
className="grid h-7 w-7 place-items-center rounded-md text-fg-2 transition-colors hover:bg-hover hover:text-fg"
/>
)}
- {messages.length > 0 && (
- <IconButton
- label="Clear conversation"
- icon={<Trash2 size={14} aria-hidden />}
- size="sm"
- variant="ghost"
- onClick={reset}
- isDisabled={busy}
- className="grid h-7 w-7 place-items-center rounded-md text-fg-2 transition-colors hover:bg-hover hover:text-fg disabled:opacity-40"
- />
- )}
+ <IconButton
+ label="Conversation history"
+ icon={<History size={14} aria-hidden />}
+ size="sm"
+ variant={historyOpen ? "secondary" : "ghost"}
+ onClick={() => setHistoryOpen((open) => !open)}
+ isDisabled={busy}
+ aria-pressed={historyOpen}
+ className="grid h-7 w-7 place-items-center rounded-md text-fg-2 transition-colors hover:bg-hover hover:text-fg disabled:opacity-40"
+ />
+ <Button
+ label="New chat"
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ newChat();
+ setHistoryOpen(false);
+ }}
+ isDisabled={busy || messages.length === 0}
+ className="h-7 shrink-0 px-2 text-[10px]"
+ >
+ <Plus size={12} aria-hidden />
+ </Button>
{onClose && (
<IconButton
label="Close"
@@ -165,6 +262,13 @@ export function ChatPanel({
</div>
</header>
+ {historyOpen && (
+ <ChatHistoryPanel
+ projectId={projectId}
+ onClose={() => setHistoryOpen(false)}
+ />
+ )}
+
<div
ref={scrollRef}
className="min-h-0 flex-1 space-y-4 overflow-y-auto p-3"
@@ -172,23 +276,27 @@ export function ChatPanel({
{messages.length === 0 ? (
<EmptyState hasOpenProject={hasOpenProject} />
) : (
- messages.map((m) => <ChatMessage key={m.id} message={m} />)
+ messages.map((m, index) => (
+ <ChatMessage
+ key={m.id}
+ message={m}
+ pending={busy && index === messages.length - 1 && m.role === "assistant"}
+ />
+ ))
)}
{pendingConfirm && <InlineConfirmCard call={pendingConfirm.call} />}
{error && (
- <div className="flex items-start gap-2 rounded-lg border border-status-error/40 bg-status-error/10 p-2.5 text-[12px] text-status-error">
- <span className="flex-1 break-words">{error}</span>
- <IconButton
- label="Clear error"
- icon={<X size={13} aria-hidden />}
- size="sm"
- variant="ghost"
- onClick={clearError}
- className="shrink-0 text-status-error/70 transition-colors hover:text-status-error"
- />
- </div>
+ <ChatErrorCard
+ error={error}
+ onDismiss={clearError}
+ onOpenSettings={openSettings}
+ onNewChat={() => {
+ newChat();
+ setHistoryOpen(false);
+ }}
+ />
)}
</div>
diff --git a/apps/web/src/components/editor/chat/MarkdownMessage.tsx b/apps/web/src/components/editor/chat/MarkdownMessage.tsx
new file mode 100644
index 00000000..ef14e674
--- /dev/null
+++ b/apps/web/src/components/editor/chat/MarkdownMessage.tsx
@@ -0,0 +1,115 @@
+import type { ComponentPropsWithoutRef, JSX, ReactNode } from "react";
+import { isValidElement, useState } from "react";
+import ReactMarkdown, { defaultUrlTransform, type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { Check, Copy } from "@/icons/lucide-compat";
+
+function nodeText(node: ReactNode): string {
+ if (typeof node === "string" || typeof node === "number") return String(node);
+ if (Array.isArray(node)) return node.map(nodeText).join("");
+ if (isValidElement<{ children?: ReactNode }>(node)) return nodeText(node.props.children);
+ return "";
+}
+
+function CodeBlock({ children }: ComponentPropsWithoutRef<"pre">): JSX.Element {
+ const [copied, setCopied] = useState(false);
+ const code = nodeText(children).replace(/\n$/, "");
+
+ const copy = async (): Promise<void> => {
+ try {
+ await navigator.clipboard.writeText(code);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ } catch {
+ // Clipboard access may be unavailable in an embedded or insecure context.
+ }
+ };
+
+ return (
+ <div className="group/code relative my-2 min-w-0">
+ <pre
+ className="max-w-full overflow-x-auto rounded-lg border border-border bg-bg-2 px-3 py-2.5 font-mono text-[11px] leading-relaxed text-fg"
+ >
+ {children}
+ </pre>
+ <button
+ type="button"
+ onClick={() => void copy()}
+ aria-label={copied ? "Copied code" : "Copy code"}
+ className="absolute right-1.5 top-1.5 grid h-6 w-6 place-items-center rounded-md border border-border bg-bg-1/90 text-fg-muted opacity-0 shadow-sm transition hover:text-fg focus:opacity-100 group-hover/code:opacity-100"
+ >
+ {copied ? <Check size={11} /> : <Copy size={11} />}
+ </button>
+ </div>
+ );
+}
+
+const components: Components = {
+ p: ({ children }) => <p className="my-1.5 first:mt-0 last:mb-0">{children}</p>,
+ h1: ({ children }) => <h1 className="mb-1.5 mt-3 text-[15px] font-semibold text-fg">{children}</h1>,
+ h2: ({ children }) => <h2 className="mb-1.5 mt-3 text-[14px] font-semibold text-fg">{children}</h2>,
+ h3: ({ children }) => <h3 className="mb-1 mt-2.5 text-[13px] font-semibold text-fg">{children}</h3>,
+ ul: ({ children }) => <ul className="my-1.5 list-disc space-y-1 pl-5 marker:text-fg-muted">{children}</ul>,
+ ol: ({ children }) => <ol className="my-1.5 list-decimal space-y-1 pl-5 marker:text-fg-muted">{children}</ol>,
+ li: ({ children }) => <li className="pl-0.5">{children}</li>,
+ blockquote: ({ children }) => (
+ <blockquote className="my-2 border-l-2 border-accent/50 pl-3 text-fg-2">{children}</blockquote>
+ ),
+ a: ({ children, href, title }) => (
+ <a
+ href={href}
+ title={title}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="font-medium text-accent underline decoration-accent/40 underline-offset-2 hover:decoration-accent"
+ >
+ {children}
+ </a>
+ ),
+ pre: CodeBlock,
+ code: ({ children, className }) => {
+ const block = className?.startsWith("language-") || nodeText(children).includes("\n");
+ return (
+ <code
+ className={
+ block
+ ? `${className ?? ""} font-mono`
+ : "rounded bg-bg-2 px-1 py-0.5 font-mono text-[0.9em] text-fg"
+ }
+ >
+ {children}
+ </code>
+ );
+ },
+ table: ({ children }) => (
+ <table className="my-2 min-w-full border-collapse text-left text-[11px]">{children}</table>
+ ),
+ thead: ({ children }) => <thead className="bg-bg-2 text-fg">{children}</thead>,
+ th: ({ children }) => <th className="border border-border px-2 py-1.5 font-medium">{children}</th>,
+ td: ({ children }) => <td className="border border-border px-2 py-1.5 align-top">{children}</td>,
+ hr: () => <hr className="my-3 border-border" />,
+ img: ({ alt, src, title }) => (
+ <img
+ src={src}
+ alt={alt ?? ""}
+ title={title}
+ loading="lazy"
+ referrerPolicy="no-referrer"
+ className="my-2 max-h-64 max-w-full rounded-lg border border-border object-contain"
+ />
+ ),
+};
+
+export function MarkdownMessage({ text }: { text: string }): JSX.Element {
+ return (
+ <div className="min-w-0 break-words text-[13px] leading-relaxed text-fg [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={components}
+ urlTransform={defaultUrlTransform}
+ >
+ {text}
+ </ReactMarkdown>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/editor/chat/ProviderModelPicker.test.tsx b/apps/web/src/components/editor/chat/ProviderModelPicker.test.tsx
new file mode 100644
index 00000000..d5178db9
--- /dev/null
+++ b/apps/web/src/components/editor/chat/ProviderModelPicker.test.tsx
@@ -0,0 +1,103 @@
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+const h = vi.hoisted(() => ({
+ discoverCompatibleModels: vi.fn(),
+}));
+
+vi.mock("../../../services/agent/model-discovery", () => ({
+ discoverCompatibleModels: h.discoverCompatibleModels,
+}));
+
+vi.mock("../../../services/secure-storage", () => ({
+ getSecret: vi.fn(async () => ""),
+ isSessionUnlocked: vi.fn(() => false),
+ onSessionLock: vi.fn(),
+}));
+
+vi.mock("@openreel/ui", async () => {
+ const actual = await vi.importActual<typeof import("@openreel/ui")>(
+ "@openreel/ui",
+ );
+ return {
+ ...actual,
+ ToolcraftPopover: ({
+ children,
+ content,
+ }: {
+ children: ReactNode;
+ content: ReactNode;
+ }) => (
+ <>
+ {children}
+ {content}
+ </>
+ ),
+ };
+});
+
+import { useSettingsStore } from "../../../stores/settings-store";
+import { ProviderModelPicker } from "./ProviderModelPicker";
+
+describe("ProviderModelPicker", () => {
+ beforeEach(() => {
+ h.discoverCompatibleModels.mockReset();
+ useSettingsStore.setState({
+ defaultLlmProvider: null,
+ llmBaseUrl: "",
+ llmModel: "",
+ configuredServices: [],
+ });
+ });
+
+ it("starts unconfigured and accepts either compatible API format", () => {
+ render(<ProviderModelPicker />);
+
+ const format = screen.getByRole("combobox", { name: "API format" });
+ expect(format).toHaveValue("");
+ expect(screen.getByRole("option", { name: "OpenAI-compatible" })).toBeTruthy();
+ expect(screen.getByRole("option", { name: "Anthropic-compatible" })).toBeTruthy();
+
+ fireEvent.change(format, { target: { value: "anthropic-compatible" } });
+ fireEvent.change(screen.getByRole("textbox", { name: "Base URL" }), {
+ target: { value: "https://gateway.example/v1" },
+ });
+ fireEvent.change(screen.getByRole("textbox", { name: "Model ID" }), {
+ target: { value: "gateway/custom-model" },
+ });
+
+ expect(useSettingsStore.getState()).toMatchObject({
+ defaultLlmProvider: "anthropic-compatible",
+ llmBaseUrl: "https://gateway.example/v1",
+ llmModel: "gateway/custom-model",
+ });
+ });
+
+ it("discovers endpoint models without auto-selecting one", async () => {
+ h.discoverCompatibleModels.mockResolvedValue([
+ { id: "tool-model-a", label: "Tool Model A" },
+ { id: "tool-model-b", label: "Tool Model B" },
+ ]);
+ useSettingsStore.setState({
+ defaultLlmProvider: "openai-compatible",
+ llmBaseUrl: "http://localhost:11434/v1",
+ });
+ render(<ProviderModelPicker />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Load models" }));
+
+ await waitFor(() =>
+ expect(
+ screen.getByRole("combobox", { name: "Models from endpoint" }),
+ ).toBeTruthy(),
+ );
+ expect(useSettingsStore.getState().llmModel).toBe("");
+
+ fireEvent.change(
+ screen.getByRole("combobox", { name: "Models from endpoint" }),
+ { target: { value: "tool-model-b" } },
+ );
+ expect(useSettingsStore.getState().llmModel).toBe("tool-model-b");
+ });
+});
diff --git a/apps/web/src/components/editor/chat/ProviderModelPicker.tsx b/apps/web/src/components/editor/chat/ProviderModelPicker.tsx
index c6c80a44..4db29dbf 100644
--- a/apps/web/src/components/editor/chat/ProviderModelPicker.tsx
+++ b/apps/web/src/components/editor/chat/ProviderModelPicker.tsx
@@ -1,14 +1,27 @@
import type { JSX } from "react";
-import { ToolcraftSelectControl as Selector } from "@openreel/ui";
+import { useState } from "react";
+import {
+ ToolcraftButton as Button,
+ ToolcraftIconButton as IconButton,
+ ToolcraftPopover as Popover,
+ ToolcraftSelectControl as Selector,
+ ToolcraftText as Text,
+ ToolcraftTextInputControl as TextInput,
+} from "@openreel/ui";
+import { Settings2 } from "@/icons/lucide-compat";
import {
useSettingsStore,
type LlmProvider,
} from "../../../stores/settings-store";
-import { modelsFor, defaultModelFor } from "./models";
+import { discoverCompatibleModels } from "../../../services/agent/model-discovery";
+import {
+ getSecret,
+ isSessionUnlocked,
+} from "../../../services/secure-storage";
const PROVIDERS: ReadonlyArray<{ id: LlmProvider; label: string }> = [
- { id: "anthropic", label: "Anthropic" },
- { id: "openai", label: "OpenAI" },
+ { id: "openai-compatible", label: "OpenAI-compatible" },
+ { id: "anthropic-compatible", label: "Anthropic-compatible" },
];
interface ProviderModelPickerProps {
@@ -19,41 +32,201 @@ export function ProviderModelPicker({
disabled = false,
}: ProviderModelPickerProps): JSX.Element {
const provider = useSettingsStore((s) => s.defaultLlmProvider);
+ const baseUrl = useSettingsStore((s) => s.llmBaseUrl);
const model = useSettingsStore((s) => s.llmModel);
+ const configuredServices = useSettingsStore((s) => s.configuredServices);
const setProvider = useSettingsStore((s) => s.setDefaultLlmProvider);
+ const setBaseUrl = useSettingsStore((s) => s.setLlmBaseUrl);
const setModel = useSettingsStore((s) => s.setLlmModel);
+ const openSettings = useSettingsStore((s) => s.openSettings);
+ const [open, setOpen] = useState(false);
+ const [discoveredModels, setDiscoveredModels] = useState<
+ Array<{ id: string; label: string }>
+ >([]);
+ const [discoveryStatus, setDiscoveryStatus] = useState<
+ "idle" | "loading" | "ready" | "error"
+ >("idle");
+ const [discoveryMessage, setDiscoveryMessage] = useState("");
+
+ const providerLabel =
+ PROVIDERS.find((item) => item.id === provider)?.label ?? "Not configured";
+ const currentModel = model.trim();
+
+ const discoverModels = async (): Promise<void> => {
+ if (!provider) {
+ setDiscoveryStatus("error");
+ setDiscoveryMessage("Choose an API format first.");
+ return;
+ }
+ if (!baseUrl.trim()) {
+ setDiscoveryStatus("error");
+ setDiscoveryMessage("Enter the endpoint base URL first.");
+ return;
+ }
+ if (configuredServices.includes(provider) && !isSessionUnlocked()) {
+ setDiscoveryStatus("error");
+ setDiscoveryMessage("Unlock API keys before loading models.");
+ return;
+ }
- const models = modelsFor(provider);
- const currentModel = models.some((m) => m.id === model)
- ? model
- : defaultModelFor(provider);
+ setDiscoveryStatus("loading");
+ setDiscoveryMessage("");
+ try {
+ const apiKey = isSessionUnlocked() ? ((await getSecret(provider)) ?? "") : "";
+ const models = await discoverCompatibleModels({
+ provider,
+ baseUrl,
+ apiKey,
+ });
+ setDiscoveredModels(models);
+ setDiscoveryStatus(models.length > 0 ? "ready" : "error");
+ setDiscoveryMessage(
+ models.length > 0
+ ? `${models.length} model${models.length === 1 ? "" : "s"} found.`
+ : "The endpoint returned no models. Enter a model ID manually.",
+ );
+ } catch (error) {
+ setDiscoveredModels([]);
+ setDiscoveryStatus("error");
+ setDiscoveryMessage(
+ error instanceof Error
+ ? error.message
+ : "Could not load models from this endpoint.",
+ );
+ }
+ };
return (
- <div className="flex items-center gap-1.5">
- <Selector
- label="LLM provider"
- isLabelHidden
- size="sm"
- width="9rem"
- value={provider}
- isDisabled={disabled}
- options={PROVIDERS.map((p) => ({ value: p.id, label: p.label }))}
- onChange={(value) => {
- const next = value as LlmProvider;
- setProvider(next);
- setModel(defaultModelFor(next));
- }}
- />
- <Selector
- label="LLM model"
- isLabelHidden
+ <Popover
+ isOpen={open}
+ onOpenChange={setOpen}
+ placement="below"
+ alignment="end"
+ width={360}
+ label="AI endpoint and model"
+ content={
+ <div className="space-y-3 p-3">
+ <div>
+ <Text type="body" color="primary" className="text-[12px] font-medium">
+ Connect any compatible model
+ </Text>
+ <Text type="supporting" color="secondary" className="mt-0.5 block text-[10px] leading-relaxed">
+ Choose the API format, then use your own host and model. OpenReel does not select a vendor or model for you.
+ </Text>
+ </div>
+
+ <Selector
+ label="API format"
+ size="sm"
+ width="100%"
+ value={provider ?? ""}
+ options={[
+ { value: "", label: "Choose API format…" },
+ ...PROVIDERS.map((item) => ({ value: item.id, label: item.label })),
+ ]}
+ onChange={(value) => {
+ setProvider((value || null) as LlmProvider | null);
+ setDiscoveredModels([]);
+ setDiscoveryStatus("idle");
+ setDiscoveryMessage("");
+ }}
+ />
+
+ <TextInput
+ label="Base URL"
+ value={baseUrl}
+ onChange={(value) => {
+ setBaseUrl(value);
+ setDiscoveredModels([]);
+ setDiscoveryStatus("idle");
+ }}
+ placeholder={
+ provider === "anthropic-compatible"
+ ? "https://gateway.example/v1"
+ : "http://localhost:11434/v1"
+ }
+ width="100%"
+ />
+
+ <div className="space-y-2 rounded-md border border-border bg-bg-2 p-2">
+ <div className="flex items-end gap-2">
+ <div className="min-w-0 flex-1">
+ <TextInput
+ label="Model ID"
+ value={model}
+ onChange={setModel}
+ placeholder="Enter any tool-capable model ID"
+ width="100%"
+ />
+ </div>
+ <Button
+ label={discoveryStatus === "loading" ? "Loading…" : "Load models"}
+ size="sm"
+ variant="secondary"
+ isDisabled={discoveryStatus === "loading" || !provider || !baseUrl.trim()}
+ onClick={() => void discoverModels()}
+ />
+ </div>
+
+ {discoveredModels.length > 0 && (
+ <Selector
+ label="Models from endpoint"
+ size="sm"
+ width="100%"
+ value={
+ discoveredModels.some((item) => item.id === currentModel)
+ ? currentModel
+ : ""
+ }
+ options={[
+ { value: "", label: "Choose a discovered model…" },
+ ...discoveredModels.map((item) => ({
+ value: item.id,
+ label: item.label === item.id ? item.id : `${item.label} · ${item.id}`,
+ })),
+ ]}
+ onChange={(value) => {
+ if (value) setModel(value);
+ }}
+ />
+ )}
+
+ {discoveryStatus !== "idle" && discoveryStatus !== "loading" && (
+ <Text
+ type="supporting"
+ color={discoveryStatus === "error" ? "danger" : "secondary"}
+ className="block text-[10px] leading-relaxed"
+ >
+ {discoveryMessage}
+ </Text>
+ )}
+ </div>
+
+ <Text type="supporting" color="secondary" className="block text-[10px] leading-relaxed">
+ Model discovery uses GET /models. If your gateway does not expose it, enter the model ID manually. Browser endpoints must allow CORS.
+ </Text>
+
+ <Button
+ label="Manage optional API key"
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ setOpen(false);
+ openSettings("api-keys");
+ }}
+ className="w-full"
+ />
+ </div>
+ }
+ >
+ <IconButton
+ label={`AI settings: ${providerLabel}, ${currentModel || "no model selected"}`}
+ icon={<Settings2 size={14} aria-hidden />}
size="sm"
- width="9rem"
- value={currentModel}
+ variant="ghost"
isDisabled={disabled}
- options={models.map((m) => ({ value: m.id, label: m.label }))}
- onChange={(value) => setModel(value)}
+ className="grid h-7 w-7 place-items-center rounded-md text-fg-2 transition-colors hover:bg-hover hover:text-fg"
/>
- </div>
+ </Popover>
);
}
diff --git a/apps/web/src/components/editor/chat/models.ts b/apps/web/src/components/editor/chat/models.ts
index fce0945e..82c6b47c 100644
--- a/apps/web/src/components/editor/chat/models.ts
+++ b/apps/web/src/components/editor/chat/models.ts
@@ -1,6 +1,8 @@
export {
LLM_MODELS,
defaultModelFor,
+ isKnownModel,
modelsFor,
+ resolveModel,
type LlmModelOption,
} from "../../../services/agent/models";
diff --git a/apps/web/src/components/editor/editing-frame-rate.test.ts b/apps/web/src/components/editor/editing-frame-rate.test.ts
new file mode 100644
index 00000000..59b4ecf2
--- /dev/null
+++ b/apps/web/src/components/editor/editing-frame-rate.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_EDITING_FRAME_RATE,
+ EDITING_FRAME_RATE_OPTIONS,
+ editingFrameDurationMs,
+ editingFrameStepSeconds,
+ normalizeEditingFrameRate,
+} from "./editing-frame-rate";
+
+describe("editing frame rate", () => {
+ it("offers standard editorial frame rates including 60 fps", () => {
+ expect(EDITING_FRAME_RATE_OPTIONS.map((option) => option.value)).toEqual([
+ 23.976,
+ 24,
+ 25,
+ 29.97,
+ 30,
+ 50,
+ 59.94,
+ 60,
+ ]);
+ });
+
+ it("drives preview cadence and frame stepping from the project rate", () => {
+ expect(editingFrameDurationMs(60)).toBeCloseTo(16.667, 2);
+ expect(editingFrameStepSeconds(60)).toBeCloseTo(1 / 60, 8);
+ });
+
+ it("falls back safely for invalid project data", () => {
+ expect(normalizeEditingFrameRate(0)).toBe(DEFAULT_EDITING_FRAME_RATE);
+ expect(normalizeEditingFrameRate(Number.NaN)).toBe(
+ DEFAULT_EDITING_FRAME_RATE,
+ );
+ expect(normalizeEditingFrameRate(1000)).toBe(240);
+ });
+});
diff --git a/apps/web/src/components/editor/editing-frame-rate.ts b/apps/web/src/components/editor/editing-frame-rate.ts
new file mode 100644
index 00000000..0fbb0ac0
--- /dev/null
+++ b/apps/web/src/components/editor/editing-frame-rate.ts
@@ -0,0 +1,30 @@
+export const DEFAULT_EDITING_FRAME_RATE = 30;
+
+export const EDITING_FRAME_RATE_OPTIONS: ReadonlyArray<{
+ value: number;
+ label: string;
+}> = [
+ { value: 23.976, label: "23.976 fps" },
+ { value: 24, label: "24 fps" },
+ { value: 25, label: "25 fps" },
+ { value: 29.97, label: "29.97 fps" },
+ { value: 30, label: "30 fps" },
+ { value: 50, label: "50 fps" },
+ { value: 59.94, label: "59.94 fps" },
+ { value: 60, label: "60 fps" },
+];
+
+export function normalizeEditingFrameRate(frameRate: number): number {
+ if (!Number.isFinite(frameRate) || frameRate <= 0) {
+ return DEFAULT_EDITING_FRAME_RATE;
+ }
+ return Math.min(240, frameRate);
+}
+
+export function editingFrameDurationMs(frameRate: number): number {
+ return 1000 / normalizeEditingFrameRate(frameRate);
+}
+
+export function editingFrameStepSeconds(frameRate: number): number {
+ return 1 / normalizeEditingFrameRate(frameRate);
+}
diff --git a/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx b/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx
index e1e88040..aa3bf186 100644
--- a/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx
+++ b/apps/web/src/components/editor/inspector/AudioDuckingSection.test.tsx
@@ -13,6 +13,48 @@ const createProjectWithPersistedDucking = (): Project => {
return {
...project,
+ mediaLibrary: {
+ items: [
+ {
+ id: "media-music",
+ name: "Music",
+ type: "audio",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 8,
+ width: 0,
+ height: 0,
+ frameRate: 0,
+ codec: "aac",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ {
+ id: "media-dialogue",
+ name: "Dialogue",
+ type: "video",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 5,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ ],
+ },
timeline: {
...project.timeline,
duration: 8,
@@ -124,4 +166,4 @@ describe("AudioDuckingSection", () => {
expect(screen.getByText("Dialogue Track")).toBeInTheDocument();
expect(screen.getByText("Trigger Source (Voice Track)")).toBeInTheDocument();
});
-});
\ No newline at end of file
+});
diff --git a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
index 4549b9e6..55f8153b 100644
--- a/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
+++ b/apps/web/src/components/editor/inspector/AudioDuckingSection.tsx
@@ -13,6 +13,7 @@ import {
import {
AudioDucker,
resolveAudibleAudioTarget,
+ trackHasAudioItems,
type Clip,
type Project,
type Track,
@@ -106,8 +107,7 @@ const findClipById = (project: Project, clipId: string): Clip | null => {
};
const getTrackLabel = (track: Track): string => {
- const prefix = track.type === "video" ? "Video" : "Audio";
- return track.name || `${prefix} ${track.id.slice(-4)}`;
+ return track.name || `Track ${track.id.slice(-4)}`;
};
interface DuckingSliderProps {
@@ -266,10 +266,10 @@ export const AudioDuckingSection: React.FC<AudioDuckingSectionProps> = ({
return project.timeline.tracks.filter(
(track): track is Track =>
- (track.type === "audio" || track.type === "video") &&
+ trackHasAudioItems(project, track.id) &&
!track.clips.every((clip) => excludedClipIds.has(clip.id)),
);
- }, [audioTargetClip?.id, clipId, project.timeline.tracks]);
+ }, [audioTargetClip?.id, clipId, project]);
const currentTrack = useMemo(() => {
for (const track of project.timeline.tracks) {
diff --git a/apps/web/src/components/editor/inspector/CaptionEditorPanel.tsx b/apps/web/src/components/editor/inspector/CaptionEditorPanel.tsx
index 5bde5efd..7dfcbc9f 100644
--- a/apps/web/src/components/editor/inspector/CaptionEditorPanel.tsx
+++ b/apps/web/src/components/editor/inspector/CaptionEditorPanel.tsx
@@ -29,7 +29,10 @@ export const CaptionEditorPanel: React.FC<CaptionEditorPanelProps> = ({
() =>
new Set(
project.timeline.tracks
- .filter((track) => track.type === "text" && track.name === "Captions")
+ .filter(
+ (track) =>
+ track.role === "captions" || track.name === "Captions",
+ )
.map((track) => track.id),
),
[project.timeline.tracks],
diff --git a/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx b/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
index 01fb8fec..ef08b4d9 100644
--- a/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
+++ b/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
@@ -24,6 +24,7 @@ import type {
Transition,
TransitionEdge,
} from "@openreel/core";
+import { getMediaItemCapabilities } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { useEngineStore } from "../../../stores/engine-store";
import { toast } from "../../../stores/notification-store";
@@ -932,13 +933,21 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
const timelineClipContext = useMemo(() => {
for (const track of project.timeline.tracks) {
- const sortedClips = [...track.clips].sort((clipA, clipB) => {
- if (clipA.startTime !== clipB.startTime) {
- return clipA.startTime - clipB.startTime;
- }
-
- return clipA.id.localeCompare(clipB.id);
- });
+ const sortedClips = track.clips
+ .filter((clip) =>
+ getMediaItemCapabilities(
+ project.mediaLibrary.items.find(
+ (item) => item.id === clip.mediaId,
+ ),
+ ).visual,
+ )
+ .sort((clipA, clipB) => {
+ if (clipA.startTime !== clipB.startTime) {
+ return clipA.startTime - clipB.startTime;
+ }
+
+ return clipA.id.localeCompare(clipB.id);
+ });
const clipIndex = sortedClips.findIndex((candidate) => candidate.id === clipId);
if (clipIndex === -1) {
@@ -954,7 +963,6 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
currentClip,
previousClip,
nextClip,
- trackType: track.type,
introTransition: track.transitions.find(
(transition) =>
transition.clipAId === currentClip.id &&
@@ -985,7 +993,7 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
}
return null;
- }, [project.timeline.tracks, clipId]);
+ }, [project.timeline.tracks, project.mediaLibrary.items, clipId]);
const clip = useMemo(() => {
const regularClip = timelineClipContext?.currentClip;
@@ -1051,11 +1059,7 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
}, [timelineClipContext]);
const edgeTransitions = useMemo<EdgeTransitionConfig[]>(() => {
- if (
- !timelineClipContext ||
- (timelineClipContext.trackType !== "video" &&
- timelineClipContext.trackType !== "image")
- ) {
+ if (!timelineClipContext) {
return [];
}
diff --git a/apps/web/src/components/editor/inspector/MotionPresetsPanel.test.tsx b/apps/web/src/components/editor/inspector/MotionPresetsPanel.test.tsx
new file mode 100644
index 00000000..9dd4b5dd
--- /dev/null
+++ b/apps/web/src/components/editor/inspector/MotionPresetsPanel.test.tsx
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import type { Clip, Track } from "@openreel/core";
+import { createEmptyProject } from "../../../stores/project/project-helpers";
+import { useProjectStore } from "../../../stores/project-store";
+import { useUIStore } from "../../../stores/ui-store";
+import { MotionPresetsPanel } from "./MotionPresetsPanel";
+
+const CLIP_ID = "motion-preset-clip";
+
+function makeClip(): Clip {
+ return {
+ id: CLIP_ID,
+ mediaId: "image-1",
+ trackId: "video-track-1",
+ startTime: 0,
+ duration: 5,
+ inPoint: 0,
+ outPoint: 5,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ };
+}
+
+describe("MotionPresetsPanel duration", () => {
+ beforeEach(() => {
+ const project = createEmptyProject("Motion preset duration");
+ const track: Track = {
+ id: "video-track-1",
+ type: "video",
+ name: "Video 1",
+ clips: [makeClip()],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ };
+ useProjectStore.setState({
+ hasOpenProject: true,
+ project: {
+ ...project,
+ timeline: {
+ ...project.timeline,
+ tracks: [track],
+ duration: 5,
+ },
+ },
+ });
+ useUIStore.getState().clearSelection();
+ });
+
+ afterEach(() => {
+ cleanup();
+ useProjectStore.setState({ hasOpenProject: false });
+ useUIStore.getState().clearSelection();
+ });
+
+ it("reapplies the selected preset with the customized duration", async () => {
+ render(<MotionPresetsPanel clipId={CLIP_ID} />);
+
+ expect(
+ screen.getByRole("slider", { name: "Motion preset duration" }),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Apply Fade In" }));
+
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Edit Motion preset duration value",
+ }),
+ );
+ const durationInput = screen.getByRole("textbox", {
+ name: "Motion preset duration value",
+ });
+ fireEvent.change(durationInput, { target: { value: "1.2s" } });
+ fireEvent.blur(durationInput);
+
+ await waitFor(() => {
+ const clip = useProjectStore
+ .getState()
+ .project.timeline.tracks[0]?.clips.find(
+ (candidate) => candidate.id === CLIP_ID,
+ );
+ const entranceKeyframes = (clip?.keyframes ?? []).filter((keyframe) =>
+ keyframe.id.startsWith("motion-in-"),
+ );
+ expect(entranceKeyframes.length).toBeGreaterThan(0);
+ expect(Math.max(...entranceKeyframes.map((keyframe) => keyframe.time))).toBe(
+ 1.2,
+ );
+ });
+ });
+});
diff --git a/apps/web/src/components/editor/inspector/MotionPresetsPanel.tsx b/apps/web/src/components/editor/inspector/MotionPresetsPanel.tsx
index 52b7f09d..a2f9419e 100644
--- a/apps/web/src/components/editor/inspector/MotionPresetsPanel.tsx
+++ b/apps/web/src/components/editor/inspector/MotionPresetsPanel.tsx
@@ -8,6 +8,7 @@ import React, {
import { ToolcraftButton as Button } from "@openreel/ui";
import { ToolcraftCard as Card } from "@openreel/ui";
import { ToolcraftClickableCard as ClickableCard } from "@openreel/ui";
+import { ToolcraftSliderControl } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
import {
Play,
@@ -221,12 +222,14 @@ function buildPreviewCSSKeyframes(preset: MotionPreset): globalThis.Keyframe[] {
interface PresetCardProps {
preset: MotionPreset;
+ duration: number;
isApplied: boolean;
onApply: () => void;
}
const PresetCard: React.FC<PresetCardProps> = ({
preset,
+ duration,
isApplied,
onApply,
}) => {
@@ -247,7 +250,7 @@ const PresetCard: React.FC<PresetCardProps> = ({
const keyframes = buildPreviewCSSKeyframes(preset);
animationRef.current = element.animate(keyframes, {
- duration: preset.duration * 1000,
+ duration: duration * 1000,
iterations: Infinity,
easing: "ease-in-out",
});
@@ -255,7 +258,7 @@ const PresetCard: React.FC<PresetCardProps> = ({
return () => {
animationRef.current?.cancel();
};
- }, [isHovered, preset]);
+ }, [duration, isHovered, preset]);
return (
<ClickableCard
@@ -294,7 +297,7 @@ const PresetCard: React.FC<PresetCardProps> = ({
{preset.name}
</Text>
<Text type="supporting" color="secondary" className="text-[8px]">
- {preset.duration}s
+ {duration}s
</Text>
</div>
</ClickableCard>
@@ -331,11 +334,31 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
const [selectedCategory, setSelectedCategory] =
useState<PresetCategory>("entrance");
- const customDurations: Record<string, number> = {};
+ const [customDurations, setCustomDurations] = useState<
+ Partial<Record<PresetCategory, number>>
+ >({});
+ const [lastAppliedPresetId, setLastAppliedPresetId] = useState<string | null>(
+ null,
+ );
+ const durationApplyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
const targetClipId = clipId || selectedClipIds[0];
const presetLibrary = useMemo(() => getPresetLibrary(), []);
- const presets = presetLibrary[selectedCategory] || [];
+ const presets = useMemo(
+ () => presetLibrary[selectedCategory] ?? [],
+ [presetLibrary, selectedCategory],
+ );
+
+ useEffect(
+ () => () => {
+ if (durationApplyTimerRef.current) {
+ clearTimeout(durationApplyTimerRef.current);
+ }
+ },
+ [],
+ );
const clip = useMemo((): { type: string; data: ClipLike } | null => {
if (!targetClipId) return null;
@@ -345,27 +368,39 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
.find((c) => c.id === targetClipId);
if (regularClip) return { type: "regular", data: regularClip as ClipLike };
- const textClip = getTextClip(targetClipId);
+ const textClip =
+ project.textClips?.find((candidate) => candidate.id === targetClipId) ??
+ getTextClip(targetClipId);
if (textClip) return { type: "text", data: textClip as ClipLike };
- const shapeClip = getShapeClip(targetClipId);
+ const shapeClip =
+ project.shapeClips?.find((candidate) => candidate.id === targetClipId) ??
+ getShapeClip(targetClipId);
if (shapeClip) return { type: "shape", data: shapeClip as ClipLike };
- const svgClip = getSVGClip(targetClipId);
+ const svgClip =
+ project.svgClips?.find((candidate) => candidate.id === targetClipId) ??
+ getSVGClip(targetClipId);
if (svgClip) return { type: "svg", data: svgClip as ClipLike };
- const stickerClip = getStickerClip(targetClipId);
+ const stickerClip =
+ project.stickerClips?.find(
+ (candidate) => candidate.id === targetClipId,
+ ) ?? getStickerClip(targetClipId);
if (stickerClip) return { type: "sticker", data: stickerClip as ClipLike };
return null;
}, [
targetClipId,
project.timeline.tracks,
+ project.textClips,
+ project.shapeClips,
+ project.svgClips,
+ project.stickerClips,
getTextClip,
getShapeClip,
getSVGClip,
getStickerClip,
- project.modifiedAt,
]);
const detectAppliedPresets = useCallback(() => {
@@ -388,7 +423,7 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
const appliedState = detectAppliedPresets();
const handleApplyPreset = useCallback(
- (preset: MotionPreset) => {
+ (preset: MotionPreset, durationOverride?: number) => {
if (!clip || !targetClipId) return;
const prefix =
@@ -410,7 +445,15 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
anchor: { x: 0.5, y: 0.5 },
};
- const customDuration = customDurations[preset.id];
+ const customDuration = Math.min(
+ clip.data.duration,
+ Math.max(
+ 0.05,
+ durationOverride ??
+ customDurations[preset.category] ??
+ preset.duration,
+ ),
+ );
const canvas = {
width: project.settings.width,
height: project.settings.height,
@@ -466,10 +509,52 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
],
);
+ const handlePresetClick = useCallback(
+ (preset: MotionPreset) => {
+ setLastAppliedPresetId(preset.id);
+ handleApplyPreset(preset);
+ },
+ [handleApplyPreset],
+ );
+
+ const handleDurationChange = useCallback(
+ (duration: number) => {
+ setCustomDurations((current) => ({
+ ...current,
+ [selectedCategory]: duration,
+ }));
+
+ const appliedPreset = presets.find(
+ (preset) => preset.id === lastAppliedPresetId,
+ );
+ if (!appliedPreset) return;
+
+ if (durationApplyTimerRef.current) {
+ clearTimeout(durationApplyTimerRef.current);
+ }
+ durationApplyTimerRef.current = setTimeout(() => {
+ durationApplyTimerRef.current = null;
+ handleApplyPreset(appliedPreset, duration);
+ }, 160);
+ },
+ [handleApplyPreset, lastAppliedPresetId, presets, selectedCategory],
+ );
+
const handleRemovePresets = useCallback(
(category: PresetCategory) => {
if (!clip || !targetClipId) return;
+ if (durationApplyTimerRef.current) {
+ clearTimeout(durationApplyTimerRef.current);
+ durationApplyTimerRef.current = null;
+ }
+ setLastAppliedPresetId((current) =>
+ current &&
+ (presetLibrary[category] ?? []).some((preset) => preset.id === current)
+ ? null
+ : current,
+ );
+
const prefix =
category === "entrance"
? "motion-in-"
@@ -516,6 +601,7 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
updateClipKeyframes,
updateTextClipKeyframes,
getGraphicsEngine,
+ presetLibrary,
],
);
@@ -541,6 +627,16 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
);
}
+ const maxPresetDuration = Math.max(0.05, clip.data.duration);
+ const defaultCategoryDuration = Math.min(
+ maxPresetDuration,
+ presets[0]?.duration ?? 0.5,
+ );
+ const selectedDuration = Math.min(
+ maxPresetDuration,
+ customDurations[selectedCategory] ?? defaultCategoryDuration,
+ );
+
return (
<div className="space-y-4">
{(appliedState.entrance ||
@@ -616,6 +712,24 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
})}
</div>
+ <Card variant="muted" padding={2} className="space-y-2 border border-border">
+ <ToolcraftSliderControl
+ ariaLabel="Motion preset duration"
+ label="Duration"
+ value={selectedDuration}
+ min={0.05}
+ max={maxPresetDuration}
+ step={0.05}
+ unit="s"
+ defaultValue={defaultCategoryDuration}
+ onChange={handleDurationChange}
+ />
+ <Text type="supporting" color="secondary" className="text-[9px]">
+ Sets how long {selectedCategory} presets run. The last applied preset
+ updates after you stop dragging.
+ </Text>
+ </Card>
+
<div className="grid grid-cols-3 gap-2 max-h-72 overflow-y-auto">
{presets.map((preset) => {
const categoryKey =
@@ -629,8 +743,11 @@ export const MotionPresetsPanel: React.FC<MotionPresetsPanelProps> = ({
<PresetCard
key={preset.id}
preset={preset}
+ duration={
+ customDurations[preset.category] ?? preset.duration
+ }
isApplied={!!appliedState[categoryKey]}
- onApply={() => handleApplyPreset(preset)}
+ onApply={() => handlePresetClick(preset)}
/>
);
})}
diff --git a/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx b/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
index e539945e..1ad34840 100644
--- a/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
+++ b/apps/web/src/components/editor/inspector/MultiCameraPanel.tsx
@@ -8,16 +8,55 @@ import {
ChevronRight,
Check,
Link,
+ Sparkles,
} from "@/icons/lucide-compat";
import { ToolcraftButton as Button } from "@openreel/ui";
import { ToolcraftIconButton as IconButton } from "@openreel/ui";
import { ToolcraftNumberInputControl } from "@openreel/ui";
import { ToolcraftSelectableCard as SelectableCard } from "@openreel/ui";
+import { ToolcraftSelectControl as Selector } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
import { ToolcraftTextInputControl } from "@openreel/ui";
import { useProjectStore } from "../../../stores/project-store";
import { useEngineStore } from "../../../stores/engine-store";
-import type { MultiCamGroup, CameraAngle } from "@openreel/core";
+import { toast } from "../../../stores/notification-store";
+import { loadAudioBuffer } from "../../../utils/load-audio-buffer";
+import {
+ analyzeMulticamActivity,
+ analyzeSileroVad,
+ calibrateMulticamBleed,
+ createOrmaArtifact,
+ extractMulticamSocialClips,
+ incorporateMulticamReactionCues,
+ MULTICAM_POLICY_PRESETS,
+ planMulticamShots,
+ parseMulticamManifest,
+ serializeMulticamManifest,
+ serializeMulticamOtio,
+ serializeOrma,
+ DEFAULT_MULTICAM_EDIT_POLICY,
+ type CameraAngle,
+ type MultiCamGroup,
+ type MulticamEditPolicy,
+ type MulticamDecisionStrategy,
+} from "@openreel/core";
+import {
+ loadMulticamArtifact,
+ saveMulticamArtifact,
+} from "../../../services/multicam-analysis-store";
+import { transcribeMulticamChannels } from "../../../services/multicam-transcription";
+import { analyzeMulticamFaceReactions } from "../../../services/multicam-face-reactions";
+import {
+ createMulticamApplyEditAction,
+ createMulticamApplyTracksAction,
+ analyzeMulticamSyncInWorker,
+ buildMulticamManifest,
+ findMulticamCalibrationRanges,
+ getMulticamAnalysisDuration,
+ prepareMulticamAnalysisAudio,
+ resolveMulticamSources,
+ updateAlignedSourceOffsets,
+} from "./multicam-workflow";
interface MultiCameraPanelProps {
onClose?: () => void;
@@ -116,7 +155,18 @@ const GroupSection: React.FC<{
onRenameAngle: (angleId: string, name: string) => void;
onOffsetChange: (angleId: string, offset: number) => void;
onSync: () => void;
+ onAutoEdit: () => void;
+ onAcceptCut: (switchId: string) => void;
+ onRejectCut: (switchId: string) => void;
+ onNudgeCut: (switchId: string, deltaSeconds: number) => void;
+ onExportOtio: () => void;
+ onExportOrma: () => void;
+ onFindSocialClips: () => void;
+ onImportManifest: (file: File) => void;
+ onExportManifest: () => void;
onDelete: () => void;
+ isProcessing: boolean;
+ status?: string;
}> = ({
group,
isExpanded,
@@ -126,7 +176,18 @@ const GroupSection: React.FC<{
onRenameAngle,
onOffsetChange,
onSync,
+ onAutoEdit,
+ onAcceptCut,
+ onRejectCut,
+ onNudgeCut,
+ onExportOtio,
+ onExportOrma,
+ onFindSocialClips,
+ onImportManifest,
+ onExportManifest,
onDelete,
+ isProcessing,
+ status,
}) => (
<div className="border border-border rounded-lg overflow-hidden">
<Button
@@ -169,8 +230,18 @@ const GroupSection: React.FC<{
variant="ghost"
icon={<Link size={10} />}
onClick={onSync}
+ isDisabled={isProcessing}
className="flex-1 flex items-center justify-center gap-1 py-1.5 text-[9px] text-fg-2 hover:text-fg bg-bg-2 rounded transition-colors"
/>
+ <Button
+ label="Auto Edit"
+ variant="primary"
+ icon={<Sparkles size={10} />}
+ onClick={onAutoEdit}
+ isLoading={isProcessing}
+ isDisabled={group.angles.length < 2}
+ className="flex-1 flex items-center justify-center gap-1 py-1.5 text-[9px] rounded transition-colors"
+ />
<IconButton
label="Delete camera group"
icon={<Trash2 size={10} />}
@@ -180,6 +251,118 @@ const GroupSection: React.FC<{
className="flex items-center justify-center gap-1 px-2 py-1.5 text-[9px] text-red-400 hover:bg-red-400/10 rounded transition-colors"
/>
</div>
+ <div className="flex gap-1">
+ <label className="flex-1 cursor-pointer rounded bg-bg-2 py-1 text-center text-[8px] text-fg-2 hover:text-fg">
+ Import manifest
+ <input
+ type="file"
+ accept=".json,.yaml,.yml,application/json,application/yaml,text/yaml"
+ className="hidden"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ if (file) onImportManifest(file);
+ event.target.value = "";
+ }}
+ />
+ </label>
+ {group.manifest && (
+ <Button
+ label="Export manifest"
+ variant="ghost"
+ onClick={onExportManifest}
+ className="flex-1 py-1 text-[8px]"
+ />
+ )}
+ </div>
+ {status && (
+ <Text type="supporting" color="secondary" className="block text-[9px] text-fg-3">
+ {status}
+ </Text>
+ )}
+ {(group.switches?.length ?? 0) > 0 && (
+ <div className="space-y-1 rounded-md border border-border bg-bg-1 p-2">
+ <div className="flex items-center justify-between text-[9px]">
+ <span className="font-medium text-fg-2">Cut review</span>
+ <span className="text-fg-3">
+ {Math.max(0, (group.switches?.length ?? 1) - 1)} cuts
+ </span>
+ </div>
+ <div className="max-h-28 space-y-1 overflow-y-auto">
+ {(group.switches ?? []).map((switchItem, switchIndex) => {
+ const angle = group.angles.find((item) => item.id === switchItem.angleId);
+ return (
+ <div
+ key={switchItem.id}
+ className="grid grid-cols-[42px_1fr_auto] items-center gap-1 text-[8px] text-fg-3"
+ >
+ <span>{switchItem.time.toFixed(2)}s</span>
+ <span className="truncate text-fg-2">{angle?.name ?? switchItem.angleId}</span>
+ <span className="text-right">
+ {switchItem.reason?.replaceAll("-", " ") ?? "manual"}
+ {switchItem.confidence !== undefined
+ ? ` · ${Math.round(switchItem.confidence * 100)}%`
+ : ""}
+ </span>
+ {switchIndex > 0 && (
+ <div className="col-span-3 flex items-center justify-end gap-1">
+ <Button
+ label="−100 ms"
+ variant="ghost"
+ onClick={() => onNudgeCut(switchItem.id, -0.1)}
+ className="px-1 py-0.5 text-[8px]"
+ />
+ <Button
+ label="+100 ms"
+ variant="ghost"
+ onClick={() => onNudgeCut(switchItem.id, 0.1)}
+ className="px-1 py-0.5 text-[8px]"
+ />
+ <Button
+ label="Reject"
+ variant="ghost"
+ onClick={() => onRejectCut(switchItem.id)}
+ className="px-1 py-0.5 text-[8px] text-red-400"
+ />
+ <Button
+ label={switchItem.reviewStatus === "accepted" ? "Accepted" : "Accept"}
+ variant="ghost"
+ onClick={() => onAcceptCut(switchItem.id)}
+ isDisabled={switchItem.reviewStatus === "accepted"}
+ className="px-1 py-0.5 text-[8px] text-emerald-400"
+ />
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ <Text type="supporting" color="secondary" className="block text-[8px] text-fg-3">
+ The generated output track remains fully editable on the timeline.
+ </Text>
+ </div>
+ )}
+ {group.manifest && group.shotPlan && (
+ <div className="flex gap-1 border-t border-border pt-2">
+ <Button
+ label="Export OTIO"
+ variant="ghost"
+ onClick={onExportOtio}
+ className="flex-1 py-1 text-[8px]"
+ />
+ <Button
+ label="Export .orma"
+ variant="ghost"
+ onClick={onExportOrma}
+ className="flex-1 py-1 text-[8px]"
+ />
+ <Button
+ label="Find clips"
+ variant="ghost"
+ onClick={onFindSocialClips}
+ className="flex-1 py-1 text-[8px]"
+ />
+ </div>
+ )}
</div>
)}
</div>
@@ -191,6 +374,17 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const [selectedClips, setSelectedClips] = useState<string[]>([]);
+ const [processingGroupId, setProcessingGroupId] = useState<string | null>(null);
+ const [groupStatus, setGroupStatus] = useState<Record<string, string>>({});
+ const [overlapStrategy, setOverlapStrategy] =
+ useState<MulticamDecisionStrategy>("hold");
+ const [overlapEscalation, setOverlapEscalation] =
+ useState<Exclude<MulticamDecisionStrategy, "hold">>("wide");
+ const [minShotSeconds, setMinShotSeconds] = useState(1.8);
+ const [maxShotSeconds, setMaxShotSeconds] = useState(30);
+ const [includeTranscripts, setIncludeTranscripts] = useState(false);
+ const [includeVisualReactions, setIncludeVisualReactions] = useState(false);
+ const [policyPreset, setPolicyPreset] = useState("custom");
const [multiCamEngine, setMultiCamEngine] =
useState<import("@openreel/core").MultiCamEngine | null>(null);
@@ -208,15 +402,26 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
};
}, [getMultiCamEngine]);
- const groups = useMemo(() => {
- return multiCamEngine?.getAllGroups() || [];
- }, [multiCamEngine, project.modifiedAt]);
+ const groups = multiCamEngine?.getAllGroups() || [];
+
+ const editPolicy = useMemo<MulticamEditPolicy>(
+ () => ({
+ ...DEFAULT_MULTICAM_EDIT_POLICY,
+ overlapStrategy: overlapStrategy === "hold" ? "hold" : "winner",
+ minShotMs: Math.max(0, minShotSeconds) * 1_000,
+ maxShotMs: Math.max(0, maxShotSeconds) * 1_000,
+ }),
+ [maxShotSeconds, minShotSeconds, overlapStrategy],
+ );
const availableClips = useMemo(() => {
const clips: { id: string; name: string; trackName: string }[] = [];
for (const track of project.timeline.tracks) {
- if (track.type === "video" || track.type === "image") {
- for (const clip of track.clips) {
+ for (const clip of track.clips) {
+ const media = project.mediaLibrary.items.find(
+ (item) => item.id === clip.mediaId,
+ );
+ if (media?.type === "video") {
clips.push({
id: clip.id,
name: `Clip ${clip.id.slice(-6)}`,
@@ -228,6 +433,77 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
return clips;
}, [project]);
+ const setStatus = useCallback((groupId: string, status: string) => {
+ setGroupStatus((current) => ({ ...current, [groupId]: status }));
+ }, []);
+
+ const persistGroups = useCallback(async () => {
+ if (!multiCamEngine) return;
+ const result = await useProjectStore.getState().executeAction({
+ type: "multicam/setAll",
+ id: crypto.randomUUID(),
+ timestamp: Date.now(),
+ params: { groups: multiCamEngine.getAllGroups() },
+ });
+ if (!result.success) {
+ throw new Error(result.error?.message ?? "Could not save the camera group.");
+ }
+ }, [multiCamEngine]);
+
+ const decodeGroupAudio = useCallback(
+ async (group: MultiCamGroup) => {
+ const currentProject = useProjectStore.getState().project;
+ const sources = resolveMulticamSources(currentProject, group);
+ const unsupportedSource = sources.find(
+ (source) => source.clip.reversed || (source.clip.speed ?? 1) !== 1,
+ );
+ if (unsupportedSource) {
+ throw new Error(
+ `${unsupportedSource.angle.name} must use normal-speed, forward playback for audio analysis.`,
+ );
+ }
+ const buffers = new Map<string, AudioBuffer>();
+ const audioContext = new AudioContext();
+ try {
+ for (const source of sources) {
+ if (!source.media.blob) {
+ throw new Error(`${source.angle.name} needs its source media relinked.`);
+ }
+ setStatus(group.id, `Decoding ${source.angle.name}…`);
+ const buffer = await loadAudioBuffer(audioContext, source.media.blob, {
+ audioTrackIndex: source.clip.audioTrackIndex,
+ onProgress: ({ message }) => setStatus(group.id, `${source.angle.name}: ${message}`),
+ });
+ if (!buffer) {
+ throw new Error(`Could not decode audio for ${source.angle.name}.`);
+ }
+ buffers.set(source.angle.id, buffer);
+ }
+ } finally {
+ await audioContext.close();
+ }
+ return { buffers, sources };
+ },
+ [setStatus],
+ );
+
+ const updateGroupSourceLayout = useCallback(
+ (
+ groupId: string,
+ sources: ReturnType<typeof resolveMulticamSources>,
+ ) => {
+ const liveGroup = multiCamEngine?.getGroup(groupId);
+ if (!liveGroup) throw new Error("Camera group is no longer available.");
+ for (const source of sources) {
+ const angle = liveGroup.angles.find((item) => item.id === source.angle.id);
+ if (angle) angle.trackId = source.track.id;
+ }
+ liveGroup.syncPoint = Math.min(...sources.map((source) => source.clip.startTime));
+ return liveGroup;
+ },
+ [multiCamEngine],
+ );
+
const toggleGroup = (groupId: string) => {
setExpandedGroups((prev) => {
const next = new Set(prev);
@@ -240,76 +516,526 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
});
};
- const handleCreateGroup = useCallback(() => {
+ const handleCreateGroup = useCallback(async () => {
if (!multiCamEngine || selectedClips.length < 2) return;
const group = multiCamEngine.createGroup(
`Multi-Cam ${groups.length + 1}`,
selectedClips,
);
+ try {
+ const sources = resolveMulticamSources(project, group);
+ updateGroupSourceLayout(group.id, sources);
+ group.duration = Math.min(...sources.map((source) => source.clip.duration));
+ await persistGroups();
+ } catch (error) {
+ multiCamEngine.deleteGroup(group.id);
+ toast.error(
+ "Camera group failed",
+ error instanceof Error ? error.message : "Could not create the camera group.",
+ );
+ return;
+ }
setExpandedGroups((prev) => new Set([...prev, group.id]));
setSelectedClips([]);
-
- void useProjectStore.getState().executeAction({
- type: "multicam/setAll",
- id: crypto.randomUUID(),
- timestamp: Date.now(),
- params: { groups: multiCamEngine?.getAllGroups() ?? [] },
- });
- }, [multiCamEngine, selectedClips, groups.length]);
+ }, [
+ groups.length,
+ multiCamEngine,
+ persistGroups,
+ project,
+ selectedClips,
+ updateGroupSourceLayout,
+ ]);
const handleSelectAngle = useCallback(
(groupId: string, angleId: string) => {
if (!multiCamEngine) return;
multiCamEngine.setActiveAngle(groupId, angleId);
- useProjectStore.setState((state) => ({
- project: { ...state.project, modifiedAt: Date.now() },
- }));
+ void persistGroups().catch((error) =>
+ toast.error("Could not save angle", error instanceof Error ? error.message : undefined),
+ );
},
- [multiCamEngine],
+ [multiCamEngine, persistGroups],
);
const handleRemoveAngle = useCallback(
(groupId: string, angleId: string) => {
if (!multiCamEngine) return;
multiCamEngine.removeAngle(groupId, angleId);
- useProjectStore.setState((state) => ({
- project: { ...state.project, modifiedAt: Date.now() },
- }));
+ void persistGroups().catch((error) =>
+ toast.error("Could not remove angle", error instanceof Error ? error.message : undefined),
+ );
},
- [multiCamEngine],
+ [multiCamEngine, persistGroups],
);
const handleRenameAngle = useCallback(
(groupId: string, angleId: string, name: string) => {
if (!multiCamEngine) return;
multiCamEngine.renameAngle(groupId, angleId, name);
- useProjectStore.setState((state) => ({
- project: { ...state.project, modifiedAt: Date.now() },
- }));
+ void persistGroups().catch((error) =>
+ toast.error("Could not rename angle", error instanceof Error ? error.message : undefined),
+ );
},
- [multiCamEngine],
+ [multiCamEngine, persistGroups],
);
const handleOffsetChange = useCallback(
(groupId: string, angleId: string, offset: number) => {
if (!multiCamEngine) return;
multiCamEngine.setAngleOffset(groupId, angleId, offset);
- useProjectStore.setState((state) => ({
- project: { ...state.project, modifiedAt: Date.now() },
- }));
+ void persistGroups().catch((error) =>
+ toast.error("Could not save offset", error instanceof Error ? error.message : undefined),
+ );
},
- [multiCamEngine],
+ [multiCamEngine, persistGroups],
);
const handleSyncAudio = useCallback(
- async (_groupId: string) => {
+ async (groupId: string) => {
if (!multiCamEngine) return;
+ const group = multiCamEngine.getGroup(groupId);
+ if (!group || processingGroupId) return;
+ setProcessingGroupId(groupId);
+ try {
+ const { buffers, sources } = await decodeGroupAudio(group);
+ updateGroupSourceLayout(groupId, sources);
+ setStatus(groupId, "Synchronizing camera audio…");
+ const { results } = await analyzeMulticamSyncInWorker(
+ buffers,
+ group.angles[0]?.id ?? "",
+ );
+ const liveGroup = multiCamEngine.getGroup(groupId);
+ if (!liveGroup) throw new Error("Camera group is no longer available.");
+ updateAlignedSourceOffsets(liveGroup, sources, results);
+ const alignedSources = sources.map((source) => ({
+ ...source,
+ angle:
+ liveGroup.angles.find((angle) => angle.id === source.angle.id) ?? source.angle,
+ }));
+ liveGroup.duration = getMulticamAnalysisDuration(alignedSources, buffers);
+ await persistGroups();
+ const confidences = [...results.values()].map((result) => result.confidence);
+ const confidence = confidences.length
+ ? confidences.reduce((sum, value) => sum + value, 0) / confidences.length
+ : 0;
+ setStatus(groupId, `Audio synchronized · ${Math.round(confidence * 100)}% confidence`);
+ toast.success("Camera audio synchronized", group.name);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Audio sync failed.";
+ setStatus(groupId, message);
+ toast.error("Audio sync failed", message);
+ } finally {
+ setProcessingGroupId(null);
+ }
+ },
+ [
+ decodeGroupAudio,
+ multiCamEngine,
+ persistGroups,
+ processingGroupId,
+ setStatus,
+ updateGroupSourceLayout,
+ ],
+ );
+
+ const handleAutoEdit = useCallback(
+ async (groupId: string) => {
+ if (!multiCamEngine || processingGroupId) return;
+ const group = multiCamEngine.getGroup(groupId);
+ if (!group) return;
+ setProcessingGroupId(groupId);
+ try {
+ const { buffers, sources } = await decodeGroupAudio(group);
+ updateGroupSourceLayout(groupId, sources);
+ setStatus(groupId, "Synchronizing camera audio…");
+ const { results: syncResults, drift } = await analyzeMulticamSyncInWorker(
+ buffers,
+ group.angles[0]?.id ?? "",
+ );
+
+ const liveGroup = multiCamEngine.getGroup(groupId);
+ if (!liveGroup) throw new Error("Camera group is no longer available.");
+ updateAlignedSourceOffsets(liveGroup, sources, syncResults);
+ for (const angle of liveGroup.angles) {
+ angle.driftSecondsPerSecond = drift[angle.id]?.secondsPerSecond ?? 0;
+ }
+ const alignedSources = sources.map((source) => ({
+ ...source,
+ angle:
+ liveGroup.angles.find((angle) => angle.id === source.angle.id) ?? source.angle,
+ }));
+ const duration = getMulticamAnalysisDuration(alignedSources, buffers);
+ if (!Number.isFinite(duration) || duration <= 0.1) {
+ throw new Error("The camera recordings do not have enough overlapping audio.");
+ }
+
+ setStatus(groupId, "Running local Silero voice detection…");
+ const vadTracks = new Map<string, import("@openreel/core").MulticamVadTrack>();
+ for (const source of alignedSources) {
+ const buffer = buffers.get(source.angle.id);
+ if (!buffer) continue;
+ const vadAudio = prepareMulticamAnalysisAudio(buffer, 16_000);
+ const vad = await analyzeSileroVad(vadAudio.samples, vadAudio.sampleRate, {
+ onProgress: (completed, total) => {
+ if (completed === total || completed % 100 === 0) {
+ setStatus(
+ groupId,
+ `Voice detection · ${source.angle.name} · ${Math.round((completed / total) * 100)}%`,
+ );
+ }
+ },
+ });
+ vadTracks.set(source.angle.id, vad);
+ }
+ setStatus(groupId, "Calibrating room noise and microphone bleed…");
+ const calibrationWindows = findMulticamCalibrationRanges(vadTracks);
+ const calibrationSources = alignedSources.map((source) => {
+ const buffer = buffers.get(source.angle.id);
+ if (!buffer) throw new Error(`Missing decoded audio for ${source.angle.name}.`);
+ const analysisAudio = prepareMulticamAnalysisAudio(buffer);
+ return { angleId: source.angle.id, ...analysisAudio };
+ });
+ const calibration = calibrateMulticamBleed(
+ calibrationSources,
+ calibrationWindows.ranges,
+ calibrationWindows.silenceRange,
+ );
+ setStatus(groupId, "Analyzing speakers and microphone bleed…");
+ const activity = analyzeMulticamActivity(
+ alignedSources.map((source) => {
+ const buffer = buffers.get(source.angle.id);
+ if (!buffer) throw new Error(`Missing decoded audio for ${source.angle.name}.`);
+ const analysisAudio = prepareMulticamAnalysisAudio(buffer);
+ return {
+ angleId: source.angle.id,
+ samples: analysisAudio.samples,
+ sampleRate: analysisAudio.sampleRate,
+ offsetSeconds: source.clip.inPoint + source.angle.offset,
+ vad: vadTracks.get(source.angle.id),
+ };
+ }),
+ { durationSeconds: duration, bleedCalibration: calibration },
+ );
+ const currentProject = useProjectStore.getState().project;
+ const manifest = liveGroup.manifest ?? buildMulticamManifest(
+ currentProject,
+ liveGroup,
+ alignedSources,
+ {
+ min_shot_ms: editPolicy.minShotMs,
+ max_shot_ms: Math.max(editPolicy.minShotMs, editPolicy.maxShotMs),
+ cut_lead_ms: editPolicy.cutLeadMs,
+ reaction_shot_after_ms: editPolicy.reactionShotAfterMs,
+ forbid_jump_cut_same_subject: editPolicy.forbidJumpCutSameSubject,
+ },
+ );
+ liveGroup.manifest = manifest;
+ const reactions = includeVisualReactions
+ ? await analyzeMulticamFaceReactions(
+ alignedSources,
+ manifest,
+ duration,
+ { onProgress: (message) => setStatus(groupId, message) },
+ )
+ : [];
+ const shotPlan = incorporateMulticamReactionCues(
+ planMulticamShots(activity, manifest, {
+ strategy: overlapStrategy,
+ escalateTo: overlapEscalation,
+ }),
+ manifest,
+ reactions,
+ );
+ if (shotPlan.shots.length === 0) {
+ throw new Error("No usable speaker activity was detected.");
+ }
+ liveGroup.shotPlan = shotPlan;
+ multiCamEngine.applyAutomaticEdit(
+ groupId,
+ {
+ duration: shotPlan.durationMs / 1_000,
+ segments: shotPlan.shots.map((shot) => ({
+ angleId: shot.layout.panels[0]?.cameraId ?? manifest.sync.reference,
+ startTime: shot.startMs / 1_000,
+ endTime: shot.endMs / 1_000,
+ reason: shot.reason,
+ confidence: shot.confidence,
+ })),
+ },
+ editPolicy,
+ activity.windowMs,
+ );
+ const artifact = createOrmaArtifact({
+ manifest,
+ media: alignedSources.map((source) => ({
+ id: source.media.id,
+ name: source.media.sourceFile?.name ?? source.media.name,
+ size: source.media.sourceFile?.size ?? source.media.blob?.size ?? 0,
+ lastModified: source.media.sourceFile?.lastModified ?? 0,
+ })),
+ activity,
+ drift,
+ calibration,
+ reactions,
+ transcripts: includeTranscripts
+ ? await transcribeMulticamChannels(buffers, {
+ onStatus: (angleId, message) => {
+ const angle = liveGroup.angles.find((entry) => entry.id === angleId);
+ setStatus(groupId, `${angle?.name ?? angleId}: ${message}`);
+ },
+ })
+ : undefined,
+ });
+ liveGroup.analysisArtifactId = await saveMulticamArtifact(
+ currentProject.id,
+ groupId,
+ artifact,
+ );
+
+ const outputTrackId = liveGroup.outputTrackId ?? `multicam-output-${groupId}`;
+ const sourceClips = new Map(
+ alignedSources.map((source) => [source.clip.id, source.clip]),
+ );
+ const outputTracks = multiCamEngine.buildShotPlanTracks(
+ groupId,
+ outputTrackId,
+ sourceClips,
+ currentProject.settings,
+ );
+ if (outputTracks.length === 0 || outputTracks.every((track) => track.clips.length === 0)) {
+ throw new Error("The detected cuts could not be mapped to source clips.");
+ }
+ multiCamEngine.setOutputTracks(groupId, outputTracks.map((track) => track.id));
+
+ setStatus(groupId, `Applying ${Math.max(0, shotPlan.shots.length - 1)} cuts…`);
+ const updatedGroup = multiCamEngine.getGroup(groupId);
+ if (!updatedGroup) throw new Error("Camera group is no longer available.");
+ const applyAction = createMulticamApplyTracksAction({
+ project: currentProject,
+ group: updatedGroup,
+ groups: multiCamEngine.getAllGroups(),
+ outputTracks,
+ });
+ const result = await useProjectStore.getState().executeAction(applyAction);
+ if (!result.success) {
+ throw new Error(result.error?.message ?? "Could not apply the automatic edit.");
+ }
+ setStatus(
+ groupId,
+ `${shotPlan.shots.length} shots created on “${group.name} Auto Edit”`,
+ );
+ toast.success(
+ "Automatic multicam edit created",
+ `${Math.max(0, shotPlan.shots.length - 1)} cuts · one undo step`,
+ );
+ } catch (error) {
+ multiCamEngine.loadGroups(
+ useProjectStore.getState().project.multicamGroups ?? [],
+ );
+ const message = error instanceof Error ? error.message : "Automatic edit failed.";
+ setStatus(groupId, message);
+ toast.error("Automatic edit failed", message);
+ } finally {
+ setProcessingGroupId(null);
+ }
+ },
+ [
+ decodeGroupAudio,
+ editPolicy,
+ includeTranscripts,
+ includeVisualReactions,
+ multiCamEngine,
+ overlapEscalation,
+ overlapStrategy,
+ processingGroupId,
+ setStatus,
+ updateGroupSourceLayout,
+ ],
+ );
+
+ const downloadText = useCallback((filename: string, contents: string, type: string) => {
+ const url = URL.createObjectURL(new Blob([contents], { type }));
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.click();
+ URL.revokeObjectURL(url);
+ }, []);
+
+ const handleExportOtio = useCallback((groupId: string) => {
+ const group = multiCamEngine?.getGroup(groupId);
+ if (!group?.manifest || !group.shotPlan) return;
+ downloadText(
+ `${group.name.replace(/[^a-z0-9-_]+/gi, "-")}.otio`,
+ serializeMulticamOtio(group.shotPlan, group.manifest, group.name),
+ "application/json",
+ );
+ }, [downloadText, multiCamEngine]);
+
+ const handleExportOrma = useCallback(async (groupId: string) => {
+ const group = multiCamEngine?.getGroup(groupId);
+ if (!group) return;
+ const artifact = await loadMulticamArtifact(
+ useProjectStore.getState().project.id,
+ groupId,
+ );
+ if (!artifact) {
+ toast.error("Analysis unavailable", "Run Auto Edit before exporting the .orma artifact.");
+ return;
+ }
+ downloadText(
+ `${group.name.replace(/[^a-z0-9-_]+/gi, "-")}.orma`,
+ serializeOrma(artifact),
+ "application/vnd.openreel.activity+json",
+ );
+ }, [downloadText, multiCamEngine]);
+
+ const handleImportManifest = useCallback(async (groupId: string, file: File) => {
+ if (!multiCamEngine) return;
+ try {
+ const parsed = parseMulticamManifest(await file.text());
+ const group = multiCamEngine.getGroup(groupId);
+ if (!group) throw new Error("Camera group is no longer available.");
+ const currentProject = useProjectStore.getState().project;
+ const sources = resolveMulticamSources(currentProject, group);
+ const unusedAngles = [...group.angles];
+ const cameras = parsed.cameras.map((camera) => {
+ const matched = unusedAngles.find((angle) => {
+ const source = sources.find((entry) => entry.angle.id === angle.id);
+ return (
+ camera.angleId === angle.id ||
+ camera.id === angle.id ||
+ camera.clipId === angle.clipId ||
+ camera.file === source?.media.sourceFile?.name ||
+ camera.file === source?.media.name
+ );
+ }) ?? unusedAngles[0];
+ if (!matched) throw new Error(`Could not map camera ${camera.id} (${camera.file}) to a selected angle.`);
+ unusedAngles.splice(unusedAngles.indexOf(matched), 1);
+ return { ...camera, clipId: matched.clipId, angleId: matched.id };
+ });
+ group.manifest = { ...parsed, cameras };
+ await persistGroups();
+ toast.success("Multicam manifest imported", `${parsed.participants.length} participants · ${parsed.cameras.length} cameras`);
+ } catch (error) {
+ toast.error("Manifest import failed", error instanceof Error ? error.message : undefined);
+ }
+ }, [multiCamEngine, persistGroups]);
+
+ const handleExportManifest = useCallback((groupId: string) => {
+ const group = multiCamEngine?.getGroup(groupId);
+ if (!group?.manifest) return;
+ downloadText(
+ `${group.name.replace(/[^a-z0-9-_]+/gi, "-")}.multicam.json`,
+ serializeMulticamManifest(group.manifest),
+ "application/json",
+ );
+ }, [downloadText, multiCamEngine]);
+
+ const handleFindSocialClips = useCallback(async (groupId: string) => {
+ const artifact = await loadMulticamArtifact(
+ useProjectStore.getState().project.id,
+ groupId,
+ );
+ if (!artifact) {
+ toast.error("Analysis unavailable", "Run Auto Edit before finding social clips.");
+ return;
+ }
+ const candidates = extractMulticamSocialClips(artifact);
+ const store = useProjectStore.getState();
+ store.beginHistoryGroup("Add multicam social clip candidates");
+ try {
+ for (const candidate of candidates) {
+ await useProjectStore.getState().executeAction({
+ type: "marker/add",
+ id: crypto.randomUUID(),
+ timestamp: Date.now(),
+ params: {
+ time: candidate.startMs / 1_000,
+ label: `Social · ${candidate.title ?? candidate.reason}`,
+ color: "#f59e0b",
+ },
+ });
+ }
+ } finally {
+ useProjectStore.getState().endHistoryGroup();
+ }
+ toast.success("Social clip candidates added", `${candidates.length} timeline markers`);
+ }, []);
+
+ const applyReviewedEdit = useCallback(
+ async (groupId: string) => {
+ if (!multiCamEngine) return;
+ const group = multiCamEngine.getGroup(groupId);
+ if (!group?.outputTrackId) return;
+ const currentProject = useProjectStore.getState().project;
+ const sources = resolveMulticamSources(currentProject, group);
+ const sourceClips = new Map(sources.map((source) => [source.clip.id, source.clip]));
+ const outputTracks = group.shotPlan
+ ? multiCamEngine.buildShotPlanTracks(
+ groupId,
+ group.outputTrackId,
+ sourceClips,
+ currentProject.settings,
+ )
+ : [];
+ const action = outputTracks.length
+ ? createMulticamApplyTracksAction({
+ project: currentProject,
+ group,
+ groups: multiCamEngine.getAllGroups(),
+ outputTracks,
+ })
+ : createMulticamApplyEditAction({
+ project: currentProject,
+ group,
+ groups: multiCamEngine.getAllGroups(),
+ outputTrackId: group.outputTrackId,
+ sequence: multiCamEngine.buildSequenceClips(
+ groupId,
+ group.outputTrackId,
+ sourceClips,
+ ),
+ });
+ const result = await useProjectStore.getState().executeAction(action);
+ if (!result.success) throw new Error(result.error?.message ?? "Could not update cut review.");
},
[multiCamEngine],
);
+ const handleAcceptCut = useCallback(async (groupId: string, switchId: string) => {
+ if (!multiCamEngine?.acceptSwitch(groupId, switchId)) return;
+ try {
+ await applyReviewedEdit(groupId);
+ } catch (error) {
+ toast.error("Could not accept cut", error instanceof Error ? error.message : undefined);
+ }
+ }, [applyReviewedEdit, multiCamEngine]);
+
+ const handleRejectCut = useCallback(async (groupId: string, switchId: string) => {
+ if (!multiCamEngine?.removeSwitch(groupId, switchId)) return;
+ try {
+ await applyReviewedEdit(groupId);
+ } catch (error) {
+ toast.error("Could not reject cut", error instanceof Error ? error.message : undefined);
+ }
+ }, [applyReviewedEdit, multiCamEngine]);
+
+ const handleNudgeCut = useCallback(async (
+ groupId: string,
+ switchId: string,
+ deltaSeconds: number,
+ ) => {
+ if (!multiCamEngine?.nudgeSwitch(groupId, switchId, deltaSeconds)) return;
+ try {
+ await applyReviewedEdit(groupId);
+ } catch (error) {
+ toast.error("Could not nudge cut", error instanceof Error ? error.message : undefined);
+ }
+ }, [applyReviewedEdit, multiCamEngine]);
+
const handleDeleteGroup = useCallback(
(groupId: string) => {
if (!multiCamEngine) return;
@@ -319,11 +1045,11 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
next.delete(groupId);
return next;
});
- useProjectStore.setState((state) => ({
- project: { ...state.project, modifiedAt: Date.now() },
- }));
+ void persistGroups().catch((error) =>
+ toast.error("Could not delete group", error instanceof Error ? error.message : undefined),
+ );
},
- [multiCamEngine],
+ [multiCamEngine, persistGroups],
);
const toggleClipSelection = (clipId: string) => {
@@ -348,6 +1074,106 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
</div>
</div>
+ <div className="space-y-2 rounded-lg border border-border bg-bg-2 p-2">
+ <span className="text-[10px] font-medium text-fg-2">Automatic edit policy</span>
+ <Selector
+ label="Preset"
+ size="sm"
+ width="100%"
+ value={policyPreset}
+ onChange={(value) => {
+ setPolicyPreset(value);
+ if (value === "conversation" || value === "energetic" || value === "panel") {
+ const preset = MULTICAM_POLICY_PRESETS[value];
+ setOverlapStrategy(preset.strategy);
+ setOverlapEscalation(preset.escalateTo);
+ }
+ }}
+ options={[
+ { label: "Custom", value: "custom" },
+ { label: "Conversation", value: "conversation" },
+ { label: "Energetic", value: "energetic" },
+ { label: "Panel", value: "panel" },
+ ]}
+ />
+ <Selector
+ label="Overlapping speakers"
+ size="sm"
+ width="100%"
+ value={overlapStrategy}
+ onChange={(value) => {
+ setPolicyPreset("custom");
+ setOverlapStrategy(value);
+ }}
+ options={[
+ { label: "Hold current camera", value: "hold" },
+ { label: "Choose energy winner", value: "winner" },
+ { label: "Participant priority", value: "priority" },
+ { label: "Use wide shot", value: "wide" },
+ { label: "Split active speakers", value: "composite" },
+ { label: "Progressive PiP", value: "progressive" },
+ ]}
+ />
+ <Selector
+ label="Sustained overlap"
+ size="sm"
+ width="100%"
+ value={overlapEscalation}
+ onChange={(value) => {
+ setPolicyPreset("custom");
+ setOverlapEscalation(value);
+ }}
+ options={[
+ { label: "Wide shot", value: "wide" },
+ { label: "Energy winner", value: "winner" },
+ { label: "Participant priority", value: "priority" },
+ { label: "Split layout", value: "composite" },
+ { label: "Progressive PiP", value: "progressive" },
+ ]}
+ />
+ <div className="grid grid-cols-2 gap-2">
+ <ToolcraftNumberInputControl
+ label="Minimum shot"
+ size="sm"
+ value={minShotSeconds}
+ min={0}
+ max={30}
+ step={0.1}
+ unit="sec"
+ onChange={(value) => setMinShotSeconds(value ?? 0)}
+ />
+ <ToolcraftNumberInputControl
+ label="Maximum shot"
+ size="sm"
+ value={maxShotSeconds}
+ min={0}
+ max={120}
+ step={1}
+ unit="sec"
+ onChange={(value) => setMaxShotSeconds(value ?? 0)}
+ />
+ </div>
+ <Text type="supporting" color="secondary" className="block text-[9px] text-fg-3">
+ Maximum shot length triggers a listener reaction or wide reset.
+ </Text>
+ <label className="flex items-center gap-2 text-[9px] text-fg-2">
+ <input
+ type="checkbox"
+ checked={includeTranscripts}
+ onChange={(event) => setIncludeTranscripts(event.target.checked)}
+ />
+ Add per-channel local Whisper transcripts to the .orma artifact
+ </label>
+ <label className="flex items-center gap-2 text-[9px] text-fg-2">
+ <input
+ type="checkbox"
+ checked={includeVisualReactions}
+ onChange={(event) => setIncludeVisualReactions(event.target.checked)}
+ />
+ Add local MediaPipe face/reaction cues (slower)
+ </label>
+ </div>
+
{groups.length > 0 && (
<div className="space-y-2">
<span className="text-[10px] font-medium text-fg-2">
@@ -368,7 +1194,18 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
handleOffsetChange(group.id, angleId, offset)
}
onSync={() => handleSyncAudio(group.id)}
+ onAutoEdit={() => handleAutoEdit(group.id)}
+ onAcceptCut={(switchId) => handleAcceptCut(group.id, switchId)}
+ onRejectCut={(switchId) => handleRejectCut(group.id, switchId)}
+ onNudgeCut={(switchId, delta) => handleNudgeCut(group.id, switchId, delta)}
+ onExportOtio={() => handleExportOtio(group.id)}
+ onExportOrma={() => void handleExportOrma(group.id)}
+ onFindSocialClips={() => void handleFindSocialClips(group.id)}
+ onImportManifest={(file) => void handleImportManifest(group.id, file)}
+ onExportManifest={() => handleExportManifest(group.id)}
onDelete={() => handleDeleteGroup(group.id)}
+ isProcessing={processingGroupId === group.id}
+ status={groupStatus[group.id]}
/>
))}
</div>
@@ -450,7 +1287,7 @@ export const MultiCameraPanel: React.FC<MultiCameraPanelProps> = () => {
</div>
<Text type="supporting" color="secondary" className="text-[9px] text-fg-3 text-center">
- Switch angles during playback to create cuts
+ Automatic edits create an editable timeline track and undo in one step
</Text>
</div>
);
diff --git a/apps/web/src/components/editor/inspector/SpeedSection.tsx b/apps/web/src/components/editor/inspector/SpeedSection.tsx
index 6b344aed..3ebe361a 100644
--- a/apps/web/src/components/editor/inspector/SpeedSection.tsx
+++ b/apps/web/src/components/editor/inspector/SpeedSection.tsx
@@ -7,7 +7,7 @@ import { ToolcraftText as Text } from "@openreel/ui";
import { ToolcraftTextInputControl } from "@openreel/ui";
import { RotateCcw, Sparkles } from "@/icons/lucide-compat";
import type { Clip } from "@openreel/core";
-import { getSpeedEngine } from "@openreel/core";
+import { getMediaItemCapabilities, getSpeedEngine } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { MockToggle } from "./shell/InspectorControls";
@@ -49,19 +49,33 @@ export const SpeedSection: React.FC<SpeedSectionProps> = ({ clip }) => {
}, [currentSpeed]);
const hasAudio = () => {
- const audioTrack = project.timeline.tracks.find(
- (track) =>
- track.type === "audio" &&
- track.clips.some((audioClip) => audioClip.mediaId === clip.mediaId),
+ return project.timeline.tracks.some((track) =>
+ track.clips.some(
+ (audioClip) =>
+ audioClip.id !== clip.id &&
+ audioClip.mediaId === clip.mediaId &&
+ getMediaItemCapabilities(
+ project.mediaLibrary.items.find(
+ (item) => item.id === audioClip.mediaId,
+ ),
+ ).audio,
+ ),
);
- return !!audioTrack;
};
const linkedAudioClip = () => {
if (!affectAudio) return undefined;
for (const track of project.timeline.tracks) {
- if (track.type !== "audio") continue;
- const audioClip = track.clips.find((c) => c.mediaId === clip.mediaId);
+ const audioClip = track.clips.find(
+ (candidate) =>
+ candidate.id !== clip.id &&
+ candidate.mediaId === clip.mediaId &&
+ getMediaItemCapabilities(
+ project.mediaLibrary.items.find(
+ (item) => item.id === candidate.mediaId,
+ ),
+ ).audio,
+ );
if (audioClip) return audioClip;
}
return undefined;
diff --git a/apps/web/src/components/editor/inspector/StickerPickerPanel.test.tsx b/apps/web/src/components/editor/inspector/StickerPickerPanel.test.tsx
index bfe08b33..ab86765d 100644
--- a/apps/web/src/components/editor/inspector/StickerPickerPanel.test.tsx
+++ b/apps/web/src/components/editor/inspector/StickerPickerPanel.test.tsx
@@ -47,22 +47,26 @@ describe("StickerPickerPanel custom sticker workflow", () => {
expect(screen.getByText("spark added at 00:03:15")).toBeInTheDocument();
});
const state = useProjectStore.getState();
- const graphicsTrack = state.project.timeline.tracks.find(
- (track) => track.type === "graphics",
+ const placementTrack = state.project.timeline.tracks.find(
+ (track) => track.mode === "standard",
);
- expect(graphicsTrack).toBeDefined();
+ expect(placementTrack).toBeDefined();
const stickers =
useEngineStore.getState().getGraphicsEngine()?.getAllStickerClips() ?? [];
expect(stickers).toHaveLength(1);
expect(stickers[0]).toMatchObject({
name: "spark",
- trackId: graphicsTrack?.id,
+ trackId: placementTrack?.id,
startTime: 3.5,
duration: 5,
});
expect(stickers[0]?.imageUrl).toMatch(/^data:image\/png;base64,/);
expect(useUIStore.getState().getSelectedClipIds()).toEqual([stickers[0]?.id]);
expect(state.project.stickerClips).toHaveLength(1);
+
+ await state.undo();
+ expect(useProjectStore.getState().project.stickerClips).toHaveLength(0);
+ expect(useProjectStore.getState().project.timeline.tracks).toHaveLength(0);
});
it("rejects non-image files without changing the timeline", async () => {
@@ -80,9 +84,7 @@ describe("StickerPickerPanel custom sticker workflow", () => {
await screen.findByRole("alert"),
).toHaveTextContent("Choose a PNG, JPEG, WebP, GIF, or SVG image.");
expect(
- useProjectStore.getState().project.timeline.tracks.some(
- (track) => track.type === "graphics",
- ),
- ).toBe(false);
+ useProjectStore.getState().project.timeline.tracks,
+ ).toHaveLength(0);
});
});
diff --git a/apps/web/src/components/editor/inspector/StickerPickerPanel.tsx b/apps/web/src/components/editor/inspector/StickerPickerPanel.tsx
index 07f24457..9dfc8d64 100644
--- a/apps/web/src/components/editor/inspector/StickerPickerPanel.tsx
+++ b/apps/web/src/components/editor/inspector/StickerPickerPanel.tsx
@@ -8,6 +8,7 @@ import { ToolcraftTextInputControl } from "@openreel/ui";
import { useProjectStore } from "../../../stores/project-store";
import { useTimelineStore } from "../../../stores/timeline-store";
import { useUIStore } from "../../../stores/ui-store";
+import { insertTimelineOverlay } from "../../../stores/project/insert-timeline-overlay";
import {
stickerLibrary,
EMOJI_CATEGORIES,
@@ -67,7 +68,6 @@ const StickerCard: React.FC<StickerCardProps> = ({ sticker, onAdd }) => (
);
export const StickerPickerPanel: React.FC = () => {
- const addTrack = useProjectStore((state) => state.addTrack);
const project = useProjectStore((state) => state.project);
const createStickerClip = useProjectStore((state) => state.createStickerClip);
const playheadPosition = useTimelineStore((state) => state.playheadPosition);
@@ -98,71 +98,58 @@ export const StickerPickerPanel: React.FC = () => {
: stickerLibrary.getAllStickers();
const stickerCategories = stickerLibrary.getCategories();
- const ensureGraphicsTrack = useCallback(async () => {
- let graphicsTrack = useProjectStore
- .getState()
- .project.timeline.tracks.find(
- (t) => t.type === "graphics",
- );
- if (graphicsTrack) return graphicsTrack;
- const result = await addTrack("graphics");
- if (!result.success) return null;
- graphicsTrack = useProjectStore
- .getState()
- .project.timeline.tracks.find((track) => track.type === "graphics");
- return graphicsTrack ?? null;
- }, [addTrack]);
-
const handleAddEmoji = useCallback(
async (emoji: EmojiItem) => {
if (!project) return null;
- const graphicsTrack = await ensureGraphicsTrack();
-
- if (graphicsTrack) {
- const clip = stickerLibrary.createEmojiClip(
- emoji,
- graphicsTrack.id,
- playheadPosition,
- 5,
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ createStickerClip(
+ stickerLibrary.createEmojiClip(
+ emoji,
+ trackId,
+ playheadPosition,
+ 5,
+ ),
+ ),
+ );
+ if (created) {
+ select(
+ { type: "shape-clip", id: created.id, trackId: created.trackId },
+ false,
);
- const created = createStickerClip(clip);
- if (created) {
- select(
- { type: "shape-clip", id: created.id, trackId: graphicsTrack.id },
- false,
- );
- }
- return created;
}
- return null;
+ return created;
},
- [createStickerClip, ensureGraphicsTrack, playheadPosition, project, select],
+ [createStickerClip, playheadPosition, project, select],
);
const handleAddSticker = useCallback(
async (sticker: StickerItem) => {
if (!project) return null;
- const graphicsTrack = await ensureGraphicsTrack();
-
- if (graphicsTrack) {
- const clip = stickerLibrary.createStickerClip(
- sticker,
- graphicsTrack.id,
- playheadPosition,
- 5,
+ const created = await insertTimelineOverlay(
+ playheadPosition,
+ 5,
+ (trackId) =>
+ createStickerClip(
+ stickerLibrary.createStickerClip(
+ sticker,
+ trackId,
+ playheadPosition,
+ 5,
+ ),
+ ),
+ );
+ if (created) {
+ select(
+ { type: "shape-clip", id: created.id, trackId: created.trackId },
+ false,
);
- const created = createStickerClip(clip);
- if (created) {
- select(
- { type: "shape-clip", id: created.id, trackId: graphicsTrack.id },
- false,
- );
- }
- return created;
}
- return null;
+ return created;
},
- [createStickerClip, ensureGraphicsTrack, playheadPosition, project, select],
+ [createStickerClip, playheadPosition, project, select],
);
const handleImportSticker = useCallback(
diff --git a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
index c906f552..d3aed756 100644
--- a/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
+++ b/apps/web/src/components/editor/inspector/TextToSpeechPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useCallback } from "react";
+import React, { useState } from "react";
import {
Mic,
Loader2,
@@ -12,22 +12,20 @@ import { ToolcraftCard as Card } from "@openreel/ui";
import { ToolcraftIconButton as IconButton } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
import { ToolcraftTextAreaControl } from "@openreel/ui";
-import { PropertySlider } from "./shell/PropertySlider";
import { MockToggle } from "./shell/InspectorControls";
-import { toast } from "../../../stores/notification-store";
-import { useSettingsStore, type TtsProvider } from "../../../stores/settings-store";
+import { useSettingsStore } from "../../../stores/settings-store";
import { useElevenLabsApi } from "./hooks/useElevenLabsApi";
import { useTtsActions } from "./hooks/useTtsActions";
import { VoiceBrowser } from "./VoiceBrowser";
import { ModelSelector } from "./ModelSelector";
import { EnhancedTextPreview } from "./EnhancedTextPreview";
import { AudioResult } from "./AudioResult";
-import { TTS_PROVIDERS } from "./tts-constants";
export const TextToSpeechPanel: React.FC = () => {
const {
- defaultTtsProvider,
defaultLlmProvider,
+ llmBaseUrl,
+ llmModel,
openSettings,
settingsOpen,
configuredServices,
@@ -37,19 +35,10 @@ export const TextToSpeechPanel: React.FC = () => {
const hasElevenLabsKey = configuredServices.includes("elevenlabs");
- const defaultProvider: TtsProvider =
- defaultTtsProvider === "elevenlabs" && hasElevenLabsKey
- ? "elevenlabs"
- : "piper";
-
- const [provider, setProvider] = useState<TtsProvider>(defaultProvider);
const [text, setText] = useState("");
const [selectedVoice, setSelectedVoice] = useState<string>(
- defaultProvider === "elevenlabs" && favoriteVoices.length > 0
- ? favoriteVoices[0].voiceId
- : "amy",
+ favoriteVoices.length > 0 ? favoriteVoices[0].voiceId : "",
);
- const [speed, setSpeed] = useState(1.0);
const [error, setError] = useState<string | null>(null);
const [enhanceText, setEnhanceText] = useState(false);
const [enhancedPreview, setEnhancedPreview] = useState<string | null>(null);
@@ -60,14 +49,14 @@ export const TextToSpeechPanel: React.FC = () => {
isLoadingVoices,
isLoadingModels,
generateWithElevenLabs,
- generateWithPiper,
enhanceViaLlm,
} = useElevenLabsApi({
- provider,
hasElevenLabsKey,
settingsOpen,
elevenLabsModel,
defaultLlmProvider,
+ llmBaseUrl,
+ llmModel,
});
const {
@@ -86,18 +75,14 @@ export const TextToSpeechPanel: React.FC = () => {
saveToMedia,
addToTimeline,
downloadAudio,
- setGeneratedAudio,
} = useTtsActions({
- provider,
selectedVoice,
text,
- speed,
enhanceText,
enhancedPreview,
allVoices,
favoriteVoices,
generateWithElevenLabs,
- generateWithPiper,
enhanceViaLlm,
setText,
setError,
@@ -110,24 +95,6 @@ export const TextToSpeechPanel: React.FC = () => {
return elevenLabsModel;
};
- const warnUnsavedAudio = useCallback(() => {
- if (hasUnsavedAudio) {
- toast.warning("Unsaved audio discarded", "Save to media or download next time to keep it.");
- }
- }, [hasUnsavedAudio]);
-
- const handleProviderSwitch = useCallback((newProvider: TtsProvider) => {
- if (newProvider === provider) return;
- warnUnsavedAudio();
- setProvider(newProvider);
- setSelectedVoice(
- newProvider === "elevenlabs"
- ? (favoriteVoices.length > 0 ? favoriteVoices[0].voiceId : "")
- : "amy",
- );
- setGeneratedAudio(null);
- }, [provider, warnUnsavedAudio, favoriteVoices, setGeneratedAudio]);
-
const charCount = text.length;
const maxChars = 5000;
@@ -147,7 +114,7 @@ export const TextToSpeechPanel: React.FC = () => {
Text to Speech
</Text>
<Text type="supporting" color="secondary" display="block" className="text-[9px]">
- AI voice generation
+ User-keyed ElevenLabs voice generation
</Text>
</div>
</div>
@@ -161,35 +128,15 @@ export const TextToSpeechPanel: React.FC = () => {
/>
</Card>
- <div className="space-y-2">
- <Text type="supporting" color="secondary" weight="bold" className="block text-[10px]">
- Provider
- </Text>
- <div className="flex gap-1.5">
- {TTS_PROVIDERS.map((p) => {
- const isDisabled = p.id === "elevenlabs" && !hasElevenLabsKey;
- return (
- <Button
- key={p.id}
- label={p.label}
- variant={provider === p.id ? "primary" : "secondary"}
- size="sm"
- onClick={() => {
- if (isDisabled) {
- openSettings("api-keys");
- return;
- }
- handleProviderSwitch(p.id);
- }}
- isDisabled={false}
- className={`flex-1 text-[10px] ${isDisabled ? "opacity-60" : ""}`}
- />
- );
- })}
- </div>
- </div>
+ {!hasElevenLabsKey && (
+ <Card variant="yellow" padding={2} className="border border-amber-500/30">
+ <Text type="supporting" className="text-[10px] text-amber-400">
+ Add your ElevenLabs API key to enable speech generation. OpenReel no longer hosts a speech server.
+ </Text>
+ </Card>
+ )}
- {provider === "elevenlabs" && hasElevenLabsKey && (
+ {hasElevenLabsKey && (
<ModelSelector allModels={allModels} isLoadingModels={isLoadingModels} />
)}
@@ -207,26 +154,22 @@ export const TextToSpeechPanel: React.FC = () => {
width="100%"
/>
<div className="flex items-center justify-between">
- {provider === "elevenlabs" ? (
- <div className="flex items-center gap-1.5">
- <MockToggle
- ariaLabel="Enhance for TTS"
- checked={enhanceText}
- onChange={setEnhanceText}
- />
- <Text
- type="supporting"
- color="secondary"
- className="flex items-center gap-1 text-[9px] cursor-pointer"
- onClick={() => setEnhanceText(!enhanceText)}
- >
- <Sparkles size={10} className={enhanceText ? "text-amber-400" : ""} aria-hidden />
- Enhance for TTS
- </Text>
- </div>
- ) : (
- <div />
- )}
+ <div className="flex items-center gap-1.5">
+ <MockToggle
+ ariaLabel="Enhance for TTS"
+ checked={enhanceText}
+ onChange={setEnhanceText}
+ />
+ <Text
+ type="supporting"
+ color="secondary"
+ className="flex items-center gap-1 text-[9px] cursor-pointer"
+ onClick={() => setEnhanceText(!enhanceText)}
+ >
+ <Sparkles size={10} className={enhanceText ? "text-amber-400" : ""} aria-hidden />
+ Enhance for TTS
+ </Text>
+ </div>
<Text
type="supporting"
className={`text-[9px] ${charCount > maxChars * 0.9 ? "text-red-400" : "text-fg-3"}`}
@@ -245,32 +188,12 @@ export const TextToSpeechPanel: React.FC = () => {
</div>
<VoiceBrowser
- provider={provider}
selectedVoice={selectedVoice}
onSelectVoice={setSelectedVoice}
allVoices={allVoices}
isLoadingVoices={isLoadingVoices}
/>
- {provider === "piper" && (
- <div className="space-y-2">
- <PropertySlider
- label="Speed"
- min={0.5}
- max={2.0}
- step={0.1}
- value={speed}
- onChange={(value: number) => setSpeed(value)}
- formatValue={(value) => `${value.toFixed(1)}x`}
- />
- <div className="flex justify-between">
- <Text type="supporting" color="secondary" className="text-[8px]">0.5x</Text>
- <Text type="supporting" color="secondary" className="text-[8px]">1.0x</Text>
- <Text type="supporting" color="secondary" className="text-[8px]">2.0x</Text>
- </div>
- </div>
- )}
-
{error && (
<Card
variant="red"
@@ -300,7 +223,7 @@ export const TextToSpeechPanel: React.FC = () => {
</Card>
)}
- {enhanceText && provider === "elevenlabs" && !enhancedPreview && (
+ {enhanceText && !enhancedPreview && (
<Button
label={isEnhancing ? "Enhancing..." : "Enhance Text"}
icon={
@@ -331,7 +254,7 @@ export const TextToSpeechPanel: React.FC = () => {
variant="primary"
size="md"
onClick={generateSpeech}
- isDisabled={isGenerating || !text.trim() || (provider === "elevenlabs" && !selectedVoice) || (enhanceText && provider === "elevenlabs" && !enhancedPreview)}
+ isDisabled={isGenerating || !hasElevenLabsKey || !text.trim() || !selectedVoice || (enhanceText && !enhancedPreview)}
isLoading={isGenerating}
className="w-full"
/>
@@ -363,8 +286,7 @@ export const TextToSpeechPanel: React.FC = () => {
)}
<Text type="supporting" color="secondary" className="block text-[9px] text-center">
- Powered by {provider === "elevenlabs" ? "ElevenLabs" : "Piper TTS"}
- {provider === "elevenlabs" && ` · ${getSelectedModelName()}`}
+ Powered by ElevenLabs · {getSelectedModelName()}
</Text>
</div>
);
diff --git a/apps/web/src/components/editor/inspector/VoiceBrowser.tsx b/apps/web/src/components/editor/inspector/VoiceBrowser.tsx
index d0ca92f4..764f1f62 100644
--- a/apps/web/src/components/editor/inspector/VoiceBrowser.tsx
+++ b/apps/web/src/components/editor/inspector/VoiceBrowser.tsx
@@ -7,7 +7,6 @@ import {
StarOff,
ChevronDown,
Loader2,
- User,
Settings,
} from "@/icons/lucide-compat";
import { ToolcraftButton as Button } from "@openreel/ui";
@@ -15,13 +14,10 @@ import { ToolcraftIconButton as IconButton } from "@openreel/ui";
import { ToolcraftSelectableCard as SelectableCard } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
import { ToolcraftTextInputControl } from "@openreel/ui";
-import type { TtsProvider } from "../../../stores/settings-store";
import { useSettingsStore } from "../../../stores/settings-store";
import type { ElevenLabsVoice } from "./tts-types";
-import { PIPER_VOICES } from "./tts-constants";
interface VoiceBrowserProps {
- provider: TtsProvider;
selectedVoice: string;
onSelectVoice: (voiceId: string) => void;
allVoices: ElevenLabsVoice[];
@@ -29,7 +25,6 @@ interface VoiceBrowserProps {
}
export const VoiceBrowser: React.FC<VoiceBrowserProps> = ({
- provider,
selectedVoice,
onSelectVoice,
allVoices,
@@ -116,38 +111,6 @@ export const VoiceBrowser: React.FC<VoiceBrowserProps> = ({
});
}, [allVoices, voiceSearch]);
- if (provider === "piper") {
- return (
- <div className="space-y-2">
- <Text type="label" color="secondary" weight="medium" className="text-[10px] text-fg-2">
- Voice
- </Text>
- <div className="flex flex-wrap gap-1.5">
- {PIPER_VOICES.map((voice) => (
- <SelectableCard
- key={voice.id}
- label={voice.name}
- isSelected={selectedVoice === voice.id}
- onChange={() => onSelectVoice(voice.id)}
- onClick={() => onSelectVoice(voice.id)}
- padding={2}
- variant={selectedVoice === voice.id ? "green" : "muted"}
- className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[10px] transition-colors ${
- selectedVoice === voice.id
- ? "bg-primary text-white font-medium"
- : "bg-bg-2 text-fg-2 hover:text-fg border border-border"
- }`}
- >
- <User size={10} />
- <span>{voice.name}</span>
- <span className="text-[8px] opacity-70">{voice.gender === "female" ? "F" : "M"}</span>
- </SelectableCard>
- ))}
- </div>
- </div>
- );
- }
-
return (
<div className="space-y-2">
<Text type="label" color="secondary" weight="medium" className="text-[10px] text-fg-2">
diff --git a/apps/web/src/components/editor/inspector/hooks/useElevenLabsApi.ts b/apps/web/src/components/editor/inspector/hooks/useElevenLabsApi.ts
index 32112f53..03a0d920 100644
--- a/apps/web/src/components/editor/inspector/hooks/useElevenLabsApi.ts
+++ b/apps/web/src/components/editor/inspector/hooks/useElevenLabsApi.ts
@@ -1,18 +1,18 @@
import { useState, useCallback, useRef, useEffect } from "react";
-import type { TtsProvider } from "../../../../stores/settings-store";
+import type { LlmProvider } from "../../../../stores/settings-store";
import { useSettingsStore } from "../../../../stores/settings-store";
import { isSessionUnlocked, getSecret } from "../../../../services/secure-storage";
import { apiFetch } from "../../../../services/api-proxy";
-import { OPENREEL_TTS_URL } from "../../../../config/api-endpoints";
import type { ElevenLabsVoice, ElevenLabsModel } from "../tts-types";
import { FALLBACK_MODELS, ENHANCE_SYSTEM_PROMPT } from "../tts-constants";
interface UseElevenLabsApiOptions {
- provider: TtsProvider;
hasElevenLabsKey: boolean;
settingsOpen: boolean;
elevenLabsModel: string;
- defaultLlmProvider: string;
+ defaultLlmProvider: LlmProvider | null;
+ llmBaseUrl: string;
+ llmModel: string;
}
interface UseElevenLabsApiReturn {
@@ -21,18 +21,25 @@ interface UseElevenLabsApiReturn {
isLoadingVoices: boolean;
isLoadingModels: boolean;
generateWithElevenLabs: (text: string, voiceId: string, signal?: AbortSignal) => Promise<Blob>;
- generateWithPiper: (text: string, voice: string, speed: number, signal?: AbortSignal) => Promise<Blob>;
enhanceViaLlm: (text: string, signal?: AbortSignal) => Promise<string>;
}
export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLabsApiReturn {
- const { provider, hasElevenLabsKey, settingsOpen, elevenLabsModel, defaultLlmProvider } = options;
+ const {
+ hasElevenLabsKey,
+ settingsOpen,
+ elevenLabsModel,
+ defaultLlmProvider,
+ llmBaseUrl,
+ llmModel,
+ } = options;
const isDesktop = typeof window !== "undefined" && window.openreel?.platform === "desktop";
const {
cachedElevenLabsVoices,
cachedElevenLabsModels,
+ configuredServices,
setCachedElevenLabsVoices,
setCachedElevenLabsModels,
} = useSettingsStore();
@@ -118,23 +125,23 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
}, [cachedElevenLabsVoices, setCachedElevenLabsVoices, isDesktop]);
useEffect(() => {
- if (provider === "elevenlabs" && hasElevenLabsKey) {
+ if (hasElevenLabsKey) {
const signal = getSignal();
if (allVoices.length === 0) fetchVoices(signal);
if (allModels.length === 0) fetchModels(signal);
}
- }, [provider, hasElevenLabsKey, allVoices.length, allModels.length, fetchVoices, fetchModels, getSignal]);
+ }, [hasElevenLabsKey, allVoices.length, allModels.length, fetchVoices, fetchModels, getSignal]);
useEffect(() => {
if (prevSettingsOpen.current && !settingsOpen) {
- if (provider === "elevenlabs" && hasElevenLabsKey && isSessionUnlocked()) {
+ if (hasElevenLabsKey && isSessionUnlocked()) {
const signal = getSignal();
if (allVoices.length === 0) fetchVoices(signal);
if (allModels.length === 0) fetchModels(signal);
}
}
prevSettingsOpen.current = settingsOpen;
- }, [settingsOpen, provider, hasElevenLabsKey, allVoices.length, allModels.length, fetchVoices, fetchModels, getSignal]);
+ }, [settingsOpen, hasElevenLabsKey, allVoices.length, allModels.length, fetchVoices, fetchModels, getSignal]);
useEffect(() => {
return () => {
@@ -144,34 +151,6 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
};
}, []);
- useEffect(() => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- abortControllerRef.current = null;
- }
- }, [provider]);
-
- const generateWithPiper = useCallback(async (inputText: string, voice: string, spd: number, signal?: AbortSignal): Promise<Blob> => {
- const response = await fetch(`${OPENREEL_TTS_URL}/tts`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ text: inputText, voice, speed: spd }),
- signal,
- });
-
- if (!response.ok) {
- if (response.status === 429) {
- throw new Error(
- "Rate limit reached. Please wait a minute. Free service is limited to 10 req/min.",
- );
- }
- const errorData = await response.json().catch(() => ({}));
- throw new Error(errorData.detail || errorData.error || "Failed to generate speech");
- }
-
- return response.blob();
- }, []);
-
const generateWithElevenLabs = useCallback(async (inputText: string, voiceId: string, signal?: AbortSignal): Promise<Blob> => {
if (!isSessionUnlocked()) {
throw new Error("Session locked. Unlock in Settings > API Keys first.");
@@ -211,26 +190,32 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
const enhanceViaLlm = useCallback(async (inputText: string, signal?: AbortSignal): Promise<string> => {
const llmProvider = defaultLlmProvider;
+ const selectedModel = llmModel.trim();
+ if (!llmProvider || !llmBaseUrl.trim() || !selectedModel) {
+ throw new Error("Configure an AI endpoint and model before using text enhancement.");
+ }
+ const compatibleKeyConfigured = configuredServices.includes(llmProvider);
- if (!isSessionUnlocked()) {
+ if (compatibleKeyConfigured && !isSessionUnlocked()) {
throw new Error("Session locked. Unlock in Settings > API Keys to use text enhancement.");
}
- const apiKey = isDesktop ? "" : (await getSecret(llmProvider)) ?? "";
- if (!isDesktop && !apiKey) {
- throw new Error(`${llmProvider === "openai" ? "OpenAI" : "Anthropic"} API key not found. Add it in Settings > API Keys.`);
- }
+ const apiKey =
+ isDesktop || (!compatibleKeyConfigured && !isSessionUnlocked())
+ ? ""
+ : (await getSecret(llmProvider)) ?? "";
- if (llmProvider === "anthropic") {
- const response = await apiFetch("anthropic", "/messages", apiKey, {
+ if (llmProvider === "anthropic-compatible") {
+ const response = await apiFetch(llmProvider, "/messages", apiKey, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- model: "claude-sonnet-4-20250514",
+ model: selectedModel,
max_tokens: 2048,
system: ENHANCE_SYSTEM_PROMPT,
messages: [{ role: "user", content: inputText }],
}),
+ baseUrl: llmBaseUrl,
signal,
});
@@ -246,19 +231,24 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
return content?.[0]?.text ?? inputText;
}
- const response = await apiFetch("openai", "/chat/completions", apiKey, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- model: "gpt-4o-mini",
- messages: [
- { role: "system", content: ENHANCE_SYSTEM_PROMPT },
- { role: "user", content: inputText },
- ],
- max_tokens: 2048,
- }),
- signal,
- });
+ const response = await apiFetch(
+ llmProvider,
+ "/chat/completions",
+ apiKey,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ model: selectedModel,
+ messages: [
+ { role: "system", content: ENHANCE_SYSTEM_PROMPT },
+ { role: "user", content: inputText },
+ ],
+ }),
+ baseUrl: llmBaseUrl,
+ signal,
+ },
+ );
if (!response.ok) {
const err = await response.json().catch(() => ({}));
@@ -269,7 +259,13 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
const data = await response.json();
const choices = (data as { choices: Array<{ message: { content: string } }> }).choices;
return choices?.[0]?.message?.content ?? inputText;
- }, [defaultLlmProvider, isDesktop]);
+ }, [
+ configuredServices,
+ defaultLlmProvider,
+ isDesktop,
+ llmBaseUrl,
+ llmModel,
+ ]);
return {
allVoices,
@@ -277,7 +273,6 @@ export function useElevenLabsApi(options: UseElevenLabsApiOptions): UseElevenLab
isLoadingVoices,
isLoadingModels,
generateWithElevenLabs,
- generateWithPiper,
enhanceViaLlm,
};
}
diff --git a/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts b/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
index 2cc76a68..ac221aa9 100644
--- a/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
+++ b/apps/web/src/components/editor/inspector/hooks/useTtsActions.ts
@@ -1,21 +1,16 @@
import { useState, useCallback, useRef, useEffect } from "react";
-import type { TtsProvider } from "../../../../stores/settings-store";
import { useProjectStore } from "../../../../stores/project-store";
import { useTtsAudioStore } from "../../../../stores/tts-store";
-import { PIPER_VOICES } from "../tts-constants";
import type { ElevenLabsVoice } from "../tts-types";
interface UseTtsActionsOptions {
- provider: TtsProvider;
selectedVoice: string;
text: string;
- speed: number;
enhanceText: boolean;
enhancedPreview: string | null;
allVoices: ElevenLabsVoice[];
favoriteVoices: Array<{ voiceId: string; name: string; previewUrl?: string }>;
generateWithElevenLabs: (text: string, voiceId: string, signal?: AbortSignal) => Promise<Blob>;
- generateWithPiper: (text: string, voice: string, speed: number, signal?: AbortSignal) => Promise<Blob>;
enhanceViaLlm: (text: string, signal?: AbortSignal) => Promise<string>;
setText: (text: string) => void;
setError: (error: string | null) => void;
@@ -43,16 +38,13 @@ interface UseTtsActionsReturn {
export function useTtsActions(options: UseTtsActionsOptions): UseTtsActionsReturn {
const {
- provider,
selectedVoice,
text,
- speed,
enhanceText,
enhancedPreview,
allVoices,
favoriteVoices,
generateWithElevenLabs,
- generateWithPiper,
enhanceViaLlm,
setText,
setError,
@@ -120,15 +112,12 @@ export function useTtsActions(options: UseTtsActionsOptions): UseTtsActionsRetur
}, [storeSetAudio, storeClearAudio]);
const getSelectedVoiceName = useCallback((): string => {
- if (provider === "piper") {
- return PIPER_VOICES.find((v) => v.id === selectedVoice)?.name ?? "TTS";
- }
const fav = favoriteVoices.find((v) => v.voiceId === selectedVoice);
if (fav) return fav.name;
const apiVoice = allVoices.find((v) => v.voice_id === selectedVoice);
if (apiVoice) return apiVoice.name;
return "TTS";
- }, [provider, selectedVoice, favoriteVoices, allVoices]);
+ }, [selectedVoice, favoriteVoices, allVoices]);
const handleEnhance = useCallback(async () => {
if (!text.trim()) {
@@ -170,9 +159,7 @@ export function useTtsActions(options: UseTtsActionsOptions): UseTtsActionsRetur
try {
const finalText = (enhanceText && enhancedPreview) ? enhancedPreview : text.trim();
- const blob = provider === "elevenlabs"
- ? await generateWithElevenLabs(finalText, selectedVoice, controller.signal)
- : await generateWithPiper(finalText, selectedVoice, speed, controller.signal);
+ const blob = await generateWithElevenLabs(finalText, selectedVoice, controller.signal);
storeSetAudio(blob);
@@ -186,7 +173,7 @@ export function useTtsActions(options: UseTtsActionsOptions): UseTtsActionsRetur
} finally {
setIsGenerating(false);
}
- }, [text, enhancedPreview, enhanceText, selectedVoice, speed, provider, generateWithPiper, generateWithElevenLabs, setError, storeSetAudio]);
+ }, [text, enhancedPreview, enhanceText, selectedVoice, generateWithElevenLabs, setError, storeSetAudio]);
const togglePlayback = useCallback(() => {
if (!audioRef.current || !audioUrl) return;
diff --git a/apps/web/src/components/editor/inspector/multicam-workflow.test.ts b/apps/web/src/components/editor/inspector/multicam-workflow.test.ts
new file mode 100644
index 00000000..f8eec2e0
--- /dev/null
+++ b/apps/web/src/components/editor/inspector/multicam-workflow.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it } from "vitest";
+import {
+ ActionExecutor,
+ type Clip,
+ type MediaItem,
+ type MultiCamGroup,
+ type Project,
+} from "@openreel/core";
+import {
+ createMulticamApplyEditAction,
+ buildMulticamManifest,
+ findMulticamCalibrationRanges,
+ getMulticamAnalysisDuration,
+ prepareMulticamAnalysisAudio,
+ resolveMulticamSources,
+ updateAlignedSourceOffsets,
+} from "./multicam-workflow";
+
+const transform = {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+};
+
+function clip(id: string, trackId: string, mediaId: string): Clip {
+ return {
+ id,
+ trackId,
+ mediaId,
+ startTime: 2,
+ duration: 8,
+ inPoint: 0,
+ outPoint: 8,
+ effects: [],
+ audioEffects: [],
+ transform,
+ volume: 1,
+ keyframes: [],
+ };
+}
+
+function media(id: string): MediaItem {
+ return {
+ id,
+ name: id,
+ type: "video",
+ fileHandle: null,
+ blob: new Blob([id]),
+ metadata: {
+ duration: 8,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ };
+}
+
+const group: MultiCamGroup = {
+ id: "group-1",
+ name: "Interview",
+ angles: [
+ {
+ id: "a",
+ name: "Host",
+ clipId: "clip-a",
+ trackId: "source-a",
+ offset: 0,
+ color: "#f00",
+ isActive: true,
+ },
+ {
+ id: "b",
+ name: "Guest",
+ clipId: "clip-b",
+ trackId: "source-b",
+ offset: 0.5,
+ color: "#0f0",
+ isActive: false,
+ },
+ ],
+ activeAngleId: "a",
+ syncPoint: 2,
+ duration: 6,
+ createdAt: 1,
+ outputTrackId: "output-1",
+ switches: [],
+};
+
+function project(): Project {
+ return {
+ id: "project-1",
+ name: "Podcast",
+ createdAt: 1,
+ modifiedAt: 1,
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48_000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [media("media-a"), media("media-b")] },
+ timeline: {
+ duration: 10,
+ subtitles: [],
+ markers: [],
+ tracks: [
+ {
+ id: "source-a",
+ type: "video",
+ name: "Host",
+ clips: [clip("clip-a", "source-a", "media-a")],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ {
+ id: "source-b",
+ type: "video",
+ name: "Guest",
+ clips: [clip("clip-b", "source-b", "media-b")],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ },
+ multicamGroups: [],
+ };
+}
+
+describe("multicam workflow", () => {
+ it("downmixes and decimates analysis audio before long-form processing", () => {
+ const left = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8]);
+ const right = new Float32Array([3, 4, 5, 6, 7, 8, 9, 10]);
+ const buffer = {
+ length: 8,
+ numberOfChannels: 2,
+ sampleRate: 8_000,
+ getChannelData: (channel: number) => (channel === 0 ? left : right),
+ } as AudioBuffer;
+
+ const analysis = prepareMulticamAnalysisAudio(buffer, 2_000);
+
+ expect(analysis.sampleRate).toBe(2_000);
+ expect(Array.from(analysis.samples)).toEqual([2, 6]);
+ });
+
+ it("resolves each angle to its clip, track, and media", () => {
+ const resolved = resolveMulticamSources(project(), group);
+
+ expect(resolved.map(({ angle, clip, media, track }) => ({
+ angle: angle.id,
+ clip: clip.id,
+ media: media.id,
+ track: track.id,
+ }))).toEqual([
+ { angle: "a", clip: "clip-a", media: "media-a", track: "source-a" },
+ { angle: "b", clip: "clip-b", media: "media-b", track: "source-b" },
+ ]);
+ });
+
+ it("uses the shortest aligned source as the analysis duration", () => {
+ const resolved = resolveMulticamSources(project(), group);
+ const buffers = new Map([
+ ["a", { duration: 8 } as AudioBuffer],
+ ["b", { duration: 7 } as AudioBuffer],
+ ]);
+
+ expect(getMulticamAnalysisDuration(resolved, buffers)).toBe(6.5);
+ });
+
+ it("translates raw sync offsets into each trimmed clip's source window", () => {
+ const target = project();
+ const targetClip = target.timeline.tracks[1]?.clips[0] as Clip;
+ (targetClip as { inPoint: number }).inPoint = 2;
+ const resolved = resolveMulticamSources(target, group);
+ const liveGroup = structuredClone(group);
+
+ updateAlignedSourceOffsets(
+ liveGroup,
+ resolved,
+ new Map([
+ ["a", { offset: 0, confidence: 1, method: "audio" as const }],
+ ["b", { offset: 3, confidence: 0.9, method: "audio" as const }],
+ ]),
+ );
+
+ expect(liveGroup.angles[1]?.offset).toBe(1);
+ });
+
+ it("builds a v1 shoot manifest from the selected camera sources", () => {
+ const target = project();
+ const resolved = resolveMulticamSources(target, group);
+ const value = buildMulticamManifest(target, group, resolved, {
+ min_shot_ms: 1_800,
+ max_shot_ms: 25_000,
+ cut_lead_ms: 120,
+ reaction_shot_after_ms: 12_000,
+ forbid_jump_cut_same_subject: true,
+ });
+
+ expect(value.spec).toBe("openreel-multicam/v1");
+ expect(value.participants.map((participant) => participant.audio)).toEqual(["a", "b"]);
+ expect(value.cameras.map((camera) => camera.clipId)).toEqual(["clip-a", "clip-b"]);
+ });
+
+ it("finds isolated speaker and room-silence calibration windows", () => {
+ const value = findMulticamCalibrationRanges(new Map([
+ ["a", { windowMs: 250, probabilities: new Float32Array([0.1, 0.1, 0.9, 0.9, 0.9, 0.1]) }],
+ ["b", { windowMs: 250, probabilities: new Float32Array([0.1, 0.1, 0.1, 0.1, 0.1, 0.9]) }],
+ ]));
+
+ expect(value.silenceRange).toEqual({ startTime: 0, endTime: 0.5 });
+ expect(value.ranges).toContainEqual({ speakerAngleId: "a", startTime: 0.5, endTime: 1.25 });
+ });
+
+ it("applies and undoes the generated timeline as one atomic action", async () => {
+ const target = project();
+ const outputClip = {
+ ...clip("generated", "output-1", "media-a"),
+ startTime: 2,
+ duration: 3,
+ outPoint: 3,
+ };
+ const action = createMulticamApplyEditAction({
+ project: target,
+ group,
+ groups: [{ ...group, switches: [{ id: "s1", groupId: group.id, angleId: "a", time: 0 }] }],
+ outputTrackId: "output-1",
+ sequence: [{ angleId: "a", clip: outputClip }],
+ createId: () => "action-1",
+ now: () => 10,
+ });
+ const executor = new ActionExecutor();
+ expect((await executor.execute(action, target)).success).toBe(true);
+
+ expect(target.timeline.tracks.find((track) => track.id === "source-a")).toMatchObject({
+ hidden: true,
+ muted: true,
+ });
+ expect(target.timeline.tracks.find((track) => track.id === "output-1")?.clips).toHaveLength(1);
+ expect(target.multicamGroups?.[0]?.switches).toHaveLength(1);
+
+ const undo = await executor.undo(target);
+
+ expect(undo.success).toBe(true);
+ expect(target.timeline.tracks.map((track) => track.id)).toEqual(["source-a", "source-b"]);
+ expect(target.timeline.tracks.every((track) => !track.hidden && !track.muted)).toBe(true);
+ expect(target.multicamGroups).toEqual([]);
+ });
+});
diff --git a/apps/web/src/components/editor/inspector/multicam-workflow.ts b/apps/web/src/components/editor/inspector/multicam-workflow.ts
new file mode 100644
index 00000000..3b36d3de
--- /dev/null
+++ b/apps/web/src/components/editor/inspector/multicam-workflow.ts
@@ -0,0 +1,396 @@
+import type {
+ Action,
+ CameraAngle,
+ Clip,
+ MediaItem,
+ MultiCamGroup,
+ MulticamSequenceClip,
+ Project,
+ SyncResult,
+ Track,
+ MulticamDriftModel,
+ MulticamManifest,
+ MulticamManifestConstraints,
+ MulticamVadTrack,
+ MulticamCalibrationRange,
+} from "@openreel/core";
+
+export interface MulticamSyncAnalysis {
+ results: Map<string, SyncResult>;
+ drift: Record<string, MulticamDriftModel>;
+}
+
+export interface ResolvedMulticamSource {
+ angle: CameraAngle;
+ clip: Clip;
+ media: MediaItem;
+ track: Track;
+}
+
+export function resolveMulticamSources(
+ project: Project,
+ group: MultiCamGroup,
+): ResolvedMulticamSource[] {
+ return group.angles.map((angle) => {
+ const track = project.timeline.tracks.find((candidate) =>
+ candidate.clips.some((clip) => clip.id === angle.clipId),
+ );
+ const clip = track?.clips.find((candidate) => candidate.id === angle.clipId);
+ if (!track || !clip) {
+ throw new Error(`${angle.name} is no longer available on the timeline.`);
+ }
+ const media = project.mediaLibrary.items.find((item) => item.id === clip.mediaId);
+ if (!media) {
+ throw new Error(`${angle.name} is missing its source media.`);
+ }
+ return { angle, clip, media, track };
+ });
+}
+
+export function prepareMulticamAnalysisAudio(
+ buffer: AudioBuffer,
+ targetSampleRate = 2_000,
+): { samples: Float32Array; sampleRate: number } {
+ const stride = Math.max(1, Math.floor(buffer.sampleRate / targetSampleRate));
+ const samples = new Float32Array(Math.ceil(buffer.length / stride));
+ const channelCount = Math.max(1, buffer.numberOfChannels);
+ for (let channel = 0; channel < buffer.numberOfChannels; channel++) {
+ const channelData = buffer.getChannelData(channel);
+ for (let index = 0; index < samples.length; index++) {
+ samples[index] += (channelData[index * stride] ?? 0) / channelCount;
+ }
+ }
+ return { samples, sampleRate: buffer.sampleRate / stride };
+}
+
+export function buildMulticamManifest(
+ project: Project,
+ group: MultiCamGroup,
+ sources: readonly ResolvedMulticamSource[],
+ constraints: MulticamManifestConstraints,
+): MulticamManifest {
+ const participantAngles = group.angles.filter(
+ (angle) => !/\bwide\b/i.test(angle.name),
+ );
+ const participants = participantAngles.map((angle, index) => ({
+ id: `participant-${angle.id}`,
+ name: angle.name,
+ audio: angle.id,
+ seat: index,
+ }));
+ const participantByAngle = new Map(
+ participantAngles.map((angle, index) => [angle.id, participants[index]!.id]),
+ );
+ const cameras = group.angles.map((angle) => {
+ const source = sources.find((entry) => entry.angle.id === angle.id);
+ const isWide = /\bwide\b/i.test(angle.name);
+ return {
+ id: angle.id,
+ type: isWide ? "wide" as const : "closeup" as const,
+ subject: isWide ? "all" : (participantByAngle.get(angle.id) ?? "all"),
+ file: source?.media.sourceFile?.name ?? source?.media.name ?? angle.name,
+ clipId: angle.clipId,
+ angleId: angle.id,
+ };
+ });
+ const reference = cameras.find((camera) => camera.type === "wide")?.id ?? cameras[0]?.id ?? "";
+ return {
+ spec: "openreel-multicam/v1",
+ fps: project.settings.frameRate,
+ sync: { method: "audio-crosscorr", reference },
+ participants,
+ cameras,
+ constraints,
+ };
+}
+
+export function findMulticamCalibrationRanges(
+ tracks: ReadonlyMap<string, MulticamVadTrack>,
+ options: { speakingThreshold?: number; quietThreshold?: number; minimumMs?: number } = {},
+): {
+ ranges: MulticamCalibrationRange[];
+ silenceRange?: { startTime: number; endTime: number };
+} {
+ const speakingThreshold = options.speakingThreshold ?? 0.7;
+ const quietThreshold = options.quietThreshold ?? 0.3;
+ const minimumMs = options.minimumMs ?? 500;
+ const entries = [...tracks.entries()];
+ const windowMs = Math.min(...entries.map(([, track]) => track.windowMs));
+ if (!entries.length || !Number.isFinite(windowMs)) return { ranges: [] };
+ const count = Math.min(
+ ...entries.map(([, track]) => Math.floor(track.probabilities.length * track.windowMs / windowMs)),
+ );
+ const ranges: MulticamCalibrationRange[] = [];
+ let silenceStart: number | undefined;
+ let silenceRange: { startTime: number; endTime: number } | undefined;
+ const activeRuns = new Map<string, number>();
+ for (let index = 0; index <= count; index++) {
+ const probabilities = new Map(entries.map(([id, track]) => [
+ id,
+ track.probabilities[Math.floor((index * windowMs) / track.windowMs)] ?? 0,
+ ]));
+ const alone = entries.find(([id]) =>
+ (probabilities.get(id) ?? 0) >= speakingThreshold &&
+ entries.every(([other]) => other === id || (probabilities.get(other) ?? 0) <= quietThreshold),
+ )?.[0];
+ for (const [id] of entries) {
+ const start = activeRuns.get(id);
+ if (alone === id && start === undefined) activeRuns.set(id, index);
+ if (alone !== id && start !== undefined) {
+ if ((index - start) * windowMs >= minimumMs) {
+ ranges.push({ speakerAngleId: id, startTime: start * windowMs / 1_000, endTime: index * windowMs / 1_000 });
+ }
+ activeRuns.delete(id);
+ }
+ }
+ const silent = entries.every(([, track]) =>
+ (track.probabilities[Math.floor((index * windowMs) / track.windowMs)] ?? 0) <= quietThreshold,
+ );
+ if (silent && silenceStart === undefined) silenceStart = index;
+ if ((!silent || index === count) && silenceStart !== undefined) {
+ if (!silenceRange && (index - silenceStart) * windowMs >= minimumMs) {
+ silenceRange = { startTime: silenceStart * windowMs / 1_000, endTime: index * windowMs / 1_000 };
+ }
+ silenceStart = undefined;
+ }
+ }
+ return { ranges, silenceRange };
+}
+
+export async function analyzeMulticamSyncInWorker(
+ buffers: ReadonlyMap<string, AudioBuffer>,
+ referenceAngleId: string,
+): Promise<MulticamSyncAnalysis> {
+ const referenceBuffer = buffers.get(referenceAngleId);
+ if (!referenceBuffer) throw new Error("The multicam reference audio is missing.");
+ const reference = prepareMulticamAnalysisAudio(referenceBuffer, 1_000);
+ const results = new Map<string, SyncResult>();
+ const drift: Record<string, MulticamDriftModel> = {};
+ results.set(referenceAngleId, { offset: 0, confidence: 1, method: "audio" });
+ for (const [angleId, buffer] of buffers) {
+ if (angleId === referenceAngleId) continue;
+ const target = prepareMulticamAnalysisAudio(buffer, 1_000);
+ const duration = Math.min(reference.samples.length, target.samples.length) / reference.sampleRate;
+ const maxOffsetSeconds = Math.max(0.05, Math.min(30, (duration - 1) / 2));
+ const worker = new Worker(
+ new URL("../../../workers/multicam-analysis-worker.ts", import.meta.url),
+ { type: "module" },
+ );
+ const requestId = crypto.randomUUID();
+ const model = await new Promise<MulticamDriftModel>((resolve, reject) => {
+ worker.onmessage = (event: MessageEvent<{ requestId: string; type: string; model?: MulticamDriftModel; message?: string }>) => {
+ if (event.data.requestId !== requestId) return;
+ worker.terminate();
+ if (event.data.type === "result" && event.data.model) resolve(event.data.model);
+ else reject(new Error(event.data.message ?? "Audio synchronization failed."));
+ };
+ worker.onerror = (event) => {
+ worker.terminate();
+ reject(new Error(event.message || "Audio synchronization worker failed."));
+ };
+ worker.postMessage({
+ requestId,
+ type: "drift",
+ reference: reference.samples,
+ target: target.samples,
+ sampleRate: reference.sampleRate,
+ options: { blockSeconds: Math.min(5, Math.max(1, duration / 3)), intervalSeconds: 300, maxOffsetSeconds, analysisSampleRate: 400 },
+ });
+ });
+ drift[angleId] = model;
+ results.set(angleId, {
+ offset: model.interceptSeconds,
+ confidence: model.confidence,
+ method: model.confidence > 0 ? "audio" : "manual",
+ });
+ }
+ return { results, drift };
+}
+
+export function getMulticamAnalysisDuration(
+ sources: readonly ResolvedMulticamSource[],
+ buffers: ReadonlyMap<string, AudioBuffer>,
+): number {
+ if (sources.length === 0) return 0;
+ return sources.reduce((duration, source) => {
+ const buffer = buffers.get(source.angle.id);
+ if (!buffer) return 0;
+ const playbackRate = Math.max(0.01, source.clip.speed ?? 1);
+ const availableMediaDuration = Math.max(
+ 0,
+ buffer.duration - source.clip.inPoint - Math.max(0, source.angle.offset),
+ ) / playbackRate;
+ const alignedDuration = Math.min(source.clip.duration, availableMediaDuration);
+ return Math.min(duration, alignedDuration);
+ }, Number.POSITIVE_INFINITY);
+}
+
+export function updateAlignedSourceOffsets(
+ group: MultiCamGroup,
+ sources: readonly ResolvedMulticamSource[],
+ results: ReadonlyMap<string, SyncResult>,
+): void {
+ const reference = sources[0];
+ if (!reference) return;
+ for (const source of sources) {
+ const result = results.get(source.angle.id);
+ const angle = group.angles.find((candidate) => candidate.id === source.angle.id);
+ if (!result || !angle) continue;
+ angle.offset = result.offset + reference.clip.inPoint - source.clip.inPoint;
+ }
+}
+
+interface TimelineActionOptions {
+ project: Project;
+ group: MultiCamGroup;
+ groups: MultiCamGroup[];
+ outputTrackId: string;
+ sequence: readonly MulticamSequenceClip[];
+ createId?: () => string;
+ now?: () => number;
+}
+
+/**
+ * Returns the complete action batch for an automatic edit. Callers wrap the
+ * batch in a history group so source-track muting, output replacement, and
+ * multicam metadata all undo together.
+ */
+export function createMulticamTimelineActions({
+ project,
+ group,
+ groups,
+ outputTrackId,
+ sequence,
+ createId = () => crypto.randomUUID(),
+ now = () => Date.now(),
+}: TimelineActionOptions): Action[] {
+ const actions: Action[] = [];
+ const action = (type: string, params: Record<string, unknown>): Action => ({
+ type,
+ id: createId(),
+ timestamp: now(),
+ params,
+ });
+ const existingOutputIndex = project.timeline.tracks.findIndex(
+ (track) => track.id === outputTrackId,
+ );
+ if (existingOutputIndex >= 0) {
+ actions.push(action("track/remove", { trackId: outputTrackId }));
+ }
+
+ const sourceTrackIds = new Set(
+ group.angles
+ .map((angle) => angle.trackId)
+ .filter((trackId) => trackId.length > 0 && trackId !== outputTrackId),
+ );
+ for (const trackId of sourceTrackIds) {
+ const track = project.timeline.tracks.find((candidate) => candidate.id === trackId);
+ if (!track) continue;
+ if (!track.hidden) {
+ actions.push(action("track/hide", { trackId, hidden: true }));
+ }
+ if (!track.muted) {
+ actions.push(action("track/mute", { trackId, muted: true }));
+ }
+ }
+
+ actions.push(
+ action("track/add", {
+ trackType: "video",
+ trackId: outputTrackId,
+ position: existingOutputIndex >= 0 ? existingOutputIndex : 0,
+ }),
+ action("track/rename", {
+ trackId: outputTrackId,
+ name: `${group.name} Auto Edit`,
+ }),
+ );
+ for (const segment of sequence) {
+ actions.push(
+ action("clip/add", {
+ trackId: outputTrackId,
+ mediaId: segment.clip.mediaId,
+ startTime: segment.clip.startTime,
+ sourceClip: segment.clip,
+ }),
+ );
+ }
+ actions.push(action("multicam/setAll", { groups }));
+ return actions;
+}
+
+export function createMulticamOutputTrack(
+ group: MultiCamGroup,
+ outputTrackId: string,
+ sequence: readonly MulticamSequenceClip[],
+): Track {
+ return {
+ id: outputTrackId,
+ type: "video",
+ name: `${group.name} Auto Edit`,
+ clips: sequence.map((segment) => structuredClone(segment.clip)),
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ };
+}
+
+export function createMulticamApplyEditAction({
+ project,
+ group,
+ groups,
+ outputTrackId,
+ sequence,
+ createId = () => crypto.randomUUID(),
+ now = () => Date.now(),
+}: TimelineActionOptions): Action {
+ const existingOutputIndex = project.timeline.tracks.findIndex(
+ (track) => track.id === outputTrackId,
+ );
+ return {
+ type: "multicam/applyEdit",
+ id: createId(),
+ timestamp: now(),
+ params: {
+ outputTracks: [createMulticamOutputTrack(group, outputTrackId, sequence)],
+ outputTrackPosition: existingOutputIndex >= 0 ? existingOutputIndex : 0,
+ sourceTrackIds: [...new Set(
+ group.angles
+ .map((angle) => angle.trackId)
+ .filter((trackId) => trackId.length > 0 && trackId !== outputTrackId),
+ )],
+ groups,
+ },
+ };
+}
+
+export function createMulticamApplyTracksAction(input: {
+ project: Project;
+ group: MultiCamGroup;
+ groups: MultiCamGroup[];
+ outputTracks: Track[];
+ createId?: () => string;
+ now?: () => number;
+}): Action {
+ const outputIds = new Set(input.outputTracks.map((track) => track.id));
+ const existingOutputIndex = input.project.timeline.tracks.findIndex((track) =>
+ outputIds.has(track.id),
+ );
+ return {
+ type: "multicam/applyEdit",
+ id: (input.createId ?? (() => crypto.randomUUID()))(),
+ timestamp: (input.now ?? (() => Date.now()))(),
+ params: {
+ outputTracks: input.outputTracks.map((track) => structuredClone(track)),
+ outputTrackPosition: existingOutputIndex >= 0 ? existingOutputIndex : 0,
+ sourceTrackIds: [...new Set(
+ input.group.angles
+ .map((angle) => angle.trackId)
+ .filter((trackId) => trackId.length > 0 && !outputIds.has(trackId)),
+ )],
+ groups: input.groups,
+ },
+ };
+}
diff --git a/apps/web/src/components/editor/inspector/shell/ToolcraftSliderControl.test.tsx b/apps/web/src/components/editor/inspector/shell/ToolcraftSliderControl.test.tsx
index cf866d70..9bb22e6a 100644
--- a/apps/web/src/components/editor/inspector/shell/ToolcraftSliderControl.test.tsx
+++ b/apps/web/src/components/editor/inspector/shell/ToolcraftSliderControl.test.tsx
@@ -18,6 +18,7 @@ describe("ToolcraftSliderControl", () => {
/>,
);
+ expect(screen.getByRole("slider", { name: "Opacity" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Edit Opacity value" }));
const input = screen.getByRole("textbox", { name: "Opacity value" });
fireEvent.change(input, { target: { value: "25%" } });
diff --git a/apps/web/src/components/editor/inspector/tabs/AiTab.tsx b/apps/web/src/components/editor/inspector/tabs/AiTab.tsx
index c25c2051..9264d07a 100644
--- a/apps/web/src/components/editor/inspector/tabs/AiTab.tsx
+++ b/apps/web/src/components/editor/inspector/tabs/AiTab.tsx
@@ -1,32 +1,15 @@
import React from "react";
-import { Zap, Captions, Loader2, Upload } from "@/icons/lucide-compat";
+import { Zap, Loader2, Upload } from "@/icons/lucide-compat";
import { ToolcraftButton as Button } from "@openreel/ui";
import { ToolcraftCard as Card } from "@openreel/ui";
import { ToolcraftFileDropControl as FileInput } from "@openreel/ui";
-import { ToolcraftProgressBar as ProgressBar } from "@openreel/ui";
-import { ToolcraftSelectControl as Selector } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
-import {
- type WhisperTranscriptionProgress,
- type CaptionAnimationStyle,
- CAPTION_ANIMATION_STYLES,
- getAnimationStyleDisplayName,
-} from "@openreel/core";
import { AutoReframeSection } from "../";
import { AutoCaptionPanel } from "../AutoCaptionPanel";
import { CaptionEditorPanel } from "../CaptionEditorPanel";
import { AutoEditPanel } from "../../panels/AutoEditPanel";
import { HighlightExtractorPanel } from "../../panels/HighlightExtractorPanel";
import { InspectorSection } from "../shell/InspectorSection";
-import { AIPanel } from "../../ai-panel/AIPanel";
-import type { ClipMediaType } from "../../ai-panel/ai-kinds.config";
-import { isDesktopGpuAvailable } from "../../../../services/gpu-jobs";
-
-const GPU_CLIP_MEDIA: readonly ClipMediaType[] = ["video", "image", "audio"];
-
-function asGpuClipMedia(clipType: string | null): ClipMediaType | null {
- return GPU_CLIP_MEDIA.includes(clipType as ClipMediaType) ? (clipType as ClipMediaType) : null;
-}
export interface AiTabProps {
clipId: string;
@@ -34,15 +17,6 @@ export interface AiTabProps {
showVideoControls: boolean;
showAudioEffects: boolean;
showVideoEffects: boolean;
- transcriptionProgress: WhisperTranscriptionProgress | null;
- isTranscribing: boolean;
- targetLanguage: string;
- setTargetLanguage: React.Dispatch<React.SetStateAction<string>>;
- defaultAnimationStyle: CaptionAnimationStyle;
- setDefaultAnimationStyle: React.Dispatch<
- React.SetStateAction<CaptionAnimationStyle>
- >;
- handleGenerateSubtitles: () => Promise<void>;
handleSRTImport: (
event: React.ChangeEvent<HTMLInputElement>,
) => Promise<void>;
@@ -63,13 +37,6 @@ export const AiTab: React.FC<AiTabProps> = ({
showVideoControls,
showAudioEffects,
showVideoEffects,
- transcriptionProgress,
- isTranscribing,
- targetLanguage,
- setTargetLanguage,
- defaultAnimationStyle,
- setDefaultAnimationStyle,
- handleGenerateSubtitles,
handleSRTImport,
srtInputRef,
handleRemoveBackground,
@@ -81,24 +48,8 @@ export const AiTab: React.FC<AiTabProps> = ({
captionWordsPerLine,
onCaptionWordsPerLineChange,
}) => {
- const gpuClipMedia = asGpuClipMedia(clipType);
- // On desktop the local transcription endpoint (cloud.openreel.video) is
- // CORS-blocked from app://openreel, so generation is done via the GPU
- // "Auto Captions" tile in Cloud GPU Tools instead.
- const isDesktop = isDesktopGpuAvailable();
-
return (
<>
- {gpuClipMedia && (
- <InspectorSection
- title="Cloud GPU Tools"
- sectionId="cloud-gpu-tools"
- defaultOpen
- >
- <AIPanel clipTypeFilter={gpuClipMedia} embedded />
- </InspectorSection>
- )}
-
{clipType === "video" && (
<>
<InspectorSection
@@ -126,103 +77,9 @@ export const AiTab: React.FC<AiTabProps> = ({
}}
className="hidden"
/>
- {isDesktop && (
- <Text type="supporting" color="secondary" className="text-[11px]">
- Use the “Auto Captions” tool in Cloud GPU Tools above to generate captions.
- </Text>
- )}
- {!isDesktop && (
- <>
- <div className="space-y-1">
- <Selector
- label="Animation Style"
- size="sm"
- width="100%"
- value={defaultAnimationStyle}
- onChange={(v) =>
- setDefaultAnimationStyle(v as CaptionAnimationStyle)
- }
- isDisabled={isTranscribing}
- options={CAPTION_ANIMATION_STYLES.map((style) => ({
- label: getAnimationStyleDisplayName(style),
- value: style,
- }))}
- />
- </div>
-
- <div className="space-y-1">
- <Selector
- label="Target Language"
- size="sm"
- width="100%"
- value={targetLanguage}
- onChange={setTargetLanguage}
- isDisabled={isTranscribing}
- options={[
- { label: "Original (no translation)", value: "none" },
- { label: "English", value: "en" },
- { label: "Spanish", value: "es" },
- { label: "French", value: "fr" },
- { label: "German", value: "de" },
- { label: "Portuguese", value: "pt" },
- { label: "Italian", value: "it" },
- { label: "Dutch", value: "nl" },
- { label: "Russian", value: "ru" },
- { label: "Chinese", value: "zh" },
- { label: "Japanese", value: "ja" },
- { label: "Korean", value: "ko" },
- { label: "Arabic", value: "ar" },
- { label: "Hindi", value: "hi" },
- { label: "Turkish", value: "tr" },
- { label: "Polish", value: "pl" },
- { label: "Swedish", value: "sv" },
- ]}
- />
- </div>
-
- {transcriptionProgress ? (
- <div className="space-y-2">
- <div className="flex items-center gap-2">
- <Loader2
- size={12}
- className="animate-spin text-primary"
- />
- <Text type="supporting" color="primary" className="text-[10px]">
- {transcriptionProgress.message}
- </Text>
- </div>
- <ProgressBar
- label="Caption generation progress"
- isLabelHidden
- value={transcriptionProgress.progress}
- max={100}
- hasValueLabel={false}
- variant={
- transcriptionProgress.phase === "error"
- ? "error"
- : transcriptionProgress.phase === "complete"
- ? "success"
- : "accent"
- }
- />
- </div>
- ) : (
- <Button
- label="Generate Captions"
- onClick={handleGenerateSubtitles}
- isDisabled={isTranscribing}
- variant="primary"
- size="sm"
- icon={<Captions size={14} aria-hidden />}
- className="w-full justify-center"
- />
- )}
- </>
- )}
<Button
label="Import SRT / VTT as Text"
onClick={() => srtInputRef.current?.click()}
- isDisabled={isTranscribing}
variant="secondary"
size="sm"
icon={<Upload size={13} aria-hidden />}
@@ -268,7 +125,7 @@ export const AiTab: React.FC<AiTabProps> = ({
{showAudioEffects && (
<InspectorSection
- title="AI Highlights"
+ title="Local Highlights"
sectionId="ai-highlights"
defaultOpen={false}
>
diff --git a/apps/web/src/components/editor/inspector/tts-constants.ts b/apps/web/src/components/editor/inspector/tts-constants.ts
index a7deab2c..371b21fb 100644
--- a/apps/web/src/components/editor/inspector/tts-constants.ts
+++ b/apps/web/src/components/editor/inspector/tts-constants.ts
@@ -1,19 +1,9 @@
-import type { ElevenLabsModel, Voice } from "./tts-types";
-
-export const TTS_PROVIDERS = [
- { id: "piper" as const, label: "Piper (Free)", description: "Built-in open-source TTS" },
- { id: "elevenlabs" as const, label: "ElevenLabs", description: "Premium AI voices" },
-];
+import type { ElevenLabsModel } from "./tts-types";
export const FALLBACK_MODELS: ElevenLabsModel[] = [
{ model_id: "eleven_v3", name: "Eleven v3", description: "Latest ElevenLabs model", can_do_text_to_speech: true, languages: [] },
];
-export const PIPER_VOICES: Voice[] = [
- { id: "amy", name: "Amy", gender: "female", language: "en-US" },
- { id: "ryan", name: "Ryan", gender: "male", language: "en-US" },
-];
-
export const ENHANCE_SYSTEM_PROMPT = `You are a professional voice director transforming text into expressive, emotionally rich scripts for ElevenLabs v3 TTS. Your goal is to turn narration into performance.
Analyze the input for speaker intent, emotional arc, subtext, physical state, relationship dynamics, pacing needs, and environmental context.
diff --git a/apps/web/src/components/editor/panels/AutoEditPanel.tsx b/apps/web/src/components/editor/panels/AutoEditPanel.tsx
index 2ff0f41e..764d3c81 100644
--- a/apps/web/src/components/editor/panels/AutoEditPanel.tsx
+++ b/apps/web/src/components/editor/panels/AutoEditPanel.tsx
@@ -16,6 +16,7 @@ import {
type CutMode,
type BeatAnalysisResult,
type Clip,
+ getMediaItemCapabilities,
} from "@openreel/core";
interface AutoEditPanelProps {
@@ -34,22 +35,33 @@ export const AutoEditPanel: React.FC<AutoEditPanelProps> = ({ onClose }) => {
const audioClips = useMemo(() => {
const clips: Clip[] = [];
for (const track of project.timeline.tracks) {
- if (track.type === "audio") {
- clips.push(...track.clips);
- }
+ clips.push(
+ ...track.clips.filter((clip) =>
+ getMediaItemCapabilities(
+ project.mediaLibrary.items.find(
+ (mediaItem) => mediaItem.id === clip.mediaId,
+ ),
+ ).audio,
+ ),
+ );
}
return clips;
- }, [project.timeline.tracks]);
+ }, [project]);
const videoClips = useMemo(() => {
const clips: Clip[] = [];
for (const track of project.timeline.tracks) {
- if (track.type === "video") {
- clips.push(...track.clips);
- }
+ clips.push(
+ ...track.clips.filter(
+ (clip) =>
+ project.mediaLibrary.items.find(
+ (mediaItem) => mediaItem.id === clip.mediaId,
+ )?.type === "video",
+ ),
+ );
}
return clips;
- }, [project.timeline.tracks]);
+ }, [project]);
const [selectedAudioClipId, setSelectedAudioClipId] = useState<string>(
audioClips[0]?.id ?? "",
@@ -140,7 +152,10 @@ export const AutoEditPanel: React.FC<AutoEditPanelProps> = ({ onClose }) => {
if (!preview || preview.cuts.length === 0) return;
const tracks = [...project.timeline.tracks];
- const videoTrackIndex = tracks.findIndex((t) => t.type === "video");
+ const sourceClipIds = new Set(videoClips.map((clip) => clip.id));
+ const videoTrackIndex = tracks.findIndex((track) =>
+ track.clips.some((clip) => sourceClipIds.has(clip.id)),
+ );
if (videoTrackIndex === -1) return;
const newClips: Clip[] = preview.cuts.map((cut, index) => {
diff --git a/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx b/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx
index bc3f609b..25d82d67 100644
--- a/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx
+++ b/apps/web/src/components/editor/panels/HighlightExtractorPanel.tsx
@@ -7,12 +7,6 @@ import { Sparkles, Play, Check, Loader2 } from "@/icons/lucide-compat";
import { useProjectStore } from "../../../stores/project-store";
import { useTimelineStore } from "../../../stores/timeline-store";
import { applyHighlightRanges } from "../../../services/highlight-apply";
-import {
- getTranscriptionService,
- initializeTranscriptionService,
- type TranscriptWord,
-} from "@openreel/core";
-import { OPENREEL_TRANSCRIBE_URL } from "../../../config/api-endpoints";
import {
extractHighlights,
type HighlightResult,
@@ -63,30 +57,8 @@ export const HighlightExtractorPanel: React.FC<HighlightExtractorPanelProps> = (
setHighlights([]);
try {
- setPhase("Transcribing audio...");
- setProgress(5);
-
- const transcriptionService = getTranscriptionService() || initializeTranscriptionService({
- apiEndpoint: `${OPENREEL_TRANSCRIBE_URL}/transcribe`,
- });
- const subtitles = await transcriptionService.transcribeClip(
- clip,
- mediaItem,
- (p) => setProgress(Math.round(p.progress * 20)),
- );
-
- const transcript: TranscriptWord[] = subtitles.flatMap((sub) =>
- sub.words
- ? sub.words.map((w) => ({ text: w.text, start: w.startTime, end: w.endTime }))
- : [{ text: sub.text, start: sub.startTime, end: sub.endTime }],
- );
-
- if (transcript.length === 0) {
- throw new Error("No transcript words found");
- }
-
setPhase("Decoding audio...");
- setProgress(25);
+ setProgress(10);
const arrayBuffer = await mediaItem.blob.arrayBuffer();
const audioContext = new OfflineAudioContext(1, 44100, 44100);
@@ -94,11 +66,11 @@ export const HighlightExtractorPanel: React.FC<HighlightExtractorPanelProps> = (
const results = await extractHighlights(
audioBuffer,
- transcript,
+ [],
preferences,
(phaseName, prog) => {
setPhase(phaseName);
- setProgress(25 + Math.round(prog * 0.75));
+ setProgress(Math.round(prog));
},
);
diff --git a/apps/web/src/components/editor/preview/canvas-renderers.test.ts b/apps/web/src/components/editor/preview/canvas-renderers.test.ts
index 3f2e83a5..a71f820f 100644
--- a/apps/web/src/components/editor/preview/canvas-renderers.test.ts
+++ b/apps/web/src/components/editor/preview/canvas-renderers.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ drawFrameWithTransform,
getAnimatedTransform,
renderTextClipToCanvas,
} from "./canvas-renderers";
@@ -96,6 +97,105 @@ describe("Transform Coordinate System", () => {
});
});
+describe("drawFrameWithTransform crop fitting", () => {
+ const createContext = () =>
+ ({
+ save: vi.fn(),
+ restore: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ scale: vi.fn(),
+ drawImage: vi.fn(),
+ beginPath: vi.fn(),
+ roundRect: vi.fn(),
+ clip: vi.fn(),
+ globalAlpha: 1,
+ filter: "none",
+ }) as unknown as CanvasRenderingContext2D;
+
+ const croppedTransform: ClipTransform = {
+ ...DEFAULT_TRANSFORM,
+ crop: { x: 0.25, y: 0, width: 0.5, height: 1 },
+ };
+
+ it("honors cover using the cropped source aspect ratio", () => {
+ const context = createContext();
+ const frame = document.createElement("canvas");
+ frame.width = 1920;
+ frame.height = 1080;
+
+ drawFrameWithTransform(
+ context,
+ frame,
+ { ...croppedTransform, fitMode: "cover" },
+ 1080,
+ 1920,
+ );
+
+ const args = vi.mocked(context.drawImage).mock.calls[0];
+ expect(args.slice(0, 5)).toEqual([frame, 480, 0, 960, 1080]);
+ expect(args[5]).toBeCloseTo(-853.333, 3);
+ expect(args[6]).toBe(-960);
+ expect(args[7]).toBeCloseTo(1706.667, 3);
+ expect(args[8]).toBe(1920);
+ });
+
+ it("honors stretch after cropping", () => {
+ const context = createContext();
+ const frame = document.createElement("canvas");
+ frame.width = 1920;
+ frame.height = 1080;
+
+ drawFrameWithTransform(
+ context,
+ frame,
+ { ...croppedTransform, fitMode: "stretch" },
+ 1080,
+ 1920,
+ );
+
+ expect(vi.mocked(context.drawImage)).toHaveBeenCalledWith(
+ frame,
+ 480,
+ 0,
+ 960,
+ 1080,
+ -540,
+ -960,
+ 1080,
+ 1920,
+ );
+ });
+
+ it("keeps lower layers visible around a scaled contained video frame", () => {
+ const context = createContext();
+ const videoFrame = document.createElement("canvas");
+ videoFrame.width = 640;
+ videoFrame.height = 480;
+
+ drawFrameWithTransform(
+ context,
+ videoFrame,
+ {
+ ...DEFAULT_TRANSFORM,
+ scale: { x: 0.6, y: 0.6 },
+ fitMode: "contain",
+ },
+ 1920,
+ 1080,
+ );
+
+ expect(vi.mocked(context.scale)).toHaveBeenCalledWith(0.6, 0.6);
+ expect(vi.mocked(context.drawImage)).toHaveBeenCalledWith(
+ videoFrame,
+ -720,
+ -540,
+ 1440,
+ 1080,
+ );
+ });
+});
+
describe("GPU Transform Normalization", () => {
it("should NOT add 0.5 offset to normalized coordinates", () => {
const canvasWidth = 1920;
diff --git a/apps/web/src/components/editor/preview/canvas-renderers.ts b/apps/web/src/components/editor/preview/canvas-renderers.ts
index 4120ce8d..50a6f011 100644
--- a/apps/web/src/components/editor/preview/canvas-renderers.ts
+++ b/apps/web/src/components/editor/preview/canvas-renderers.ts
@@ -14,6 +14,8 @@ import {
type EmphasisAnimation,
isNeutralColorGrading,
type TransitionEdge,
+ resolveCanvasFitDimensions,
+ type Clip,
} from "@openreel/core";
import * as THREE from "three";
@@ -1719,38 +1721,17 @@ export const drawFrameWithTransform = (
sourceHeight = "height" in frame ? frame.height : canvasHeight;
}
- const sourceAspect = sourceWidth / sourceHeight;
- const canvasAspect = canvasWidth / canvasHeight;
- // Treat a missing or "none" fit as "contain" so clips preserve their
- // aspect ratio (letterboxed) instead of being drawn at raw native pixels.
- // Keeps the playing render consistent with the paused/scrub render, which
- // always letterboxes.
- const fitMode =
- !t.fitMode || t.fitMode === "none" ? "contain" : t.fitMode;
-
- let drawWidth: number;
- let drawHeight: number;
-
- if (fitMode === "stretch") {
- drawWidth = canvasWidth;
- drawHeight = canvasHeight;
- } else if (fitMode === "cover") {
- if (sourceAspect > canvasAspect) {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- } else {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- }
- } else {
- if (sourceAspect > canvasAspect) {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- } else {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- }
- }
+ const crop = t.crop;
+ const visibleSourceWidth = crop ? crop.width * sourceWidth : sourceWidth;
+ const visibleSourceHeight = crop ? crop.height * sourceHeight : sourceHeight;
+ const { width: drawWidth, height: drawHeight } =
+ resolveCanvasFitDimensions(
+ t.fitMode,
+ visibleSourceWidth,
+ visibleSourceHeight,
+ canvasWidth,
+ canvasHeight,
+ );
const drawX = -drawWidth * t.anchor.x;
const drawY = -drawHeight * t.anchor.y;
@@ -1763,37 +1744,20 @@ export const drawFrameWithTransform = (
ctx.clip();
}
- if (t.crop) {
- const sx = t.crop.x * sourceWidth;
- const sy = t.crop.y * sourceHeight;
- const sWidth = t.crop.width * sourceWidth;
- const sHeight = t.crop.height * sourceHeight;
-
- const croppedAspect = sWidth / sHeight;
- let cropDrawWidth: number;
- let cropDrawHeight: number;
-
- if (croppedAspect > canvasAspect) {
- cropDrawWidth = canvasWidth;
- cropDrawHeight = canvasWidth / croppedAspect;
- } else {
- cropDrawHeight = canvasHeight;
- cropDrawWidth = canvasHeight * croppedAspect;
- }
-
- const cropDrawX = -cropDrawWidth * t.anchor.x;
- const cropDrawY = -cropDrawHeight * t.anchor.y;
+ if (crop) {
+ const sx = crop.x * sourceWidth;
+ const sy = crop.y * sourceHeight;
ctx.drawImage(
frame,
sx,
sy,
- sWidth,
- sHeight,
- cropDrawX,
- cropDrawY,
- cropDrawWidth,
- cropDrawHeight,
+ visibleSourceWidth,
+ visibleSourceHeight,
+ drawX,
+ drawY,
+ drawWidth,
+ drawHeight,
);
} else {
ctx.drawImage(frame, drawX, drawY, drawWidth, drawHeight);
@@ -1979,14 +1943,9 @@ export const getTransitionAtTime = (
tracks: Array<{
id: string;
type: string;
- clips: Array<{
- id: string;
- startTime: number;
- duration: number;
- mediaId: string;
- inPoint?: number;
- }>;
+ clips: Clip[];
}>,
+ isEligibleClip: (clip: Clip) => boolean = () => true,
): TransitionRenderInfo | null => {
try {
const transitionBridge = getTransitionBridge();
@@ -1994,11 +1953,7 @@ export const getTransitionAtTime = (
return null;
}
- const videoTracks = tracks.filter(
- (t) => t.type === "video" || t.type === "image",
- );
-
- for (const track of videoTracks) {
+ for (const track of tracks) {
const transitions = transitionBridge.getTransitionsForTrack(track.id);
for (const transition of transitions) {
@@ -2007,7 +1962,13 @@ export const getTransitionAtTime = (
? track.clips.find((c) => c.id === transition.clipBId)
: undefined;
- if (!clipA || (transition.clipBId && !clipB)) continue;
+ if (
+ !clipA ||
+ !isEligibleClip(clipA) ||
+ (transition.clipBId && (!clipB || !isEligibleClip(clipB)))
+ ) {
+ continue;
+ }
if (
transitionBridge.isTimeInTransition(
diff --git a/apps/web/src/components/editor/preview/video-frame.test.ts b/apps/web/src/components/editor/preview/video-frame.test.ts
new file mode 100644
index 00000000..06de6509
--- /dev/null
+++ b/apps/web/src/components/editor/preview/video-frame.test.ts
@@ -0,0 +1,19 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { captureNativeVideoFrame } from "./video-frame";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("captureNativeVideoFrame", () => {
+ it("captures the native video source without canvas-sized background padding", async () => {
+ const video = {} as HTMLVideoElement;
+ const nativeFrame = { width: 720, height: 1280 } as ImageBitmap;
+ const createBitmap = vi.fn().mockResolvedValue(nativeFrame);
+ vi.stubGlobal("createImageBitmap", createBitmap);
+
+ await expect(captureNativeVideoFrame(video)).resolves.toBe(nativeFrame);
+ expect(createBitmap).toHaveBeenCalledOnce();
+ expect(createBitmap).toHaveBeenCalledWith(video);
+ });
+});
diff --git a/apps/web/src/components/editor/preview/video-frame.ts b/apps/web/src/components/editor/preview/video-frame.ts
new file mode 100644
index 00000000..3243d958
--- /dev/null
+++ b/apps/web/src/components/editor/preview/video-frame.ts
@@ -0,0 +1,11 @@
+/**
+ * Capture only the decoded video pixels for preview compositing.
+ *
+ * The caller owns project background and layer ordering. Expanding a paused
+ * video frame to the project canvas here would add opaque letterbox padding
+ * that can cover lower tracks and would make paused rendering diverge from
+ * native playback.
+ */
+export const captureNativeVideoFrame = (
+ video: HTMLVideoElement,
+): Promise<ImageBitmap> => createImageBitmap(video);
diff --git a/apps/web/src/components/editor/settings/ApiKeysPanel.tsx b/apps/web/src/components/editor/settings/ApiKeysPanel.tsx
index 441f911c..8c92985b 100644
--- a/apps/web/src/components/editor/settings/ApiKeysPanel.tsx
+++ b/apps/web/src/components/editor/settings/ApiKeysPanel.tsx
@@ -28,6 +28,7 @@ import {
saveSecret,
getSecret,
deleteSecret,
+ hasSecret,
listSecrets,
changeMasterPassword,
} from "../../../services/secure-storage";
@@ -57,7 +58,23 @@ export const ApiKeysPanel: React.FC = () => {
setUnlocked(isSessionUnlocked());
if (isSessionUnlocked()) {
- const keys = await listSecrets();
+ const keys =
+ typeof window !== "undefined" && window.openreel?.platform === "desktop"
+ ? (
+ await Promise.all(
+ SERVICE_REGISTRY.map(async (service) =>
+ (await hasSecret(service.id))
+ ? {
+ id: service.id,
+ label: service.label,
+ createdAt: 0,
+ updatedAt: 0,
+ }
+ : null,
+ ),
+ )
+ ).filter((key): key is NonNullable<typeof key> => key !== null)
+ : await listSecrets();
setStoredKeys(keys);
}
}, []);
@@ -183,7 +200,7 @@ export const ApiKeysPanel: React.FC = () => {
</Text>
<Text as="p" type="supporting" color="secondary" display="block" className="mb-6 max-w-sm">
Set up a master password to encrypt and store your API keys locally.
- Keys are encrypted with AES-256-GCM and never leave your browser.
+ Keys are encrypted with AES-256-GCM and are only sent when making a request to the selected service.
</Text>
<Button
label="Set Up Master Password"
@@ -327,8 +344,9 @@ export const ApiKeysPanel: React.FC = () => {
</Card>
<Text type="supporting" color="secondary" display="block" className="mt-2 text-[10px]">
- Added {new Date(stored.createdAt).toLocaleDateString()} &middot;
- Updated {new Date(stored.updatedAt).toLocaleDateString()}
+ {stored.createdAt > 0
+ ? `Added ${new Date(stored.createdAt).toLocaleDateString()} · Updated ${new Date(stored.updatedAt).toLocaleDateString()}`
+ : "Stored securely in the system keychain"}
</Text>
</Card>
);
@@ -342,7 +360,9 @@ export const ApiKeysPanel: React.FC = () => {
<Plus size={14} className="text-primary" aria-hidden />
<Text type="label" weight="bold">
Add{" "}
- {SERVICE_REGISTRY.find((s) => s.id === addingService)?.label} Key
+ {SERVICE_REGISTRY.find((s) => s.id === addingService)?.keyOptional
+ ? `Optional ${SERVICE_REGISTRY.find((s) => s.id === addingService)?.label} Key`
+ : `${SERVICE_REGISTRY.find((s) => s.id === addingService)?.label} Key`}
</Text>
</div>
<ToolcraftTextInputControl
@@ -351,7 +371,11 @@ export const ApiKeysPanel: React.FC = () => {
type="password"
value={newKeyValue}
onChange={setNewKeyValue}
- placeholder="Paste your API key here"
+ placeholder={
+ SERVICE_REGISTRY.find((s) => s.id === addingService)?.keyOptional
+ ? "Paste an API key if your endpoint requires one"
+ : "Paste your API key here"
+ }
hasAutoFocus
width="100%"
className="mb-3 font-mono text-xs"
@@ -384,7 +408,7 @@ export const ApiKeysPanel: React.FC = () => {
{availableServices.map((service) => (
<ClickableCard
key={service.id}
- label={`Add ${service.label} API key`}
+ label={`Add ${service.keyOptional ? "optional " : ""}${service.label} API key`}
onClick={() => setAddingService(service.id)}
padding={3}
variant="default"
@@ -396,7 +420,7 @@ export const ApiKeysPanel: React.FC = () => {
</div>
<div>
<Text type="label" weight="bold" display="block">
- {service.label}
+ {service.label}{service.keyOptional ? " (optional key)" : ""}
</Text>
<Text type="supporting" color="secondary" display="block">
{service.description}
diff --git a/apps/web/src/components/editor/settings/GeneralPanel.test.tsx b/apps/web/src/components/editor/settings/GeneralPanel.test.tsx
new file mode 100644
index 00000000..b6325734
--- /dev/null
+++ b/apps/web/src/components/editor/settings/GeneralPanel.test.tsx
@@ -0,0 +1,44 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { useProjectStore } from "../../../stores/project-store";
+import { GeneralPanel } from "./GeneralPanel";
+
+describe("GeneralPanel project frame rate", () => {
+ const originalUpdateSettings = useProjectStore.getState().updateSettings;
+ const originalProject = useProjectStore.getState().project;
+ const updateSettings = vi.fn();
+
+ beforeEach(() => {
+ updateSettings.mockResolvedValue({ success: true });
+ useProjectStore.setState({
+ project: {
+ ...originalProject,
+ settings: { ...originalProject.settings, frameRate: 30 },
+ },
+ updateSettings: updateSettings as unknown as typeof originalUpdateSettings,
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ updateSettings.mockReset();
+ useProjectStore.setState({
+ project: originalProject,
+ updateSettings: originalUpdateSettings,
+ });
+ });
+
+ it("changes the project editing timebase to 60 fps", () => {
+ render(<GeneralPanel />);
+
+ const selector = screen.getByRole("combobox", {
+ name: "Editing frame rate",
+ });
+ expect(selector).toHaveValue("30");
+ expect(screen.getByRole("option", { name: "60 fps" })).toBeTruthy();
+
+ fireEvent.change(selector, { target: { value: "60" } });
+
+ expect(updateSettings).toHaveBeenCalledWith({ frameRate: 60 });
+ });
+});
diff --git a/apps/web/src/components/editor/settings/GeneralPanel.tsx b/apps/web/src/components/editor/settings/GeneralPanel.tsx
index fead98db..e9a2dfc0 100644
--- a/apps/web/src/components/editor/settings/GeneralPanel.tsx
+++ b/apps/web/src/components/editor/settings/GeneralPanel.tsx
@@ -5,8 +5,10 @@ import { ToolcraftClickableCard as ClickableCard } from "@openreel/ui";
import { ToolcraftNumberInputControl } from "@openreel/ui";
import { ToolcraftSelectControl as Selector } from "@openreel/ui";
import { ToolcraftText as Text } from "@openreel/ui";
+import { ToolcraftTextInputControl as TextInput } from "@openreel/ui";
import { useSettingsStore, SERVICE_REGISTRY, type TtsProvider, type LlmProvider, type AggregatorProvider } from "../../../stores/settings-store";
import { useProjectStore } from "../../../stores/project-store";
+import { EDITING_FRAME_RATE_OPTIONS } from "../editing-frame-rate";
const ASPECT_PRESETS: Array<{ label: string; width: number; height: number }> = [
{ label: "16:9 Landscape (1080p)", width: 1920, height: 1080 },
@@ -37,17 +39,24 @@ export const GeneralPanel: React.FC = () => {
autoSaveInterval,
defaultTtsProvider,
defaultLlmProvider,
+ llmBaseUrl,
+ llmModel,
defaultAggregator,
configuredServices,
setAutoSave,
setAutoSaveInterval,
setDefaultTtsProvider,
setDefaultLlmProvider,
+ setLlmBaseUrl,
+ setLlmModel,
setDefaultAggregator,
} = useSettingsStore();
const projectWidth = useProjectStore((s) => s.project.settings.width);
const projectHeight = useProjectStore((s) => s.project.settings.height);
+ const projectFrameRate = useProjectStore(
+ (s) => s.project.settings.frameRate,
+ );
const updateProjectSettings = useProjectStore((s) => s.updateSettings);
const backgroundFillMode = useProjectStore(
(s) => s.project.timeline.backgroundFillMode,
@@ -82,18 +91,10 @@ export const GeneralPanel: React.FC = () => {
}
}, [draftWidth, draftHeight, applyDimensions]);
- const ttsProviders = [
- { id: "piper", label: "Piper (Free / Built-in)" },
- ...SERVICE_REGISTRY.filter(
- (s) => s.id === "elevenlabs" || configuredServices.includes(s.id),
- ),
- ];
+ const ttsProviders = SERVICE_REGISTRY.filter((s) => s.id === "elevenlabs");
const llmProviders = SERVICE_REGISTRY.filter(
- (s) =>
- s.id === "openai" ||
- s.id === "anthropic" ||
- configuredServices.includes(s.id),
+ (s) => s.id === "openai-compatible" || s.id === "anthropic-compatible",
);
const aggregatorProviders = SERVICE_REGISTRY.filter(
@@ -102,7 +103,6 @@ export const GeneralPanel: React.FC = () => {
s.id === "freepik" ||
configuredServices.includes(s.id),
);
-
return (
<div className="space-y-6 pb-4">
{/* Project Composition */}
@@ -172,6 +172,35 @@ export const GeneralPanel: React.FC = () => {
/>
</div>
+ <div className="flex items-center justify-between gap-4 rounded-lg border border-border bg-background-tertiary p-3">
+ <div>
+ <Text type="supporting" color="primary" className="text-sm font-medium">
+ Editing frame rate
+ </Text>
+ <Text type="supporting" color="secondary" className="mt-0.5 block text-[11px]">
+ Controls preview playback, frame stepping, and the default export rate.
+ Existing clip timing stays unchanged.
+ </Text>
+ </div>
+ <Selector
+ label="Editing frame rate"
+ isLabelHidden
+ size="md"
+ width={160}
+ value={String(projectFrameRate)}
+ onChange={(value) => {
+ const frameRate = Number(value);
+ if (Number.isFinite(frameRate) && frameRate > 0) {
+ void updateProjectSettings({ frameRate });
+ }
+ }}
+ options={EDITING_FRAME_RATE_OPTIONS.map((option) => ({
+ label: option.label,
+ value: String(option.value),
+ }))}
+ />
+ </div>
+
<div className="space-y-2">
<Text type="supporting" color="secondary" className="text-xs font-medium">
Background fill
@@ -284,14 +313,13 @@ export const GeneralPanel: React.FC = () => {
<div className="h-px bg-border" />
- {/* Default providers */}
+ {/* AI connections */}
<div className="space-y-4">
<Text type="body" color="primary" className="text-sm font-medium">
- Default AI Providers
+ AI Connections
</Text>
<Text type="supporting" color="secondary" className="text-xs">
- Choose which service to use by default for AI features.
- Configure API keys in the &quot;API Keys&quot; tab first.
+ Connect a compatible endpoint you control. OpenReel does not choose a vendor or model for you.
</Text>
<div className="space-y-3">
@@ -312,19 +340,66 @@ export const GeneralPanel: React.FC = () => {
<div className="flex items-center justify-between">
<Text type="supporting" color="secondary" className="text-sm">
- AI Assistant (LLM)
+ AI Assistant API format
</Text>
<Selector
- label="AI Assistant provider"
+ label="AI Assistant API format"
isLabelHidden
size="md"
width={180}
- value={defaultLlmProvider}
- onChange={(value) => setDefaultLlmProvider(value as LlmProvider)}
- options={llmProviders.map((s) => ({ label: s.label, value: s.id }))}
+ value={defaultLlmProvider ?? ""}
+ onChange={(value) =>
+ setDefaultLlmProvider((value || null) as LlmProvider | null)
+ }
+ options={[
+ { label: "Choose API format…", value: "" },
+ ...llmProviders.map((s) => ({ label: s.label, value: s.id })),
+ ]}
/>
</div>
+ {defaultLlmProvider ? (
+ <div className="space-y-3 rounded-lg border border-border bg-background-tertiary p-3">
+ <div>
+ <Text type="supporting" color="secondary" className="text-sm font-medium">
+ {defaultLlmProvider === "anthropic-compatible"
+ ? "Anthropic-compatible endpoint"
+ : "OpenAI-compatible endpoint"}
+ </Text>
+ <Text type="supporting" color="secondary" className="mt-0.5 block text-xs">
+ Enter your API host and the exact tool-capable model ID exposed by that host.
+ </Text>
+ </div>
+ <TextInput
+ label="Base URL"
+ value={llmBaseUrl}
+ onChange={setLlmBaseUrl}
+ placeholder={
+ defaultLlmProvider === "anthropic-compatible"
+ ? "https://gateway.example/v1"
+ : "http://localhost:11434/v1"
+ }
+ width="100%"
+ />
+ <TextInput
+ label="Model ID"
+ value={llmModel}
+ onChange={setLlmModel}
+ placeholder="Enter any model ID from your endpoint"
+ width="100%"
+ />
+ <Text type="supporting" color="secondary" className="block text-[11px] leading-relaxed">
+ Load available models from the AI chat settings, or enter an ID manually when discovery is unavailable. API keys are optional.
+ </Text>
+ </div>
+ ) : (
+ <div className="rounded-lg border border-dashed border-border bg-background-tertiary p-3">
+ <Text type="supporting" color="secondary" className="block text-xs">
+ Choose an API format to configure your host and model.
+ </Text>
+ </div>
+ )}
+
<div className="flex items-center justify-between">
<div>
<Text type="supporting" color="secondary" className="text-sm">
diff --git a/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.test.tsx b/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.test.tsx
index 97b669b8..4958edd9 100644
--- a/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.test.tsx
+++ b/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.test.tsx
@@ -2,6 +2,7 @@ import "../../../test/install-local-storage-mock";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { Project, TextClip } from "@openreel/core";
+import { useEngineStore } from "../../../stores/engine-store";
import { createEmptyProject } from "../../../stores/project/project-helpers";
import { useProjectStore } from "../../../stores/project-store";
import { useUIStore } from "../../../stores/ui-store";
@@ -43,7 +44,7 @@ function captionProject(): Project {
const empty = createEmptyProject("Caption selection");
return {
...empty,
- textClips: [caption("caption-a", 0), caption("caption-b", 2)],
+ textClips: [],
timeline: {
...empty.timeline,
tracks: [
@@ -65,12 +66,17 @@ function captionProject(): Project {
describe("CaptionBatchSelectButton", () => {
beforeEach(() => {
+ useEngineStore
+ .getState()
+ .getTitleEngine()
+ ?.loadTextClips([caption("caption-a", 0), caption("caption-b", 2)]);
useProjectStore.setState({ project: captionProject(), hasOpenProject: true });
useUIStore.getState().clearSelection();
});
afterEach(() => {
cleanup();
+ useEngineStore.getState().getTitleEngine()?.clear();
useUIStore.getState().clearSelection();
});
diff --git a/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.tsx b/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.tsx
index 09f0dc01..4582a456 100644
--- a/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.tsx
+++ b/apps/web/src/components/editor/timeline/CaptionBatchSelectButton.tsx
@@ -7,17 +7,22 @@ import { getTimelineTrackSelection } from "../../../utils/timeline-item-actions"
export const CaptionBatchSelectButton: React.FC = () => {
const project = useProjectStore((state) => state.project);
+ const getFullProject = useProjectStore((state) => state.getFullProject);
const selectMultiple = useUIStore((state) => state.selectMultiple);
+ const projectRevision = project.modifiedAt;
const captionSelection = useMemo(() => {
- const captionTrack = project.timeline.tracks.find(
+ void projectRevision;
+ const liveProject = getFullProject();
+ const captionTrack = liveProject.timeline.tracks.find(
(track) =>
- track.type === "text" && track.name.trim().toLowerCase() === "captions",
+ (track.role === "captions" ||
+ track.name.trim().toLowerCase() === "captions"),
);
return captionTrack
- ? getTimelineTrackSelection(project, captionTrack.id)
+ ? getTimelineTrackSelection(liveProject, captionTrack.id)
: [];
- }, [project]);
+ }, [getFullProject, projectRevision]);
if (captionSelection.length < 2) return null;
diff --git a/apps/web/src/components/editor/timeline/CaptionContextMenuSelection.test.tsx b/apps/web/src/components/editor/timeline/CaptionContextMenuSelection.test.tsx
new file mode 100644
index 00000000..e2b3aa58
--- /dev/null
+++ b/apps/web/src/components/editor/timeline/CaptionContextMenuSelection.test.tsx
@@ -0,0 +1,41 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { ToolcraftContextMenu as ContextMenu } from "@openreel/ui";
+import { useUIStore } from "../../../stores/ui-store";
+
+describe("caption context-menu selection", () => {
+ afterEach(() => {
+ cleanup();
+ useUIStore.getState().clearSelection();
+ });
+
+ it("does not let the menu click clear the selected captions", () => {
+ const captionSelection = [
+ { id: "caption-a", trackId: "captions", type: "text-clip" as const },
+ { id: "caption-b", trackId: "captions", type: "text-clip" as const },
+ ];
+
+ render(
+ <div onClick={() => useUIStore.getState().clearSelection()}>
+ <ContextMenu
+ items={[
+ {
+ label: "Select All Captions",
+ onClick: () =>
+ useUIStore.getState().selectMultiple(captionSelection),
+ },
+ ]}
+ >
+ <button type="button">Caption clip</button>
+ </ContextMenu>
+ </div>,
+ );
+
+ fireEvent.contextMenu(screen.getByRole("button", { name: "Caption clip" }));
+ fireEvent.click(
+ screen.getByRole("menuitem", { name: "Select All Captions" }),
+ );
+
+ expect(useUIStore.getState().selectedItems).toEqual(captionSelection);
+ });
+});
diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsx
index 68f9fcbf..31bde8cd 100644
--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx
+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx
@@ -5,7 +5,11 @@ import type { Clip, Track, TransitionType } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { useUIStore } from "../../../stores/ui-store";
import { useTimelineStore } from "../../../stores/timeline-store";
-import { calculateSnap, getClipStyle } from "./utils";
+import {
+ calculateSnap,
+ getClipStyle,
+ getClipWaveformBarAmplitudes,
+} from "./utils";
import { useClipContextMenuItems } from "./ClipContextMenu";
import { toast } from "../../../stores/notification-store";
import { getTransitionBridge } from "../../../bridges/transition-bridge";
@@ -28,7 +32,7 @@ interface ClipComponentProps {
clipId: string,
newStartTime: number,
targetTrackId?: string,
- ) => void;
+ ) => void | Promise<void>;
onSnapIndicator: (time: number | null) => void;
onTrimClip?: (
clipId: string,
@@ -108,7 +112,9 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
scrollTop: 0,
});
const mousePositionRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({ time: 0 });
+ const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({
+ time: clip.startTime,
+ });
const dragPendingRef = useRef<{ active: boolean; startX: number; startY: number }>({
active: false,
startX: 0,
@@ -129,11 +135,12 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const left = clip.startTime * pixelsPerSecond;
const width = clip.duration * pixelsPerSecond;
- const isVideo = track.type === "video";
- const isAudio = track.type === "audio";
- const isImage = track.type === "image";
+ const clipMediaType = mediaItem?.type ?? track.type;
+ const isVideo = clipMediaType === "video";
+ const isAudio = clipMediaType === "audio";
+ const isImage = clipMediaType === "image";
const isMotionClip = Boolean(clip.metadata?.motionClip);
- const clipStyle = getClipStyle(track.type);
+ const clipStyle = getClipStyle(clipMediaType);
const handleClick = (e: React.MouseEvent) => {
if (e.button !== 0) return;
@@ -501,14 +508,14 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const scrollTop = timelineRef.current?.scrollTop || 0;
const mouseY = e.clientY - timelineRect.top + scrollTop;
let targetTrackId: string | undefined;
- let hoveredTrackType: string | undefined;
+ let hoveredTrackIsLocked = false;
let cumulativeY = 0;
for (const t of allTracks) {
const height = trackHeights.get(t.id) || 48;
if (mouseY >= cumulativeY && mouseY < cumulativeY + height) {
- hoveredTrackType = t.type;
- if (t.type === track.type && t.id !== track.id) {
+ hoveredTrackIsLocked = Boolean(t.locked);
+ if (!t.locked && t.id !== track.id) {
targetTrackId = t.id;
}
break;
@@ -516,8 +523,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
cumulativeY += height;
}
- const isOverDifferentTrackType = hoveredTrackType !== undefined && hoveredTrackType !== track.type;
- setIsInvalidDrop(isOverDifferentTrackType);
+ setIsInvalidDrop(hoveredTrackIsLocked);
pendingDropRef.current = { time: snapResult.time, targetTrackId };
@@ -532,10 +538,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const companions = multiDragSnapshotRef.current;
pendingCommitRef.current = () => {
onMoveClip(clip.id, moveTime, undefined);
- // Move every companion clip in the multi-selection by the same
- // delta. Cross-track moves of the primary don't take any
- // companions along — that gets too lossy when they live on tracks
- // of a different type — but same-track drags stay locked.
+ // Move every companion clip in the multi-selection by the same delta.
if (companions.length > 0) {
const deltaTime = moveTime - baseStartTime;
for (const snap of companions) {
@@ -558,7 +561,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
projectStore.endHistoryGroup();
};
- const handleMouseUp = () => {
+ const handleMouseUp = async () => {
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId);
}
@@ -574,9 +577,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
pendingCommit?.();
const { time, targetTrackId } = pendingDropRef.current;
- if (targetTrackId) {
- onMoveClip(clip.id, time, targetTrackId);
- }
+ await onMoveClip(clip.id, time, targetTrackId ?? track.id);
setIsDragging(false);
setDragYOffset(0);
@@ -607,7 +608,6 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
pixelsPerSecond,
clip.id,
track.id,
- track.type,
allTracks,
trackHeights,
timelineRef,
@@ -873,7 +873,16 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
{isAudio &&
(() => {
const barCount = Math.max(8, Math.floor(width / 6));
- const data = mediaItem?.waveformData;
+ const amplitudes = getClipWaveformBarAmplitudes(
+ mediaItem?.waveformData,
+ {
+ barCount,
+ mediaDuration: mediaItem?.metadata.duration ?? 0,
+ inPoint: clip.inPoint,
+ outPoint: clip.outPoint,
+ reversed: clip.reversed,
+ },
+ );
return (
<svg
className="absolute left-0 bottom-0 w-full pointer-events-none"
@@ -881,12 +890,8 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
preserveAspectRatio="none"
viewBox={`0 0 ${barCount * 6 + 6} 28`}
>
- {Array.from({ length: barCount }).map((_, i) => {
- const amp =
- data && data.length > 0
- ? Math.abs(data[Math.floor((i / barCount) * data.length)] ?? 0)
- : 0.35 + 0.5 * Math.abs(Math.sin(i * 1.3) * Math.cos(i * 0.7));
- const h = Math.max(3, Math.min(24, amp * 26));
+ {amplitudes.map((amplitude, i) => {
+ const h = Math.min(24, amplitude * 26);
return (
<rect
key={i}
diff --git a/apps/web/src/components/editor/timeline/ClipContextMenu.tsx b/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
index 7f87dbd6..b6313008 100644
--- a/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
+++ b/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
@@ -60,9 +60,10 @@ export function useClipContextMenuItems({
}, [track.clips, clip.id, clip.startTime]);
const mediaItem = getMediaItem(clip.mediaId);
- const isVideo = track.type === "video";
- const isAudio = track.type === "audio";
- const isImage = track.type === "image";
+ const clipMediaType = mediaItem?.type ?? track.type;
+ const isVideo = clipMediaType === "video";
+ const isAudio = clipMediaType === "audio";
+ const isImage = clipMediaType === "image";
const isVideoWithAudio =
isVideo &&
mediaItem?.type === "video" &&
@@ -83,7 +84,7 @@ export function useClipContextMenuItems({
};
const handleSelectTrackClips = () => {
- const project = useProjectStore.getState().project;
+ const project = useProjectStore.getState().getFullProject();
selectMultiple(getTimelineTrackSelection(project, track.id));
onClose?.();
};
diff --git a/apps/web/src/components/editor/timeline/GraphicsClipContextMenu.tsx b/apps/web/src/components/editor/timeline/GraphicsClipContextMenu.tsx
index 92ab2f50..978851ee 100644
--- a/apps/web/src/components/editor/timeline/GraphicsClipContextMenu.tsx
+++ b/apps/web/src/components/editor/timeline/GraphicsClipContextMenu.tsx
@@ -42,8 +42,8 @@ export function useGraphicsClipContextMenuItems({
(project.timeline.tracks.some(
(track) =>
track.id === clip.trackId &&
- track.type === "text" &&
- track.name.trim().toLowerCase() === "captions",
+ (track.role === "captions" ||
+ track.name.trim().toLowerCase() === "captions"),
) ||
("metadata" in clip &&
typeof clip.metadata?.captionSource === "string"));
@@ -77,7 +77,7 @@ export function useGraphicsClipContextMenuItems({
};
const handleSelectTrackClips = () => {
- const project = useProjectStore.getState().project;
+ const project = useProjectStore.getState().getFullProject();
selectMultiple(getTimelineTrackSelection(project, clip.trackId));
onClose?.();
};
diff --git a/apps/web/src/components/editor/timeline/ShapeClipComponent.tsx b/apps/web/src/components/editor/timeline/ShapeClipComponent.tsx
index 033edd9a..87c9b4d3 100644
--- a/apps/web/src/components/editor/timeline/ShapeClipComponent.tsx
+++ b/apps/web/src/components/editor/timeline/ShapeClipComponent.tsx
@@ -1,7 +1,7 @@
import React, { useRef, useState, useEffect, useCallback } from "react";
import { ToolcraftContextMenu as ContextMenu } from "@openreel/ui";
import { Shapes, FileCode, Smile } from "@/icons/lucide-compat";
-import type { ShapeClip, SVGClip, StickerClip } from "@openreel/core";
+import type { ShapeClip, SVGClip, StickerClip, Track } from "@openreel/core";
import { useGraphicsClipContextMenuItems } from "./GraphicsClipContextMenu";
import { calculateSnap } from "./utils";
import { useProjectStore } from "../../../stores/project-store";
@@ -16,7 +16,14 @@ interface ShapeClipComponentProps {
isSelected: boolean;
onSelect: (clipId: string, addToSelection: boolean) => void;
onTrim: (clipId: string, edge: "left" | "right", newTime: number) => void;
- onMoveClip: (clipId: string, newStartTime: number) => void;
+ onMoveClip: (
+ clipId: string,
+ newStartTime: number,
+ targetTrackId?: string,
+ ) => void | Promise<void>;
+ allTracks: Track[];
+ trackHeights: Map<string, number>;
+ timelineRef: React.RefObject<HTMLDivElement | null>;
}
export const ShapeClipComponent: React.FC<ShapeClipComponentProps> = ({
@@ -26,12 +33,18 @@ export const ShapeClipComponent: React.FC<ShapeClipComponentProps> = ({
onSelect,
onTrim,
onMoveClip,
+ allTracks,
+ trackHeights,
+ timelineRef,
}) => {
const clipRef = useRef<HTMLDivElement>(null);
const [isDragging, setIsDragging] = useState(false);
const [dragOffset, setDragOffset] = useState(0);
const [isTrimming, setIsTrimming] = useState<"left" | "right" | null>(null);
const historyGroupOpenRef = useRef(false);
+ const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({
+ time: shapeClip.startTime,
+ });
const { snapSettings } = useUIStore();
const { playheadPosition } = useTimelineStore();
const trimStartRef = useRef<{
@@ -105,7 +118,6 @@ export const ShapeClipComponent: React.FC<ShapeClipComponentProps> = ({
const rect = timelineElement.getBoundingClientRect();
const x = e.clientX - rect.left - dragOffset;
const rawTime = Math.max(0, x / pixelsPerSecond);
- const allTracks = useProjectStore.getState().project.timeline.tracks;
const dragSnapSettings = { ...snapSettings, snapToPlayhead: false };
const snapResult = calculateSnap(
rawTime,
@@ -116,10 +128,34 @@ export const ShapeClipComponent: React.FC<ShapeClipComponentProps> = ({
pixelsPerSecond,
shapeClip.duration,
);
+ const timelineRect = timelineRef.current?.getBoundingClientRect();
+ const scrollTop = timelineRef.current?.scrollTop ?? 0;
+ let targetTrackId: string | undefined;
+ if (timelineRect) {
+ const mouseY = e.clientY - timelineRect.top + scrollTop;
+ let cumulativeY = 0;
+ for (const track of allTracks) {
+ const height = trackHeights.get(track.id) ?? 48;
+ if (mouseY >= cumulativeY && mouseY < cumulativeY + height) {
+ if (!track.locked && track.id !== shapeClip.trackId) {
+ targetTrackId = track.id;
+ }
+ break;
+ }
+ cumulativeY += height;
+ }
+ }
+ pendingDropRef.current = { time: snapResult.time, targetTrackId };
onMoveClip(shapeClip.id, snapResult.time);
};
- const handleMouseUp = () => {
+ const handleMouseUp = async () => {
+ const pending = pendingDropRef.current;
+ await onMoveClip(
+ shapeClip.id,
+ pending.time,
+ pending.targetTrackId ?? shapeClip.trackId,
+ );
setIsDragging(false);
endTimingGesture();
};
@@ -131,7 +167,21 @@ export const ShapeClipComponent: React.FC<ShapeClipComponentProps> = ({
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
- }, [isDragging, dragOffset, pixelsPerSecond, shapeClip.id, shapeClip.duration, onMoveClip, snapSettings, playheadPosition, endTimingGesture]);
+ }, [
+ isDragging,
+ dragOffset,
+ pixelsPerSecond,
+ shapeClip.id,
+ shapeClip.trackId,
+ shapeClip.duration,
+ onMoveClip,
+ snapSettings,
+ playheadPosition,
+ endTimingGesture,
+ timelineRef,
+ allTracks,
+ trackHeights,
+ ]);
useEffect(() => {
if (!isTrimming) return;
diff --git a/apps/web/src/components/editor/timeline/TextClipComponent.tsx b/apps/web/src/components/editor/timeline/TextClipComponent.tsx
index e50fc348..1973089c 100644
--- a/apps/web/src/components/editor/timeline/TextClipComponent.tsx
+++ b/apps/web/src/components/editor/timeline/TextClipComponent.tsx
@@ -1,7 +1,7 @@
import React, { useRef, useState, useEffect, useCallback } from "react";
import { ToolcraftContextMenu as ContextMenu } from "@openreel/ui";
import { Type } from "@/icons/lucide-compat";
-import type { TextClip } from "@openreel/core";
+import type { TextClip, Track } from "@openreel/core";
import { useGraphicsClipContextMenuItems } from "./GraphicsClipContextMenu";
import { calculateSnap } from "./utils";
import { useProjectStore } from "../../../stores/project-store";
@@ -14,7 +14,14 @@ interface TextClipComponentProps {
isSelected: boolean;
onSelect: (clipId: string, addToSelection: boolean) => void;
onTrim: (clipId: string, edge: "left" | "right", newTime: number) => void;
- onMoveClip?: (clipId: string, newStartTime: number) => void;
+ onMoveClip?: (
+ clipId: string,
+ newStartTime: number,
+ targetTrackId?: string,
+ ) => void | Promise<void>;
+ allTracks: Track[];
+ trackHeights: Map<string, number>;
+ timelineRef: React.RefObject<HTMLDivElement | null>;
}
export const TextClipComponent: React.FC<TextClipComponentProps> = ({
@@ -24,12 +31,18 @@ export const TextClipComponent: React.FC<TextClipComponentProps> = ({
onSelect,
onTrim,
onMoveClip,
+ allTracks,
+ trackHeights,
+ timelineRef,
}) => {
const clipRef = useRef<HTMLDivElement>(null);
const [isTrimming, setIsTrimming] = useState<"left" | "right" | null>(null);
const [isDragging, setIsDragging] = useState(false);
const [dragOffset, setDragOffset] = useState(0);
const historyGroupOpenRef = useRef(false);
+ const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({
+ time: textClip.startTime,
+ });
const { snapSettings } = useUIStore();
const { playheadPosition } = useTimelineStore();
const trimStartRef = useRef<{
@@ -100,10 +113,34 @@ export const TextClipComponent: React.FC<TextClipComponentProps> = ({
pixelsPerSecond,
textClip.duration,
);
+ const timelineRect = timelineRef.current?.getBoundingClientRect();
+ const scrollTop = timelineRef.current?.scrollTop ?? 0;
+ let targetTrackId: string | undefined;
+ if (timelineRect) {
+ const mouseY = e.clientY - timelineRect.top + scrollTop;
+ let cumulativeY = 0;
+ for (const track of allTracks) {
+ const height = trackHeights.get(track.id) ?? 48;
+ if (mouseY >= cumulativeY && mouseY < cumulativeY + height) {
+ if (!track.locked && track.id !== textClip.trackId) {
+ targetTrackId = track.id;
+ }
+ break;
+ }
+ cumulativeY += height;
+ }
+ }
+ pendingDropRef.current = { time: snapResult.time, targetTrackId };
onMoveClip(textClip.id, snapResult.time);
};
- const handleMouseUp = () => {
+ const handleMouseUp = async () => {
+ const pending = pendingDropRef.current;
+ await onMoveClip(
+ textClip.id,
+ pending.time,
+ pending.targetTrackId ?? textClip.trackId,
+ );
setIsDragging(false);
endTimingGesture();
};
@@ -115,7 +152,21 @@ export const TextClipComponent: React.FC<TextClipComponentProps> = ({
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
- }, [isDragging, textClip.id, textClip.duration, pixelsPerSecond, dragOffset, onMoveClip, snapSettings, playheadPosition, endTimingGesture]);
+ }, [
+ isDragging,
+ textClip.id,
+ textClip.trackId,
+ textClip.duration,
+ pixelsPerSecond,
+ dragOffset,
+ onMoveClip,
+ snapSettings,
+ playheadPosition,
+ endTimingGesture,
+ timelineRef,
+ allTracks,
+ trackHeights,
+ ]);
const handleTrimStart = (e: React.MouseEvent, edge: "left" | "right") => {
if (e.button !== 0) return;
diff --git a/apps/web/src/components/editor/timeline/TrackClipSelectionMenu.test.tsx b/apps/web/src/components/editor/timeline/TrackClipSelectionMenu.test.tsx
index a1820267..93b703d3 100644
--- a/apps/web/src/components/editor/timeline/TrackClipSelectionMenu.test.tsx
+++ b/apps/web/src/components/editor/timeline/TrackClipSelectionMenu.test.tsx
@@ -3,6 +3,7 @@ import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { Clip, Project, TextClip, Track } from "@openreel/core";
import type { ToolcraftContextMenuOption as ContextMenuOption } from "@openreel/ui";
+import { useEngineStore } from "../../../stores/engine-store";
import { createEmptyProject } from "../../../stores/project/project-helpers";
import { useProjectStore } from "../../../stores/project-store";
import { useUIStore } from "../../../stores/ui-store";
@@ -96,7 +97,7 @@ function testProject(): Project {
},
],
},
- textClips: [caption("caption-a", 0), caption("caption-b", 2)],
+ textClips: [],
};
}
@@ -112,12 +113,17 @@ function menuAction(items: ContextMenuOption[], label: string): () => void {
describe("select all clips on track context menu", () => {
beforeEach(() => {
+ useEngineStore
+ .getState()
+ .getTitleEngine()
+ ?.loadTextClips([caption("caption-a", 0), caption("caption-b", 2)]);
useProjectStore.setState({ project: testProject(), hasOpenProject: true });
useUIStore.getState().clearSelection();
});
afterEach(() => {
cleanup();
+ useEngineStore.getState().getTitleEngine()?.clear();
useUIStore.getState().clearSelection();
});
@@ -135,7 +141,7 @@ describe("select all clips on track context menu", () => {
});
it("selects all editable captions from a caption menu", () => {
- const clip = useProjectStore.getState().project.textClips?.[0];
+ const clip = useProjectStore.getState().getAllTextClips()[0];
if (!clip) throw new Error("Caption fixture was not created");
const { result } = renderHook(() =>
useGraphicsClipContextMenuItems({ clip, clipType: "text" }),
diff --git a/apps/web/src/components/editor/timeline/TrackHeader.audio.test.tsx b/apps/web/src/components/editor/timeline/TrackHeader.audio.test.tsx
index cb6e8dad..504f050f 100644
--- a/apps/web/src/components/editor/timeline/TrackHeader.audio.test.tsx
+++ b/apps/web/src/components/editor/timeline/TrackHeader.audio.test.tsx
@@ -10,7 +10,28 @@ function audioTrack(id: string, name: string): Track {
id,
type: "audio",
name,
- clips: [],
+ clips: [
+ {
+ id: `${id}-clip`,
+ mediaId: `${id}-media`,
+ trackId: id,
+ startTime: 0,
+ duration: 5,
+ inPoint: 0,
+ outPoint: 5,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ },
+ ],
transitions: [],
locked: false,
hidden: false,
@@ -41,6 +62,27 @@ describe("TrackHeader audio controls", () => {
hasOpenProject: true,
project: {
...project,
+ mediaLibrary: {
+ items: ["dialogue", "music"].map((id) => ({
+ id: `${id}-media`,
+ name: id,
+ type: "audio" as const,
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 5,
+ width: 0,
+ height: 0,
+ frameRate: 0,
+ codec: "aac",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ })),
+ },
timeline: {
...project.timeline,
tracks: [audioTrack("dialogue", "Dialogue"), audioTrack("music", "Music")],
diff --git a/apps/web/src/components/editor/timeline/TrackHeader.tsx b/apps/web/src/components/editor/timeline/TrackHeader.tsx
index 7cf4cd98..1129aa34 100644
--- a/apps/web/src/components/editor/timeline/TrackHeader.tsx
+++ b/apps/web/src/components/editor/timeline/TrackHeader.tsx
@@ -6,6 +6,11 @@ import {
} from "@openreel/ui";
import { ToolcraftTextInputControl } from "@openreel/ui";
import type { Track } from "@openreel/core";
+import {
+ getTrackItems,
+ trackHasAudioItems,
+ trackHasVisualItems,
+} from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { useTimelineStore } from "../../../stores/timeline-store";
import { getTrackInfo } from "./utils";
@@ -46,24 +51,18 @@ export const TrackHeader: React.FC<TrackHeaderProps> = ({
const inputRef = useRef<HTMLInputElement>(null);
const trackInfo = getTrackInfo(track, index);
- const isVisual =
- track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics";
- const isAudio = track.type === "audio";
+ const isVisual = trackHasVisualItems(project, track.id);
+ const isAudio = trackHasAudioItems(project, track.id);
const hasSoloedAudioTrack = project.timeline.tracks.some(
- (candidate) => candidate.type === "audio" && candidate.solo,
+ (candidate) =>
+ trackHasAudioItems(project, candidate.id) && candidate.solo,
);
const effectivelyMuted =
isAudio && (track.muted || (hasSoloedAudioTrack && !track.solo));
const groupCandidates = project.timeline.tracks.filter(
(candidate) =>
candidate.id !== track.id &&
- candidate.groupId !== track.groupId &&
- (track.type === "text"
- ? candidate.type !== "text" && candidate.type !== "graphics"
- : candidate.type === "text"),
+ candidate.groupId !== track.groupId,
);
const handleRemoveTrack = async () => {
@@ -76,15 +75,15 @@ export const TrackHeader: React.FC<TrackHeaderProps> = ({
// Only enable "Remove Gaps" if there's actually a gap on this track.
const hasGaps = React.useMemo(() => {
- if (track.clips.length === 0) return false;
- const sorted = [...track.clips].sort((a, b) => a.startTime - b.startTime);
+ const sorted = getTrackItems(project, track.id);
+ if (sorted.length === 0) return false;
if (sorted[0].startTime > 0.0001) return true;
for (let i = 1; i < sorted.length; i++) {
const prevEnd = sorted[i - 1].startTime + sorted[i - 1].duration;
if (sorted[i].startTime - prevEnd > 0.0001) return true;
}
return false;
- }, [track.clips]);
+ }, [project, track.id]);
const startRename = () => {
setRenameValue(track.name);
diff --git a/apps/web/src/components/editor/timeline/TrackLane.tsx b/apps/web/src/components/editor/timeline/TrackLane.tsx
index f9ccce81..681fa16c 100644
--- a/apps/web/src/components/editor/timeline/TrackLane.tsx
+++ b/apps/web/src/components/editor/timeline/TrackLane.tsx
@@ -6,6 +6,10 @@ import type {
SVGClip,
StickerClip,
} from "@openreel/core";
+import {
+ getMediaItemCapabilities,
+ resolveTimelinePlacement,
+} from "@openreel/core";
import { ClipComponent } from "./ClipComponent";
import { TextClipComponent } from "./TextClipComponent";
import { ShapeClipComponent } from "./ShapeClipComponent";
@@ -36,8 +40,12 @@ interface TrackLaneProps {
clipId: string,
newStartTime: number,
targetTrackId?: string,
- ) => void;
- onMoveTextClip: (clipId: string, newStartTime: number) => void;
+ ) => void | Promise<void>;
+ onMoveTextClip: (
+ clipId: string,
+ newStartTime: number,
+ targetTrackId?: string,
+ ) => void | Promise<void>;
onSnapIndicator: (time: number | null) => void;
onTrimClip?: (
clipId: string,
@@ -96,6 +104,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
const isExpanded = isTrackExpanded(track.id);
const { snapSettings } = useUIStore();
const [isDragOver, setIsDragOver] = useState(false);
+ const [dropHint, setDropHint] = useState("Drop to add clip");
const [isResizing, setIsResizing] = useState(false);
const laneRef = useRef<HTMLDivElement>(null);
const resizeStartY = useRef<number>(0);
@@ -104,24 +113,65 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
(state.project.adjustmentLayers ?? []).filter((layer) => layer.trackId === track.id),
);
const frameRate = useProjectStore((state) => state.project.settings.frameRate);
+ const mediaItems = useProjectStore((state) => state.project.mediaLibrary.items);
const clipsWithKeyframes = useMemo(() => {
return track.clips.filter((clip) => clip.keyframes && clip.keyframes.length > 0);
}, [track.clips]);
const transitionHandles = useMemo(
- () => resolveTransitionHandles(track, pixelsPerSecond),
- [track, pixelsPerSecond],
+ () =>
+ resolveTransitionHandles(track, pixelsPerSecond, (clip) =>
+ getMediaItemCapabilities(
+ mediaItems.find((item) => item.id === clip.mediaId),
+ ).visual,
+ ),
+ [track, pixelsPerSecond, mediaItems],
);
- const handleDragOver = useCallback((e: React.DragEvent) => {
- e.preventDefault();
- e.dataTransfer.dropEffect = "copy";
- setIsDragOver(true);
- }, []);
+ const handleDragOver = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ setIsDragOver(true);
+ try {
+ const payload = JSON.parse(e.dataTransfer.getData("application/json"));
+ const mediaId = typeof payload?.mediaId === "string" ? payload.mediaId : "";
+ const mediaItem = mediaItems.find((item) => item.id === mediaId);
+ const rect = laneRef.current?.getBoundingClientRect();
+ if (!mediaItem || !rect) {
+ setDropHint("Drop to add clip");
+ return;
+ }
+ const startTime = Math.max(
+ 0,
+ (e.clientX - rect.left + scrollX) / pixelsPerSecond,
+ );
+ const duration =
+ mediaItem.metadata.duration > 0 ? mediaItem.metadata.duration : 5;
+ const project = useProjectStore.getState().project;
+ const placement = resolveTimelinePlacement(project, {
+ targetTrackId: track.id,
+ startTime,
+ duration,
+ policy: "stack-above",
+ newTrackId: "placement-preview",
+ });
+ setDropHint(
+ placement.ok && placement.trackId !== track.id
+ ? "Place above"
+ : "Drop to add clip",
+ );
+ } catch {
+ setDropHint("Drop to add clip");
+ }
+ },
+ [mediaItems, pixelsPerSecond, scrollX, track.id],
+ );
const handleDragLeave = useCallback(() => {
setIsDragOver(false);
+ setDropHint("Drop to add clip");
}, []);
const handleDrop = useCallback(
@@ -129,6 +179,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
+ setDropHint("Drop to add clip");
// External OS file drop (e.g. from Windows Explorer)
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
@@ -144,7 +195,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
snapSettings,
pixelsPerSecond,
);
- const { importMedia, addClip } = useProjectStore.getState();
+ const { importMedia, placeMediaClip } = useProjectStore.getState();
for (const file of Array.from(e.dataTransfer.files)) {
try {
const beforeIds = new Set(
@@ -156,7 +207,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
.getState()
.project.mediaLibrary.items.find(i => !beforeIds.has(i.id));
if (newItem) {
- await addClip(track.id, newItem.id, snapResult.time);
+ await placeMediaClip(newItem.id, track.id, snapResult.time);
toast.success(`Added to ${track.name}`, file.name);
}
}
@@ -200,7 +251,16 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
// Silently ignore parse errors
}
},
- [track.id, track.name, pixelsPerSecond, scrollX, onDropMedia],
+ [
+ allTracks,
+ onDropMedia,
+ pixelsPerSecond,
+ playheadPosition,
+ scrollX,
+ snapSettings,
+ track.id,
+ track.name,
+ ],
);
const handleResizeStart = useCallback(
@@ -282,6 +342,9 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
onSelect={onSelectClip}
onTrim={onTrimTextClip}
onMoveClip={onMoveTextClip}
+ allTracks={allTracks}
+ trackHeights={trackHeights}
+ timelineRef={timelineRef}
/>
))}
{shapeClips.map((shapeClip) => (
@@ -293,6 +356,9 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
onSelect={onSelectClip}
onTrim={onTrimShapeClip}
onMoveClip={onMoveClip}
+ allTracks={allTracks}
+ trackHeights={trackHeights}
+ timelineRef={timelineRef}
/>
))}
{adjustmentLayers.map((layer) => {
@@ -311,8 +377,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
/>
);
})}
- {track.type === "video" &&
- transitionHandles.map((handle) => (
+ {transitionHandles.map((handle) => (
<TransitionHandle
key={
handle.clipB
@@ -332,7 +397,7 @@ export const TrackLane: React.FC<TrackLaneProps> = ({
{isDragOver && (
<div className="absolute inset-0 border-2 border-dashed border-primary/50 rounded pointer-events-none flex items-center justify-center">
<span className="text-xs text-primary bg-background/80 px-2 py-1 rounded">
- Drop to add clip
+ {dropHint}
</span>
</div>
)}
diff --git a/apps/web/src/components/editor/timeline/transition-handles.test.ts b/apps/web/src/components/editor/timeline/transition-handles.test.ts
index 19d794a5..0f7abe49 100644
--- a/apps/web/src/components/editor/timeline/transition-handles.test.ts
+++ b/apps/web/src/components/editor/timeline/transition-handles.test.ts
@@ -113,4 +113,24 @@ describe("resolveTransitionHandles", () => {
);
expect(result).toHaveLength(1);
});
+
+ it("builds adjacency from eligible visual clips on a mixed track", () => {
+ const video = clip("video", 0, 2);
+ const audio = clip("audio", 2, 1);
+ const image = clip("image", 2, 3);
+
+ const result = resolveTransitionHandles(
+ track(
+ [video, audio, image],
+ [transition("visual-transition", "video", "image")],
+ ),
+ 50,
+ (candidate) => candidate.id !== "audio",
+ );
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.transition?.id).toBe("visual-transition");
+ expect(result[0]?.clipA.id).toBe("video");
+ expect(result[0]?.clipB?.id).toBe("image");
+ });
});
diff --git a/apps/web/src/components/editor/timeline/transition-handles.ts b/apps/web/src/components/editor/timeline/transition-handles.ts
index 94b93382..1aa3f7e3 100644
--- a/apps/web/src/components/editor/timeline/transition-handles.ts
+++ b/apps/web/src/components/editor/timeline/transition-handles.ts
@@ -13,10 +13,11 @@ export interface ResolvedTransitionHandle {
export function resolveTransitionHandles(
track: Track,
pixelsPerSecond: number,
+ isEligibleClip: (clip: Clip) => boolean = () => true,
): ResolvedTransitionHandle[] {
- const sorted = [...track.clips].sort(
- (a, b) => a.startTime - b.startTime || a.id.localeCompare(b.id),
- );
+ const sorted = track.clips
+ .filter(isEligibleClip)
+ .sort((a, b) => a.startTime - b.startTime || a.id.localeCompare(b.id));
const handles: ResolvedTransitionHandle[] = [];
for (let i = 0; i < sorted.length - 1; i++) {
diff --git a/apps/web/src/components/editor/timeline/utils.test.ts b/apps/web/src/components/editor/timeline/utils.test.ts
new file mode 100644
index 00000000..f1b68ed3
--- /dev/null
+++ b/apps/web/src/components/editor/timeline/utils.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { getClipWaveformBarAmplitudes } from "./utils";
+
+describe("getClipWaveformBarAmplitudes", () => {
+ it("keeps silent waveform buckets at zero", () => {
+ expect(
+ getClipWaveformBarAmplitudes(new Float32Array(100), {
+ barCount: 5,
+ mediaDuration: 10,
+ inPoint: 0,
+ outPoint: 10,
+ }),
+ ).toEqual([0, 0, 0, 0, 0]);
+ });
+
+ it("does not invent a waveform while source data is unavailable", () => {
+ expect(
+ getClipWaveformBarAmplitudes(null, {
+ barCount: 4,
+ mediaDuration: 10,
+ inPoint: 0,
+ outPoint: 10,
+ }),
+ ).toEqual([0, 0, 0, 0]);
+ });
+
+ it("samples only the source range used by a trimmed clip", () => {
+ expect(
+ getClipWaveformBarAmplitudes(
+ new Float32Array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),
+ {
+ barCount: 4,
+ mediaDuration: 10,
+ inPoint: 2,
+ outPoint: 6,
+ },
+ ),
+ ).toEqual([
+ expect.closeTo(0.2),
+ expect.closeTo(0.3),
+ expect.closeTo(0.4),
+ expect.closeTo(0.5),
+ ]);
+ });
+
+ it("aggregates peaks and reverses their display order when needed", () => {
+ expect(
+ getClipWaveformBarAmplitudes(new Float32Array([0, 0.8, 0, 0.4]), {
+ barCount: 2,
+ mediaDuration: 4,
+ inPoint: 0,
+ outPoint: 4,
+ reversed: true,
+ }),
+ ).toEqual([expect.closeTo(0.4), expect.closeTo(0.8)]);
+ });
+});
diff --git a/apps/web/src/components/editor/timeline/utils.ts b/apps/web/src/components/editor/timeline/utils.ts
index 2f2889ca..af844593 100644
--- a/apps/web/src/components/editor/timeline/utils.ts
+++ b/apps/web/src/components/editor/timeline/utils.ts
@@ -134,6 +134,82 @@ export const generateWaveformPath = (
return points.join(" ");
};
+interface ClipWaveformBarOptions {
+ barCount: number;
+ mediaDuration: number;
+ inPoint: number;
+ outPoint: number;
+ reversed?: boolean;
+}
+
+/**
+ * Samples the source-media waveform over the range represented by a timeline
+ * clip. Each bar uses the highest peak in its source-time bucket so short
+ * transients remain visible while genuinely silent buckets stay at zero.
+ */
+export const getClipWaveformBarAmplitudes = (
+ waveformData: Float32Array | number[] | null | undefined,
+ options: ClipWaveformBarOptions,
+): number[] => {
+ const barCount = Math.max(0, Math.floor(options.barCount));
+ if (barCount === 0) return [];
+
+ if (
+ !waveformData ||
+ waveformData.length === 0 ||
+ !Number.isFinite(options.mediaDuration) ||
+ options.mediaDuration <= 0
+ ) {
+ return Array.from({ length: barCount }, () => 0);
+ }
+
+ const mediaDuration = options.mediaDuration;
+ const sourceStart = Math.max(0, Math.min(mediaDuration, options.inPoint));
+ const sourceEnd = Math.max(
+ sourceStart,
+ Math.min(mediaDuration, options.outPoint),
+ );
+ const sourceDuration = sourceEnd - sourceStart;
+
+ if (sourceDuration <= 0) {
+ return Array.from({ length: barCount }, () => 0);
+ }
+
+ return Array.from({ length: barCount }, (_, barIndex) => {
+ const displayIndex = options.reversed
+ ? barCount - barIndex - 1
+ : barIndex;
+ const bucketStartTime =
+ sourceStart + (displayIndex / barCount) * sourceDuration;
+ const bucketEndTime =
+ sourceStart + ((displayIndex + 1) / barCount) * sourceDuration;
+ const startSample = Math.max(
+ 0,
+ Math.min(
+ waveformData.length - 1,
+ Math.floor((bucketStartTime / mediaDuration) * waveformData.length),
+ ),
+ );
+ const endSample = Math.max(
+ startSample + 1,
+ Math.min(
+ waveformData.length,
+ Math.ceil((bucketEndTime / mediaDuration) * waveformData.length),
+ ),
+ );
+
+ let peak = 0;
+ for (let sampleIndex = startSample; sampleIndex < endSample; sampleIndex++) {
+ const sample = Number(waveformData[sampleIndex]);
+ if (Number.isFinite(sample)) {
+ peak = Math.max(peak, Math.abs(sample));
+ }
+ }
+
+ return Math.min(1, peak);
+ });
+};
+
export const formatTimecode = (
timeInSeconds: number,
frameRate: number = 30,
@@ -153,6 +229,15 @@ export const formatTimecode = (
};
export const getTrackInfo = (track: Track, index: number): TrackInfo => {
+ if (track.mode === "standard") {
+ return {
+ label: `T${index + 1}`,
+ icon: Layers,
+ color: "bg-fg-muted",
+ textColor: "text-fg-2",
+ bgLight: "bg-fg-muted/10",
+ };
+ }
switch (track.type) {
case "video":
return {
diff --git a/apps/web/src/config/api-endpoints.ts b/apps/web/src/config/api-endpoints.ts
index a8917081..d84b2cb1 100644
--- a/apps/web/src/config/api-endpoints.ts
+++ b/apps/web/src/config/api-endpoints.ts
@@ -12,14 +12,6 @@ export const OPENREEL_CLOUD_URL = isDev
? "http://localhost:8787"
: "https://api.openreel.video";
-/** OpenReel transcription / TTS service */
-export const OPENREEL_TTS_URL =
- import.meta.env.VITE_OPENREEL_TTS_URL ||
- (isDev ? "http://127.0.0.1:18000" : "https://cloud.openreel.video");
-
-/** OpenReel transcription service (GPU) */
-export const OPENREEL_TRANSCRIBE_URL = "https://cloud.openreel.video";
-
/**
* Third-party API base URLs.
* These are used by the api-proxy service in dev mode (direct calls)
diff --git a/apps/web/src/desktop/DesktopApp.test.tsx b/apps/web/src/desktop/DesktopApp.test.tsx
index 135a52cb..03118239 100644
--- a/apps/web/src/desktop/DesktopApp.test.tsx
+++ b/apps/web/src/desktop/DesktopApp.test.tsx
@@ -44,7 +44,14 @@ function mockHasProject(value: boolean): void {
}
beforeEach(() => {
- useUIStore.setState({ desktopPage: "edit" });
+ const panels = useUIStore.getState().panels;
+ useUIStore.setState({
+ desktopPage: "edit",
+ panels: {
+ ...panels,
+ agentChat: { ...panels.agentChat, visible: false },
+ },
+ });
useSettingsStore.setState({ settingsOpen: false, settingsTab: "general" });
(window as unknown as { openreel: unknown }).openreel = {
platform: "desktop",
@@ -90,6 +97,21 @@ describe("DesktopApp", () => {
).toBeNull();
});
+ it("toggles the AI Editor side panel from the desktop title bar", () => {
+ mockHasProject(true);
+ const view = render(<DesktopApp />);
+ const button = view.getByRole("button", { name: "AI Editor" });
+
+ expect(button).toHaveAttribute("aria-pressed", "false");
+ fireEvent.click(button);
+
+ expect(useUIStore.getState().panels.agentChat.visible).toBe(true);
+ expect(button).toHaveAttribute("aria-pressed", "true");
+
+ fireEvent.click(button);
+ expect(useUIStore.getState().panels.agentChat.visible).toBe(false);
+ });
+
it("keeps settings reachable from the desktop title bar", () => {
mockHasProject(false);
const view = render(<DesktopApp />);
diff --git a/apps/web/src/desktop/DesktopApp.tsx b/apps/web/src/desktop/DesktopApp.tsx
index e92594d1..7376019d 100644
--- a/apps/web/src/desktop/DesktopApp.tsx
+++ b/apps/web/src/desktop/DesktopApp.tsx
@@ -13,12 +13,11 @@ import { installRendererCrashHandlers, reportRendererCrash } from "./crash-repor
import { installMcpListener } from "../services/agent/mcp-listener";
import { getLiveEditorHost } from "../services/agent/host-singleton";
import { createExportJobRunner } from "../services/agent/export-job-runner";
-import { useGpuJobPoller } from "../hooks/useGpuJobPoller";
import { useUIStore } from "../stores/ui-store";
import { useSettingsStore } from "../stores/settings-store";
import { SettingsDialog } from "../components/editor/settings/SettingsDialog";
import { ToolcraftButton as Button } from "@openreel/ui";
-import { Settings } from "@/icons/lucide-compat";
+import { Settings, Sparkles } from "@/icons/lucide-compat";
import "./theme/desktop-theme.css";
function detectPlatform(): string {
@@ -31,9 +30,12 @@ export function DesktopApp(): JSX.Element {
const platform = detectPlatform();
const hasProject = useProjectStore((state) => state.hasOpenProject);
const desktopPage = useUIStore((state) => state.desktopPage);
+ const agentChatVisible = useUIStore(
+ (state) => state.panels.agentChat?.visible ?? false,
+ );
+ const togglePanel = useUIStore((state) => state.togglePanel);
const isVideoEditing = desktopPage !== "motion";
- useGpuJobPoller();
// Drive native-menu actions into the app: undo/redo hit the project store
// directly; new/open/export are broadcast as events for the relevant UI to
@@ -94,6 +96,17 @@ export function DesktopApp(): JSX.Element {
return (
<div className="openreel-desktop isolate flex h-screen w-screen flex-col overflow-hidden bg-bg text-fg">
<DesktopTitleBar platform={platform}>
+ {hasProject && isVideoEditing ? (
+ <Button
+ label="AI Editor"
+ variant={agentChatVisible ? "primary" : "secondary"}
+ size="sm"
+ icon={<Sparkles size={15} aria-hidden />}
+ onClick={() => togglePanel("agentChat")}
+ className="mr-2"
+ aria-pressed={agentChatVisible}
+ />
+ ) : null}
{hasProject && isVideoEditing ? <DesktopExportButton /> : null}
<Button
label="Settings"
diff --git a/apps/web/src/desktop/pages/EditPage.test.tsx b/apps/web/src/desktop/pages/EditPage.test.tsx
new file mode 100644
index 00000000..138f86e9
--- /dev/null
+++ b/apps/web/src/desktop/pages/EditPage.test.tsx
@@ -0,0 +1,62 @@
+import "../../test/install-local-storage-mock";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { useUIStore } from "../../stores/ui-store";
+
+vi.mock("../../components/editor/AssetsPanel", () => ({
+ AssetsPanel: () => <div>Media panel</div>,
+}));
+vi.mock("../../components/editor/InspectorPanel", () => ({
+ InspectorPanel: () => <div>Inspector panel</div>,
+}));
+vi.mock("../../components/editor/Preview", () => ({
+ Preview: () => <div>Preview panel</div>,
+}));
+vi.mock("../../components/editor/Timeline", () => ({
+ Timeline: () => <div>Timeline panel</div>,
+}));
+vi.mock("../../components/editor/chat/ChatPanel", () => ({
+ ChatPanel: ({ onClose }: { onClose?: () => void }) => (
+ <div data-testid="desktop-ai-editor">
+ <button type="button" onClick={onClose}>Close AI Editor</button>
+ </div>
+ ),
+}));
+
+import { EditPage } from "./EditPage";
+
+describe("EditPage AI Editor dock", () => {
+ beforeEach(() => {
+ const panels = useUIStore.getState().panels;
+ useUIStore.setState({
+ panels: {
+ ...panels,
+ agentChat: { ...panels.agentChat, visible: true },
+ },
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ window.localStorage.clear();
+ });
+
+ it("renders the chat as a resizable right-side panel and closes it", async () => {
+ render(<EditPage />);
+
+ expect(await screen.findByTestId("desktop-ai-editor")).toBeTruthy();
+ expect(screen.getByTestId("desktop-edit-page").style.gridTemplateAreas).toContain(
+ "chat",
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Close AI Editor" }));
+
+ await waitFor(() => {
+ expect(screen.queryByTestId("desktop-ai-editor")).toBeNull();
+ });
+ expect(useUIStore.getState().panels.agentChat.visible).toBe(false);
+ expect(screen.getByTestId("desktop-edit-page").style.gridTemplateAreas).not.toContain(
+ "chat",
+ );
+ });
+});
diff --git a/apps/web/src/desktop/pages/EditPage.tsx b/apps/web/src/desktop/pages/EditPage.tsx
index 6c5268c0..fe76577e 100644
--- a/apps/web/src/desktop/pages/EditPage.tsx
+++ b/apps/web/src/desktop/pages/EditPage.tsx
@@ -7,6 +7,7 @@ import { AssetsPanel } from "../../components/editor/AssetsPanel";
import { InspectorPanel } from "../../components/editor/InspectorPanel";
import { PanelErrorBoundary } from "../../components/ErrorBoundary";
import { Icon } from "@/icons/Icon";
+import { useUIStore } from "../../stores/ui-store";
import { useResizable } from "../editor/useResizable";
const Preview = lazy(() =>
@@ -15,6 +16,11 @@ const Preview = lazy(() =>
const Timeline = lazy(() =>
import("../../components/editor/Timeline").then((m) => ({ default: m.Timeline })),
);
+const ChatPanel = lazy(() =>
+ import("../../components/editor/chat/ChatPanel").then((m) => ({
+ default: m.ChatPanel,
+ })),
+);
function PanelLoading(): JSX.Element {
return (
@@ -93,6 +99,10 @@ function RowHandle({
}
export function EditPage(): JSX.Element {
+ const chatVisible = useUIStore(
+ (state) => state.panels.agentChat?.visible ?? false,
+ );
+ const setPanelVisible = useUIStore((state) => state.setPanelVisible);
const mediaW = useResizable({
initial: 320,
min: 220,
@@ -109,6 +119,14 @@ export function EditPage(): JSX.Element {
direction: -1,
storageKey: "openreel-desktop-inspector-w",
});
+ const chatW = useResizable({
+ initial: 380,
+ min: 320,
+ max: 560,
+ axis: "x",
+ direction: -1,
+ storageKey: "openreel-desktop-chat-w",
+ });
const timelineH = useResizable({
initial: 320,
min: 160,
@@ -118,14 +136,26 @@ export function EditPage(): JSX.Element {
storageKey: "openreel-desktop-timeline-h",
});
- const gridStyle: React.CSSProperties = {
- gridTemplateColumns: `${mediaW.value}px 1fr ${inspectorW.value}px`,
- gridTemplateRows: `1fr ${timelineH.value}px`,
- gridTemplateAreas: "'media stage inspector' 'timeline timeline timeline'",
- };
+ const gridStyle: React.CSSProperties = chatVisible
+ ? {
+ gridTemplateColumns: `${mediaW.value}px 1fr ${inspectorW.value}px ${chatW.value}px`,
+ gridTemplateRows: `1fr ${timelineH.value}px`,
+ gridTemplateAreas:
+ "'media stage inspector chat' 'timeline timeline timeline timeline'",
+ }
+ : {
+ gridTemplateColumns: `${mediaW.value}px 1fr ${inspectorW.value}px`,
+ gridTemplateRows: `1fr ${timelineH.value}px`,
+ gridTemplateAreas:
+ "'media stage inspector' 'timeline timeline timeline'",
+ };
return (
- <div className="grid h-full min-h-0 w-full gap-px overflow-hidden bg-border" style={gridStyle}>
+ <div
+ className="grid h-full min-h-0 w-full gap-px overflow-hidden bg-border"
+ style={gridStyle}
+ data-testid="desktop-edit-page"
+ >
<DockRegion label="Media" name="Media" area="media" icon="photo.on.rectangle">
<AssetsPanel />
<ColumnHandle edge="right" onPointerDown={mediaW.onHandlePointerDown} />
@@ -142,6 +172,22 @@ export function EditPage(): JSX.Element {
<ColumnHandle edge="left" onPointerDown={inspectorW.onHandlePointerDown} />
</DockRegion>
+ {chatVisible ? (
+ <div
+ className="relative flex min-h-0 min-w-0 flex-col overflow-hidden bg-bg-1"
+ style={{ gridArea: "chat" }}
+ >
+ <PanelErrorBoundary name="AI Editor">
+ <Suspense fallback={<PanelLoading />}>
+ <ChatPanel
+ onClose={() => setPanelVisible("agentChat", false)}
+ />
+ </Suspense>
+ </PanelErrorBoundary>
+ <ColumnHandle edge="left" onPointerDown={chatW.onHandlePointerDown} />
+ </div>
+ ) : null}
+
<DockRegion label="Timeline" name="Timeline" area="timeline" icon="rectangle.split.3x1" className="bg-tl-bg">
<Suspense fallback={<PanelLoading />}>
<Timeline />
diff --git a/apps/web/src/hooks/useGpuJobPoller.test.ts b/apps/web/src/hooks/useGpuJobPoller.test.ts
deleted file mode 100644
index 474a6e22..00000000
--- a/apps/web/src/hooks/useGpuJobPoller.test.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { renderHook, act } from "@testing-library/react";
-import { useGpuJobPoller } from "./useGpuJobPoller";
-import { useGpuJobStore } from "../stores/gpu-job-store";
-import { useProjectStore } from "../stores/project-store";
-import { createEmptyProject } from "../stores/project/project-helpers";
-
-const importGpuResult = vi.fn(async (..._args: unknown[]) => undefined);
-vi.mock("../services/gpu-result-import", () => ({
- importGpuResult: (...args: unknown[]) => importGpuResult(...args),
-}));
-
-const PROJECT_ID = "test-project-id";
-
-function installDesktopBridge(gpu: Record<string, unknown>): void {
- (window as unknown as { openreel: unknown }).openreel = {
- platform: "desktop",
- gpu,
- fs: {
- readFileBytes: vi.fn(async () => new ArrayBuffer(8)),
- },
- };
-}
-
-function seedProject(): void {
- const project = { ...createEmptyProject("Poller Test"), id: PROJECT_ID };
- useProjectStore.setState({ project });
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- importGpuResult.mockClear();
- useGpuJobStore.setState({ jobs: [] });
- seedProject();
-});
-
-afterEach(() => {
- vi.runOnlyPendingTimers();
- vi.useRealTimers();
- delete (window as unknown as { openreel?: unknown }).openreel;
-});
-
-describe("useGpuJobPoller", () => {
- it("schedules polling for a job added AFTER the hook mounts (store-reactive)", async () => {
- const jobStatus = vi.fn(async () => ({ jobID: "job-1", status: "processing" }));
- installDesktopBridge({
- jobStatus,
- fetchManifest: vi.fn(),
- downloadArtifact: vi.fn(),
- });
-
- renderHook(() => useGpuJobPoller());
-
- expect(jobStatus).not.toHaveBeenCalled();
-
- act(() => {
- useGpuJobStore.getState().addJob({
- jobID: "job-1",
- mediaId: "media-1",
- projectId: PROJECT_ID,
- kind: "upscale",
- suggestedName: "Upscaled",
- });
- });
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2000);
- });
-
- expect(jobStatus).toHaveBeenCalledWith("job-1");
- });
-
- it("imports the artifact and removes the job on completion", async () => {
- const jobStatus = vi.fn(async () => ({ jobID: "job-2", status: "completed" }));
- const fetchManifest = vi.fn(async () => ({
- jobID: "job-2",
- kind: "upscale",
- artifacts: [{ type: "video", relativePath: "out/result.mp4" }],
- }));
- const downloadArtifact = vi.fn(async () => ({ tempPath: "/tmp/result.mp4", mime: "video/mp4" }));
- installDesktopBridge({ jobStatus, fetchManifest, downloadArtifact });
-
- renderHook(() => useGpuJobPoller());
-
- act(() => {
- useGpuJobStore.getState().addJob({
- jobID: "job-2",
- mediaId: "media-2",
- projectId: PROJECT_ID,
- kind: "upscale",
- suggestedName: "Upscaled",
- });
- });
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2000);
- });
-
- expect(jobStatus).toHaveBeenCalledWith("job-2");
- expect(downloadArtifact).toHaveBeenCalledWith("job-2", "out/result.mp4");
- expect(importGpuResult).toHaveBeenCalledTimes(1);
- expect(useGpuJobStore.getState().jobs.find((j) => j.jobID === "job-2")).toBeUndefined();
- });
-});
diff --git a/apps/web/src/hooks/useGpuJobPoller.ts b/apps/web/src/hooks/useGpuJobPoller.ts
deleted file mode 100644
index d3d79840..00000000
--- a/apps/web/src/hooks/useGpuJobPoller.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { useEffect, useRef } from "react";
-import { useGpuJobStore } from "../stores/gpu-job-store";
-import { useProjectStore } from "../stores/project-store";
-import { isDesktopGpuAvailable, isGpuAvailable, gpuBackoffMs, isTransientGpuError } from "../services/gpu-jobs";
-import { getWebGpuClient } from "../services/gpu-web-client";
-import { importGpuResult, importGpuStems } from "../services/gpu-result-import";
-import { applyGpuDataResult } from "../services/gpu-data-import";
-import { outputForKind, isMultiAssetKind } from "../components/editor/ai-panel/ai-kinds.config";
-import { artifactIsAudio, isTerminalStatus, normalizeResultManifest, primaryArtifact } from "@openreel/core";
-
-const POLL_BASE_MS = 2000;
-const MAX_RETRIES = 5;
-const MAX_AGE_MS = 30 * 60 * 1000;
-
-export function useGpuJobPoller(): void {
- const jobs = useGpuJobStore((s) => s.jobs);
- const projectId = useProjectStore((s) => s.project?.id);
-
- const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
- const inFlightRef = useRef<Set<string>>(new Set());
-
- useEffect(() => {
- if (!isGpuAvailable()) return;
-
- const desktop = isDesktopGpuAvailable();
- const io = desktop
- ? {
- jobStatus: (id: string): Promise<{ status: string }> => window.openreel!.gpu.jobStatus(id),
- fetchManifest: (id: string): Promise<Record<string, unknown>> => window.openreel!.gpu.fetchManifest(id),
- download: async (id: string, rel: string): Promise<{ bytes: ArrayBuffer; mime: string }> => {
- const { tempPath, mime } = await window.openreel!.gpu.downloadArtifact(id, rel);
- const bytes = await window.openreel!.fs.readFileBytes(tempPath);
- return { bytes, mime };
- },
- }
- : {
- jobStatus: (id: string): Promise<{ status: string }> => getWebGpuClient().jobStatus(id),
- fetchManifest: (id: string): Promise<Record<string, unknown>> => getWebGpuClient().fetchManifest(id),
- download: (id: string, rel: string): Promise<{ bytes: ArrayBuffer; mime: string }> =>
- getWebGpuClient().downloadArtifact(id, rel),
- };
-
- const flagError = (mediaId: string): void => {
- useProjectStore.getState().setKieAIItemState(mediaId, false, true);
- };
-
- const schedule = (jobID: string, delay: number): void => {
- const existing = timersRef.current.get(jobID);
- if (existing) clearTimeout(existing);
- timersRef.current.set(jobID, setTimeout(() => void tick(jobID), delay));
- };
-
- const tick = async (jobID: string): Promise<void> => {
- timersRef.current.delete(jobID);
- if (inFlightRef.current.has(jobID)) return;
-
- const job = useGpuJobStore.getState().jobs.find((j) => j.jobID === jobID);
- if (!job) return;
-
- if (Date.now() - job.createdAt > MAX_AGE_MS) {
- useGpuJobStore.getState().markFailed(jobID);
- flagError(job.mediaId);
- return;
- }
-
- inFlightRef.current.add(jobID);
- try {
- const status = await io.jobStatus(jobID);
-
- if (status.status === "completed") {
- try {
- const rawManifest = await io.fetchManifest(jobID);
- const output = outputForKind(job.kind);
- if (output === "media") {
- const manifest = normalizeResultManifest(rawManifest);
- if (isMultiAssetKind(job.kind)) {
- const audioArts = manifest.artifacts.filter(artifactIsAudio);
- const arts = audioArts.length > 0 ? audioArts : manifest.artifacts;
- const stems: { bytes: ArrayBuffer; mime: string; relativePath: string }[] = [];
- for (const a of arts) {
- const { bytes, mime } = await io.download(jobID, a.relativePath);
- stems.push({ bytes, mime, relativePath: a.relativePath });
- }
- if (stems.length > 0) await importGpuStems({ job, stems });
- } else {
- const art = primaryArtifact(manifest);
- if (art) {
- const { bytes, mime } = await io.download(jobID, art.relativePath);
- await importGpuResult({ job, bytes, mime, relativePath: art.relativePath });
- }
- }
- } else {
- await applyGpuDataResult(output, rawManifest, job);
- }
- useGpuJobStore.getState().removeJob(jobID);
- } catch {
- useGpuJobStore.getState().markFailed(jobID);
- flagError(job.mediaId);
- useGpuJobStore.getState().removeJob(jobID);
- }
- return;
- }
-
- if (isTerminalStatus(status.status)) {
- useGpuJobStore.getState().markFailed(jobID);
- flagError(job.mediaId);
- useGpuJobStore.getState().removeJob(jobID);
- return;
- }
-
- if (job.retries > 0) useGpuJobStore.getState().resetRetries(jobID);
- schedule(jobID, POLL_BASE_MS);
- } catch (err) {
- if (isTransientGpuError(err as { status?: number })) {
- useGpuJobStore.getState().incrementRetry(jobID);
- const retries = useGpuJobStore.getState().jobs.find((j) => j.jobID === jobID)?.retries ?? MAX_RETRIES;
- if (retries >= MAX_RETRIES) {
- useGpuJobStore.getState().markFailed(jobID);
- flagError(job.mediaId);
- } else {
- schedule(jobID, gpuBackoffMs(retries));
- }
- } else {
- useGpuJobStore.getState().markFailed(jobID);
- flagError(job.mediaId);
- }
- } finally {
- inFlightRef.current.delete(jobID);
- }
- };
-
- const activeJobs = jobs.filter((j) => j.projectId === projectId && !j.failed);
-
- for (const job of activeJobs) {
- if (timersRef.current.has(job.jobID)) continue;
- if (inFlightRef.current.has(job.jobID)) continue;
- schedule(job.jobID, POLL_BASE_MS);
- }
-
- for (const [jobID, timer] of timersRef.current) {
- const stillActive = activeJobs.some((j) => j.jobID === jobID);
- if (!stillActive) {
- clearTimeout(timer);
- timersRef.current.delete(jobID);
- }
- }
- }, [jobs, projectId]);
-
- useEffect(() => {
- const timers = timersRef.current;
- return () => {
- for (const timer of timers.values()) clearTimeout(timer);
- timers.clear();
- };
- }, []);
-}
diff --git a/apps/web/src/hooks/useKeyboardShortcuts.ts b/apps/web/src/hooks/useKeyboardShortcuts.ts
index 330240d0..ea217004 100644
--- a/apps/web/src/hooks/useKeyboardShortcuts.ts
+++ b/apps/web/src/hooks/useKeyboardShortcuts.ts
@@ -17,6 +17,7 @@ import {
splitTimelineItem,
trimTimelineItemToPlayhead,
} from "../utils/timeline-item-actions";
+import { editingFrameStepSeconds } from "../components/editor/editing-frame-rate";
export function useKeyboardShortcuts() {
const [showShortcutsOverlay, setShowShortcutsOverlay] = useState(false);
@@ -48,12 +49,12 @@ export function useKeyboardShortcuts() {
}, [togglePlayback]);
const handleFrameBack = useCallback(() => {
- seekRelative(-1 / 30);
- }, [seekRelative]);
+ seekRelative(-editingFrameStepSeconds(project.settings.frameRate));
+ }, [seekRelative, project.settings.frameRate]);
const handleFrameForward = useCallback(() => {
- seekRelative(1 / 30);
- }, [seekRelative]);
+ seekRelative(editingFrameStepSeconds(project.settings.frameRate));
+ }, [seekRelative, project.settings.frameRate]);
const handleSecondBack = useCallback(() => {
seekRelative(-1);
diff --git a/apps/web/src/motion/components/AnimationPresetsPanel.multi-selection.test.tsx b/apps/web/src/motion/components/AnimationPresetsPanel.multi-selection.test.tsx
index b8bb50bc..9f01ee50 100644
--- a/apps/web/src/motion/components/AnimationPresetsPanel.multi-selection.test.tsx
+++ b/apps/web/src/motion/components/AnimationPresetsPanel.multi-selection.test.tsx
@@ -108,4 +108,33 @@ describe("AnimationPresetsPanel multi-selection", () => {
previews.some((preview) => preview.dataset.presetId === "flip-in-3d"),
).toBe(true);
});
+
+ it("uses the duration slider when generating preset keyframes", async () => {
+ render(<AnimationPresetsPanel composition={composition()} />);
+
+ expect(
+ screen.getByRole("slider", { name: "Motion preset duration" }),
+ ).toBeInTheDocument();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Edit Motion preset duration value",
+ }),
+ );
+ const durationInput = screen.getByRole("textbox", {
+ name: "Motion preset duration value",
+ });
+ fireEvent.change(durationInput, { target: { value: "1.2s" } });
+ fireEvent.blur(durationInput);
+ fireEvent.click(screen.getByRole("button", { name: "Apply Fade In" }));
+
+ await waitFor(() => {
+ const stored = useProjectStore
+ .getState()
+ .project.motionCompositions?.find(
+ (candidate) => candidate.id === COMPOSITION_ID,
+ );
+ expect(stored?.layers[0]?.keyframes.at(-1)?.time).toBe(2.7);
+ expect(stored?.layers[1]?.keyframes.at(-1)?.time).toBe(1.7);
+ });
+ });
});
diff --git a/apps/web/src/motion/components/AnimationPresetsPanel.tsx b/apps/web/src/motion/components/AnimationPresetsPanel.tsx
index 2bb04446..21e88552 100644
--- a/apps/web/src/motion/components/AnimationPresetsPanel.tsx
+++ b/apps/web/src/motion/components/AnimationPresetsPanel.tsx
@@ -16,7 +16,11 @@ import {
type MotionAnimationPresetCategory,
type MotionComposition,
} from "@openreel/core";
-import { ToolcraftClickableCard, ToolcraftText } from "@openreel/ui";
+import {
+ ToolcraftClickableCard,
+ ToolcraftSliderControl,
+ ToolcraftText,
+} from "@openreel/ui";
import { useProjectStore } from "../../stores/project-store";
import { useMotionStore } from "../stores/motion-store";
import {
@@ -133,16 +137,18 @@ export function AnimationPresetsPanel({
{embedded ? null : <PanelHeader title="Animation Presets" icon={Sparkles} />}
<div className={embedded ? "" : "min-h-0 flex-1 overflow-auto"}>
<Section title="Timing" icon={MoveUp}>
- <div className="grid grid-cols-3 gap-2.5">
- <Field label="Duration" hint="s">
- <NumberInput
- value={duration}
- min={0.05}
- max={selectedLayer.duration}
- step={0.05}
- onChange={setDuration}
- />
- </Field>
+ <ToolcraftSliderControl
+ ariaLabel="Motion preset duration"
+ label="Duration"
+ value={duration}
+ min={0.05}
+ max={selectedLayer.duration}
+ step={0.05}
+ unit="s"
+ defaultValue={0.6}
+ onChange={setDuration}
+ />
+ <div className="grid grid-cols-2 gap-2.5">
<Field label="Distance" hint="px">
<NumberInput
value={distance}
diff --git a/apps/web/src/motion/components/GenerateShaderBox.test.tsx b/apps/web/src/motion/components/GenerateShaderBox.test.tsx
index 445ab031..d2e2e852 100644
--- a/apps/web/src/motion/components/GenerateShaderBox.test.tsx
+++ b/apps/web/src/motion/components/GenerateShaderBox.test.tsx
@@ -7,6 +7,7 @@ import {
} from "@openreel/core/motion/shaders";
import { createEmptyProject } from "../../stores/project/project-helpers";
import { useProjectStore } from "../../stores/project-store";
+import { useSettingsStore } from "../../stores/settings-store";
const generateAiShaderMock = vi.fn();
const getSecretMock = vi.fn();
@@ -53,6 +54,12 @@ describe("GenerateShaderBox", () => {
makeBYOKClientMock.mockReturnValue({
complete: vi.fn().mockResolvedValue({ text: "{}", toolUses: [], stopReason: "end_turn" }),
});
+ useSettingsStore.setState({
+ defaultLlmProvider: "openai-compatible",
+ llmBaseUrl: "https://gateway.example/v1",
+ llmModel: "tool-capable-model",
+ configuredServices: ["openai-compatible"],
+ });
useProjectStore.setState({
hasOpenProject: true,
@@ -112,6 +119,33 @@ describe("GenerateShaderBox", () => {
expect(onGenerated).not.toHaveBeenCalled();
});
+ it("supports a keyless OpenAI-compatible shader model", async () => {
+ const def = sampleDef();
+ generateAiShaderMock.mockResolvedValue({ ok: true, def });
+ isSessionUnlockedMock.mockReturnValue(false);
+ useSettingsStore.setState({
+ defaultLlmProvider: "openai-compatible",
+ llmBaseUrl: "http://localhost:11434/v1",
+ llmModel: "qwen2.5-coder",
+ configuredServices: [],
+ });
+
+ render(<GenerateShaderBox category="fill" onGenerated={vi.fn()} />);
+ fireEvent.change(screen.getByRole("textbox", { name: "Describe a shader, e.g. holographic foil" }), {
+ target: { value: "iridescent foil" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Generate shader" }));
+
+ await waitFor(() => expect(generateAiShaderMock).toHaveBeenCalledOnce());
+ expect(getSecretMock).not.toHaveBeenCalled();
+ expect(makeBYOKClientMock).toHaveBeenCalledWith({
+ provider: "openai-compatible",
+ model: "qwen2.5-coder",
+ apiKey: "",
+ baseUrl: "http://localhost:11434/v1",
+ });
+ });
+
it("surfaces the service error", async () => {
generateAiShaderMock.mockResolvedValue({ ok: false, error: "shader failed to compile" });
const onGenerated = vi.fn();
diff --git a/apps/web/src/motion/components/GenerateShaderBox.tsx b/apps/web/src/motion/components/GenerateShaderBox.tsx
index f49644b3..fd6e9e6f 100644
--- a/apps/web/src/motion/components/GenerateShaderBox.tsx
+++ b/apps/web/src/motion/components/GenerateShaderBox.tsx
@@ -5,10 +5,9 @@ import type { MotionShaderCategory, MotionShaderDef } from "@openreel/core";
import { ToolcraftText } from "@openreel/ui";
import { generateAiShader, type LlmMessage } from "../../services/ai-shader";
import { makeBYOKClient } from "../../services/agent/llm-transport";
-import { defaultModelFor, modelsFor } from "../../services/agent/models";
import { getSecret, isSessionUnlocked } from "../../services/secure-storage";
import { useProjectStore } from "../../stores/project-store";
-import { useSettingsStore } from "../../stores/settings-store";
+import { useSettingsStore, type LlmProvider } from "../../stores/settings-store";
import { Button, Field, TextInput } from "./primitives";
interface GenerateShaderBoxProps {
@@ -27,21 +26,28 @@ function isDesktop(): boolean {
return typeof window !== "undefined" && window.openreel?.platform === "desktop";
}
-function resolveModel(): { provider: "openai" | "anthropic"; model: string } {
- const provider = useSettingsStore.getState().defaultLlmProvider;
- const storedModel = useSettingsStore.getState().llmModel;
- const model = modelsFor(provider).some((option) => option.id === storedModel)
- ? storedModel
- : defaultModelFor(provider);
- return { provider, model };
+function resolveModel(): {
+ provider: LlmProvider | null;
+ model: string;
+ baseUrl: string;
+} {
+ const settings = useSettingsStore.getState();
+ return {
+ provider: settings.defaultLlmProvider,
+ model: settings.llmModel.trim(),
+ baseUrl: settings.llmBaseUrl,
+ };
}
-async function resolveApiKey(provider: "openai" | "anthropic"): Promise<string | null> {
+async function resolveApiKey(provider: LlmProvider): Promise<string | null> {
if (isDesktop()) return "";
+ const optionalKey =
+ !useSettingsStore.getState().configuredServices.includes(provider);
+ if (optionalKey && !isSessionUnlocked()) return "";
if (!isSessionUnlocked()) return null;
try {
const key = await getSecret(provider);
- return key ?? null;
+ return key ?? (optionalKey ? "" : null);
} catch {
return null;
}
@@ -62,14 +68,18 @@ export function GenerateShaderBox({
setPhase({ kind: "generating" });
- const { provider, model } = resolveModel();
+ const { provider, model, baseUrl } = resolveModel();
+ if (!provider || !model || !baseUrl.trim()) {
+ setPhase({ kind: "error", message: CONFIGURE_PROVIDER });
+ return;
+ }
const apiKey = await resolveApiKey(provider);
- if (apiKey === null || (!isDesktop() && apiKey === "")) {
+ if (apiKey === null) {
setPhase({ kind: "error", message: CONFIGURE_PROVIDER });
return;
}
- const client = makeBYOKClient({ provider, model, apiKey });
+ const client = makeBYOKClient({ provider, model, apiKey, baseUrl });
const send = async (messages: readonly LlmMessage[]): Promise<string> => {
const response = await client.complete({
messages: messages.map((message) => ({
diff --git a/apps/web/src/motion/export-motion-frame.test.ts b/apps/web/src/motion/export-motion-frame.test.ts
index 903d6006..ff068a8d 100644
--- a/apps/web/src/motion/export-motion-frame.test.ts
+++ b/apps/web/src/motion/export-motion-frame.test.ts
@@ -81,6 +81,7 @@ vi.mock("@openreel/core", () => ({
renderAudio: audioEngineRenderAudioMock,
}),
isMotionLayerContentVisible: isMotionLayerContentVisibleMock,
+ trackHasAudioItems: () => false,
motionEngine: {
createInstance: vi.fn((composition, options) => ({
id: "instance-1",
diff --git a/apps/web/src/motion/export-motion-frame.ts b/apps/web/src/motion/export-motion-frame.ts
index 0807004f..4437757a 100644
--- a/apps/web/src/motion/export-motion-frame.ts
+++ b/apps/web/src/motion/export-motion-frame.ts
@@ -14,6 +14,7 @@ import {
DEFAULT_VIDEO_SETTINGS,
getAudioEngine,
getExportEngine,
+ trackHasAudioItems,
isMotionLayerContentVisible,
MotionHighQualityRenderer,
motionEngine,
@@ -475,10 +476,7 @@ async function encodeMotionSceneAudioToNativeBackend(
if (timelineDuration <= 0) return;
const hasAudio = project.timeline.tracks.some(
- (track) =>
- (track.type === "audio" || track.type === "video") &&
- !track.muted &&
- track.clips.length > 0,
+ (track) => !track.muted && trackHasAudioItems(project, track.id),
);
if (!hasAudio) return;
diff --git a/apps/web/src/services/agent/export-job-runner.ts b/apps/web/src/services/agent/export-job-runner.ts
index b900a886..9ce9b688 100644
--- a/apps/web/src/services/agent/export-job-runner.ts
+++ b/apps/web/src/services/agent/export-job-runner.ts
@@ -142,35 +142,40 @@ function nativeBackendFactory() {
);
}
-async function uploadExport(
+async function saveExportLocally(
blob: Blob,
projectName: string | undefined,
ext: string,
contentType: string,
): Promise<JobResult> {
- const bridge = window.openreel?.gpu?.uploadExport;
- if (typeof bridge !== "function") {
- return { ok: false, error: "Export upload is only available in the desktop app" };
- }
+ const bridge = window.openreel?.fs;
+ if (!bridge) return { ok: false, error: "Local export storage is unavailable" };
const filename = `${sanitizeName(projectName)}-${Date.now()}.${ext}`;
- const bytes = await blob.arrayBuffer();
- const { mediaKey, downloadUrl } = await bridge({ bytes, filename, contentType });
- if (!downloadUrl) {
- return {
- ok: false,
- error: `Export uploaded (key ${mediaKey}) but the broker returned no download URL`,
- };
+ const path = await bridge.tempFilePath(ext);
+ const handleId = await bridge.openWrite(path);
+ const reader = blob.stream().getReader();
+ let position = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ await bridge.writeChunk(handleId, value, position);
+ position += value.byteLength;
+ }
+ await bridge.closeWrite(handleId);
+ } catch (error) {
+ await bridge.abortWrite(handleId).catch(() => {});
+ throw error;
}
return {
ok: true,
data: {
- url: downloadUrl,
- mediaKey,
+ path,
filename,
bytes: blob.size,
format: ext,
contentType,
- expiresInSec: 900,
+ storage: "local",
},
};
}
@@ -210,7 +215,7 @@ export function createExportJobRunner(): JobRunner {
if (blob.size === 0) {
return { ok: false, error: "Video export produced no data" };
}
- return await uploadExport(blob, project.name, ext, blob.type || contentType);
+ return await saveExportLocally(blob, project.name, ext, blob.type || contentType);
}
if (kind === "exportAudio") {
@@ -220,7 +225,7 @@ export function createExportJobRunner(): JobRunner {
return { ok: false, error: result.error?.message ?? "Audio export failed" };
}
const ext = (AUDIO_FORMATS.has(format as AudioExportSettings["format"]) ? format : "wav");
- return await uploadExport(result.blob, project.name, ext, result.blob.type || AUDIO_MIME[ext]);
+ return await saveExportLocally(result.blob, project.name, ext, result.blob.type || AUDIO_MIME[ext]);
}
if (kind === "exportFrame") {
diff --git a/apps/web/src/services/agent/live-host.ts b/apps/web/src/services/agent/live-host.ts
index 0ce62468..2dd832b6 100644
--- a/apps/web/src/services/agent/live-host.ts
+++ b/apps/web/src/services/agent/live-host.ts
@@ -29,6 +29,7 @@ import type {
MotionRenderQueueAddResult,
MotionRenderQueueAddError,
MotionRenderQueueRunResult,
+ MulticamHostBridge,
} from "@openreel/agent";
import type { TextStyle, TextAnimationPreset } from "@openreel/core/text/types";
import type { ShapeStyle, ShapeType } from "@openreel/core/graphics/types";
@@ -38,6 +39,7 @@ import type { Action } from "@openreel/core/types/actions";
import type { Project } from "@openreel/core/types/project";
import type { CapabilityManifest } from "@openreel/core/capabilities/manifest";
import { useProjectStore } from "../../stores/project-store";
+import { insertTimelineOverlay } from "../../stores/project/insert-timeline-overlay";
import { checkForRecovery } from "../auto-save";
import { inspectGltfModel } from "../../motion/model-inspection";
import {
@@ -52,6 +54,7 @@ import {
type MotionRenderQueueFormat,
} from "../../motion/stores/motion-store";
import { runMotionRenderQueue } from "../../motion/render-queue-runner";
+import { createMulticamHostBridge } from "./multicam-bridge";
const MIME_BY_EXT: Record<string, string> = {
mp4: "video/mp4",
@@ -144,6 +147,9 @@ function normalizeRenderQueueScale(
export class LiveEditorHost implements EditingHost {
private jobRunner?: JobRunner;
private appliedInTxn = 0;
+ readonly multicam: MulticamHostBridge = createMulticamHostBridge((timeMs) =>
+ this.runJob("exportFrame", { time: timeMs / 1_000 }),
+ );
constructor(options: LiveEditorHostOptions = {}) {
this.jobRunner = options.jobRunner;
@@ -488,38 +494,21 @@ export class LiveEditorHost implements EditingHost {
async createTextOverlay(options: TextOverlayOptions): Promise<OverlayRef> {
this.requireOpenProject();
- const store = useProjectStore.getState();
- const tracks = store.project.timeline.tracks;
-
- let trackId = options.trackId;
- if (!trackId || !tracks.some((t) => t.id === trackId)) {
- const existing = tracks.find((t) => t.type === "text");
- if (existing) {
- trackId = existing.id;
- } else {
- await store.executeAction({
- type: "track/add",
- id: crypto.randomUUID(),
- timestamp: Date.now(),
- params: { trackType: "text" },
- } as Action);
- const created = useProjectStore
+ const clip = await insertTimelineOverlay(
+ options.startSec,
+ options.durationSec,
+ (trackId) =>
+ useProjectStore
.getState()
- .project.timeline.tracks.find((t) => t.type === "text");
- if (!created) throw new Error("Failed to create a text track");
- trackId = created.id;
- }
- }
-
- const clip = useProjectStore
- .getState()
- .createTextClip(
- trackId,
- options.startSec,
- options.text,
- options.durationSec,
- options.style as Partial<TextStyle> | undefined,
- );
+ .createTextClip(
+ trackId,
+ options.startSec,
+ options.text,
+ options.durationSec,
+ options.style as Partial<TextStyle> | undefined,
+ ),
+ options.trackId,
+ );
if (!clip) throw new Error("Failed to create text overlay");
if (options.animation && options.animation !== "none") {
@@ -532,47 +521,30 @@ export class LiveEditorHost implements EditingHost {
options.animationOutSec ?? 0.25,
);
}
- return { id: clip.id, trackId };
+ return { id: clip.id, trackId: clip.trackId };
}
async createShapeOverlay(options: ShapeOverlayOptions): Promise<OverlayRef> {
this.requireOpenProject();
- const store = useProjectStore.getState();
- const tracks = store.project.timeline.tracks;
-
- let trackId = options.trackId;
- if (!trackId || !tracks.some((t) => t.id === trackId)) {
- const existing = tracks.find((t) => t.type === "graphics");
- if (existing) {
- trackId = existing.id;
- } else {
- await store.executeAction({
- type: "track/add",
- id: crypto.randomUUID(),
- timestamp: Date.now(),
- params: { trackType: "graphics" },
- } as Action);
- const created = useProjectStore
- .getState()
- .project.timeline.tracks.find((t) => t.type === "graphics");
- if (!created) throw new Error("Failed to create a graphics track");
- trackId = created.id;
- }
- }
-
const style: Partial<ShapeStyle> = {
fill: { type: "solid", color: options.color ?? "#000000", opacity: options.opacity ?? 0.45 },
stroke: { color: "#000000", width: 0, opacity: 0 },
};
- const clip = useProjectStore
- .getState()
- .createShapeClip(
- trackId,
- options.startSec,
- (options.shapeType ?? "rectangle") as ShapeType,
- options.durationSec,
- style,
- );
+ const clip = await insertTimelineOverlay(
+ options.startSec,
+ options.durationSec,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .createShapeClip(
+ trackId,
+ options.startSec,
+ (options.shapeType ?? "rectangle") as ShapeType,
+ options.durationSec,
+ style,
+ ),
+ options.trackId,
+ );
if (!clip) throw new Error("Failed to create shape overlay");
if (options.fullFrame) {
@@ -585,23 +557,7 @@ export class LiveEditorHost implements EditingHost {
opacity: 1,
});
}
- return { id: clip.id, trackId };
- }
-
- private async ensureOverlayTrack(
- type: "text" | "graphics",
- trackId?: string,
- ): Promise<string> {
- const tracks = useProjectStore.getState().project.timeline.tracks;
- if (trackId && tracks.some((t) => t.id === trackId)) return trackId;
- const existing = tracks.find((t) => t.type === type);
- if (existing) return existing.id;
- await useProjectStore.getState().addTrack(type, 0);
- const created = useProjectStore
- .getState()
- .project.timeline.tracks.find((t) => t.type === type);
- if (!created) throw new Error(`Failed to create a ${type} track`);
- return created.id;
+ return { id: clip.id, trackId: clip.trackId };
}
async updateTextOverlay(
@@ -691,34 +647,40 @@ export class LiveEditorHost implements EditingHost {
options: StickerOverlayOptions,
): Promise<OverlayRef> {
this.requireOpenProject();
- const trackId = await this.ensureOverlayTrack("graphics", options.trackId);
const { stickerLibrary } = await import("@openreel/core");
- const clip = options.imageUrl
- ? stickerLibrary.createStickerClip(
- {
- id: crypto.randomUUID(),
- name: options.name ?? "sticker",
- category: "custom",
- imageUrl: options.imageUrl,
- },
- trackId,
- options.startSec,
- options.durationSec,
- )
- : stickerLibrary.createEmojiClip(
- {
- id: crypto.randomUUID(),
- emoji: options.emoji ?? "⭐",
- name: options.name ?? options.emoji ?? "emoji",
- category: "emojis",
- },
- trackId,
- options.startSec,
- options.durationSec,
- );
- const created = useProjectStore.getState().createStickerClip(clip);
+ const created = await insertTimelineOverlay(
+ options.startSec,
+ options.durationSec,
+ (trackId) => {
+ const clip = options.imageUrl
+ ? stickerLibrary.createStickerClip(
+ {
+ id: crypto.randomUUID(),
+ name: options.name ?? "sticker",
+ category: "custom",
+ imageUrl: options.imageUrl,
+ },
+ trackId,
+ options.startSec,
+ options.durationSec,
+ )
+ : stickerLibrary.createEmojiClip(
+ {
+ id: crypto.randomUUID(),
+ emoji: options.emoji ?? "⭐",
+ name: options.name ?? options.emoji ?? "emoji",
+ category: "emojis",
+ },
+ trackId,
+ options.startSec,
+ options.durationSec,
+ );
+ return useProjectStore.getState().createStickerClip(clip);
+ },
+ options.trackId,
+ );
if (!created) throw new Error("Failed to create sticker overlay");
- return { id: created.id, trackId };
+ return { id: created.id, trackId: created.trackId };
}
async updateStickerOverlay(
@@ -742,12 +704,22 @@ export class LiveEditorHost implements EditingHost {
async createSvgOverlay(options: SvgOverlayOptions): Promise<OverlayRef> {
this.requireOpenProject();
- const trackId = await this.ensureOverlayTrack("graphics", options.trackId);
- const clip = useProjectStore
- .getState()
- .importSVG(options.svg, trackId, options.startSec, options.durationSec);
+ const clip = await insertTimelineOverlay(
+ options.startSec,
+ options.durationSec,
+ (trackId) =>
+ useProjectStore
+ .getState()
+ .importSVG(
+ options.svg,
+ trackId,
+ options.startSec,
+ options.durationSec,
+ ),
+ options.trackId,
+ );
if (!clip) throw new Error("Failed to create SVG overlay");
- return { id: clip.id, trackId };
+ return { id: clip.id, trackId: clip.trackId };
}
async updateSvgOverlay(
diff --git a/apps/web/src/services/agent/llm-transport.test.ts b/apps/web/src/services/agent/llm-transport.test.ts
new file mode 100644
index 00000000..3a0b1107
--- /dev/null
+++ b/apps/web/src/services/agent/llm-transport.test.ts
@@ -0,0 +1,86 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const h = vi.hoisted(() => ({
+ apiFetch: vi.fn(),
+}));
+
+vi.mock("../api-proxy", () => ({
+ apiFetch: h.apiFetch,
+}));
+
+import { makeBYOKClient } from "./llm-transport";
+
+describe("compatible LLM transport", () => {
+ beforeEach(() => {
+ h.apiFetch.mockReset();
+ });
+
+ it("uses OpenAI message formatting for an arbitrary OpenAI-compatible model", async () => {
+ h.apiFetch.mockResolvedValue(
+ Response.json({
+ choices: [{ message: { content: "done" }, finish_reason: "stop" }],
+ }),
+ );
+ const client = makeBYOKClient({
+ provider: "openai-compatible",
+ baseUrl: "https://gateway.example/v1",
+ model: "vendor/custom-tool-model",
+ apiKey: "secret",
+ });
+
+ await expect(
+ client.complete({
+ messages: [{ role: "user", content: "hello" }],
+ tools: [],
+ }),
+ ).resolves.toMatchObject({ text: "done" });
+
+ expect(h.apiFetch).toHaveBeenCalledWith(
+ "openai-compatible",
+ "/chat/completions",
+ "secret",
+ expect.objectContaining({
+ baseUrl: "https://gateway.example/v1",
+ body: expect.stringContaining('"model":"vendor/custom-tool-model"'),
+ }),
+ );
+ });
+
+ it("uses Anthropic message formatting for an arbitrary Anthropic-compatible model", async () => {
+ h.apiFetch.mockResolvedValue(
+ Response.json({
+ content: [{ type: "text", text: "done" }],
+ stop_reason: "end_turn",
+ }),
+ );
+ const client = makeBYOKClient({
+ provider: "anthropic-compatible",
+ baseUrl: "https://gateway.example/v1",
+ model: "gateway/claude-tool-model",
+ apiKey: "secret",
+ });
+
+ await expect(
+ client.complete({
+ system: "edit the video",
+ messages: [{ role: "user", content: "hello" }],
+ tools: [],
+ }),
+ ).resolves.toMatchObject({ text: "done" });
+
+ const body = JSON.parse(
+ (h.apiFetch.mock.calls[0][3] as { body: string }).body,
+ ) as Record<string, unknown>;
+ expect(h.apiFetch).toHaveBeenCalledWith(
+ "anthropic-compatible",
+ "/messages",
+ "secret",
+ expect.objectContaining({ baseUrl: "https://gateway.example/v1" }),
+ );
+ expect(body).toMatchObject({
+ model: "gateway/claude-tool-model",
+ max_tokens: 4096,
+ system: "edit the video",
+ });
+ });
+});
diff --git a/apps/web/src/services/agent/llm-transport.ts b/apps/web/src/services/agent/llm-transport.ts
index 963936ce..26b03643 100644
--- a/apps/web/src/services/agent/llm-transport.ts
+++ b/apps/web/src/services/agent/llm-transport.ts
@@ -9,25 +9,37 @@ import { apiFetch } from "../api-proxy";
import type { LlmProvider } from "../../stores/settings-store";
const PATHS: Record<LlmProvider, string> = {
- anthropic: "/messages",
- openai: "/chat/completions",
+ "openai-compatible": "/chat/completions",
+ "anthropic-compatible": "/messages",
};
function makeSend(
provider: LlmProvider,
apiKey: string,
+ baseUrl?: string,
signal?: AbortSignal,
) {
return async (body: unknown): Promise<unknown> => {
if (signal?.aborted) {
throw new DOMException("Aborted", "AbortError");
}
- const res = await apiFetch(provider, PATHS[provider], apiKey, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- signal,
- });
+ let res: Response;
+ try {
+ res = await apiFetch(provider, PATHS[provider], apiKey, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ baseUrl,
+ signal,
+ });
+ } catch (error) {
+ if (error instanceof TypeError) {
+ throw new Error(
+ "Could not reach the compatible endpoint. Check its URL, availability, and browser CORS settings.",
+ );
+ }
+ throw error;
+ }
if (!res.ok) {
const text = await res.text().catch(() => "");
throw llmHttpError(
@@ -45,23 +57,26 @@ export interface BYOKClientOptions {
readonly provider: LlmProvider;
readonly model: string;
readonly apiKey: string;
+ readonly baseUrl?: string;
readonly maxTokens?: number;
readonly signal?: AbortSignal;
}
/**
* Builds an @openreel/agent LLMClient whose transport routes through the
- * existing BYOK apiFetch (same-origin Pages proxy in prod, keychain on desktop,
- * direct in dev) — keys never leave their existing path.
+ * existing BYOK apiFetch (same-origin Pages proxy for built-ins, direct browser
+ * requests for custom endpoints, and keychain-backed native requests on desktop).
*/
export function makeBYOKClient(opts: BYOKClientOptions): LLMClient {
- const send = withRetry(makeSend(opts.provider, opts.apiKey, opts.signal), {
+ const send = withRetry(makeSend(opts.provider, opts.apiKey, opts.baseUrl, opts.signal), {
signal: opts.signal,
});
return makeClientFromSend({
- provider: opts.provider,
+ provider:
+ opts.provider === "anthropic-compatible" ? "anthropic" : "openai",
model: opts.model,
maxTokens: opts.maxTokens,
+ omitMaxTokens: opts.provider === "openai-compatible" && opts.maxTokens === undefined,
send,
});
}
diff --git a/apps/web/src/services/agent/model-discovery.test.ts b/apps/web/src/services/agent/model-discovery.test.ts
new file mode 100644
index 00000000..135d6df5
--- /dev/null
+++ b/apps/web/src/services/agent/model-discovery.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { discoverCompatibleModels } from "./model-discovery";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("compatible model discovery", () => {
+ it("loads OpenAI-compatible model IDs from GET /models", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ data: [
+ { id: "local/tool-model", owned_by: "local" },
+ { id: "second-model" },
+ ],
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ discoverCompatibleModels({
+ provider: "openai-compatible",
+ baseUrl: "http://localhost:11434/v1/",
+ apiKey: "",
+ }),
+ ).resolves.toEqual([
+ { id: "local/tool-model", label: "local/tool-model" },
+ { id: "second-model", label: "second-model" },
+ ]);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "http://localhost:11434/v1/models",
+ expect.objectContaining({ headers: {} }),
+ );
+ });
+
+ it("loads Anthropic-compatible IDs and display names", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json({
+ data: [
+ { id: "gateway/claude", display_name: "Gateway Claude" },
+ { id: "gateway/claude", display_name: "Duplicate" },
+ ],
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ discoverCompatibleModels({
+ provider: "anthropic-compatible",
+ baseUrl: "https://gateway.example/v1/messages",
+ apiKey: "secret",
+ }),
+ ).resolves.toEqual([
+ { id: "gateway/claude", label: "Gateway Claude" },
+ ]);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://gateway.example/v1/models",
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ "x-api-key": "secret",
+ Authorization: "Bearer secret",
+ "anthropic-version": "2023-06-01",
+ }),
+ }),
+ );
+ });
+
+ it("surfaces endpoint discovery errors", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ Response.json(
+ { error: { message: "Model listing is disabled" } },
+ { status: 404 },
+ ),
+ ),
+ );
+
+ await expect(
+ discoverCompatibleModels({
+ provider: "openai-compatible",
+ baseUrl: "https://gateway.example/v1",
+ apiKey: "",
+ }),
+ ).rejects.toThrow("Model listing is disabled");
+ });
+});
diff --git a/apps/web/src/services/agent/model-discovery.ts b/apps/web/src/services/agent/model-discovery.ts
new file mode 100644
index 00000000..031ca884
--- /dev/null
+++ b/apps/web/src/services/agent/model-discovery.ts
@@ -0,0 +1,82 @@
+import {
+ apiFetch,
+ normalizeCompatibleBaseUrl,
+} from "../api-proxy";
+import type { LlmProvider } from "../../stores/settings-store";
+
+export interface DiscoveredLlmModel {
+ readonly id: string;
+ readonly label: string;
+}
+
+interface DiscoverModelsOptions {
+ readonly provider: LlmProvider;
+ readonly baseUrl: string;
+ readonly apiKey: string;
+ readonly signal?: AbortSignal;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+function errorMessage(payload: unknown): string | null {
+ if (!isRecord(payload)) return null;
+ if (typeof payload.message === "string") return payload.message;
+ if (isRecord(payload.error)) {
+ if (typeof payload.error.message === "string") return payload.error.message;
+ if (typeof payload.error.type === "string") return payload.error.type;
+ }
+ return null;
+}
+
+/** Discover models from the endpoint's standard GET /models route. */
+export async function discoverCompatibleModels({
+ provider,
+ baseUrl,
+ apiKey,
+ signal,
+}: DiscoverModelsOptions): Promise<DiscoveredLlmModel[]> {
+ const normalizedBaseUrl = normalizeCompatibleBaseUrl(baseUrl);
+ const response = await apiFetch(provider, "/models", apiKey, {
+ baseUrl: normalizedBaseUrl,
+ signal,
+ });
+ const payload: unknown = await response.json().catch(() => null);
+
+ if (!response.ok) {
+ throw new Error(
+ errorMessage(payload) ??
+ `Could not load models from the endpoint (${response.status}).`,
+ );
+ }
+
+ const candidates = Array.isArray(payload)
+ ? payload
+ : isRecord(payload) && Array.isArray(payload.data)
+ ? payload.data
+ : isRecord(payload) && Array.isArray(payload.models)
+ ? payload.models
+ : [];
+ const seen = new Set<string>();
+ const models: DiscoveredLlmModel[] = [];
+
+ for (const candidate of candidates) {
+ const id =
+ typeof candidate === "string"
+ ? candidate.trim()
+ : isRecord(candidate) && typeof candidate.id === "string"
+ ? candidate.id.trim()
+ : "";
+ if (!id || seen.has(id)) continue;
+ const label =
+ isRecord(candidate) && typeof candidate.display_name === "string"
+ ? candidate.display_name.trim() || id
+ : isRecord(candidate) && typeof candidate.name === "string"
+ ? candidate.name.trim() || id
+ : id;
+ seen.add(id);
+ models.push({ id, label });
+ }
+
+ return models;
+}
diff --git a/apps/web/src/services/agent/models.test.ts b/apps/web/src/services/agent/models.test.ts
new file mode 100644
index 00000000..eb5b23c4
--- /dev/null
+++ b/apps/web/src/services/agent/models.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import {
+ defaultModelFor,
+ isKnownModel,
+ modelsFor,
+ resolveModel,
+} from "./models";
+import type { LlmProvider } from "../../stores/settings-store";
+
+describe("agent model registry", () => {
+ it("does not preconfigure models for compatible endpoints", () => {
+ expect(modelsFor("openai-compatible")).toEqual([]);
+ expect(modelsFor("anthropic-compatible")).toEqual([]);
+ expect(defaultModelFor("openai-compatible")).toBe("");
+ expect(defaultModelFor("anthropic-compatible")).toBe("");
+ });
+
+ it("preserves any model ID entered by the user", () => {
+ expect(isKnownModel("openai-compatible", "account-deployment")).toBe(false);
+ expect(resolveModel("openai-compatible", " account-deployment ")).toBe(
+ "account-deployment",
+ );
+ });
+
+ it("falls back only when a model ID is blank", () => {
+ expect(resolveModel("anthropic-compatible", " ")).toBe("");
+ });
+
+ it("falls back safely when persisted settings name a removed provider", () => {
+ const removedProvider = "removed-provider" as LlmProvider;
+
+ expect(modelsFor(removedProvider)).toEqual([]);
+ expect(defaultModelFor(removedProvider)).toBe("");
+ });
+
+ it("falls back safely when a persisted model value is missing", () => {
+ expect(resolveModel("openai-compatible", undefined)).toBe("");
+ });
+});
diff --git a/apps/web/src/services/agent/models.ts b/apps/web/src/services/agent/models.ts
index 1eb44650..427afc73 100644
--- a/apps/web/src/services/agent/models.ts
+++ b/apps/web/src/services/agent/models.ts
@@ -5,26 +5,31 @@ export interface LlmModelOption {
readonly label: string;
}
-/** Tool-use-capable models per provider for the agent chat (BYOK). */
+/**
+ * Compatible endpoints own their model catalogs. This registry intentionally
+ * stays empty so the app never invents a provider or model selection.
+ */
export const LLM_MODELS: Record<LlmProvider, LlmModelOption[]> = {
- anthropic: [
- { id: "claude-sonnet-4-20250514", label: "Claude Sonnet 4" },
- { id: "claude-opus-4-20250514", label: "Claude Opus 4" },
- { id: "claude-3-5-sonnet-20241022", label: "Claude 3.5 Sonnet" },
- { id: "claude-3-5-haiku-20241022", label: "Claude 3.5 Haiku" },
- ],
- openai: [
- { id: "gpt-4o", label: "GPT-4o" },
- { id: "gpt-4o-mini", label: "GPT-4o mini" },
- { id: "gpt-4.1", label: "GPT-4.1" },
- { id: "o4-mini", label: "o4-mini" },
- ],
+ "openai-compatible": [],
+ "anthropic-compatible": [],
};
export function defaultModelFor(provider: LlmProvider): string {
- return LLM_MODELS[provider][0].id;
+ return modelsFor(provider)[0]?.id ?? "";
}
export function modelsFor(provider: LlmProvider): LlmModelOption[] {
- return LLM_MODELS[provider];
+ return LLM_MODELS[provider] ?? [];
+}
+
+export function isKnownModel(provider: LlmProvider, model: string): boolean {
+ return modelsFor(provider).some((option) => option.id === model);
+}
+
+/** Accept a provider model id entered by the user, falling back only when blank. */
+export function resolveModel(
+ provider: LlmProvider,
+ model: string | null | undefined,
+): string {
+ return model?.trim() || defaultModelFor(provider);
}
diff --git a/apps/web/src/services/agent/multicam-bridge.ts b/apps/web/src/services/agent/multicam-bridge.ts
new file mode 100644
index 00000000..efbac5a6
--- /dev/null
+++ b/apps/web/src/services/agent/multicam-bridge.ts
@@ -0,0 +1,258 @@
+import type { JobResult, MulticamHostBridge } from "@openreel/agent";
+import {
+ DEFAULT_MULTICAM_SHOT_POLICY,
+ incorporateMulticamReactionCues,
+ planMulticamShots,
+ type MultiCamGroup,
+ type MulticamShotPolicy,
+} from "@openreel/core";
+import { useProjectStore } from "../../stores/project-store";
+import { useEngineStore } from "../../stores/engine-store";
+import { loadMulticamArtifact } from "../multicam-analysis-store";
+import {
+ createMulticamApplyTracksAction,
+ resolveMulticamSources,
+} from "../../components/editor/inspector/multicam-workflow";
+import { extractMulticamSocialClips } from "@openreel/core";
+
+function selectGroup(groupId?: string): MultiCamGroup {
+ const groups = useProjectStore.getState().project.multicamGroups ?? [];
+ const group = groupId
+ ? groups.find((entry) => entry.id === groupId)
+ : groups[0];
+ if (!group) throw new Error(groupId ? `Multicam group not found: ${groupId}` : "No multicam group exists");
+ return structuredClone(group);
+}
+
+async function artifact(groupId?: string) {
+ const project = useProjectStore.getState().project;
+ const group = selectGroup(groupId);
+ const value = await loadMulticamArtifact(project.id, group.id);
+ if (!value) throw new Error(`Reusable activity artifact is unavailable for ${group.name}`);
+ return { project, group, artifact: value };
+}
+
+async function liveEngine() {
+ const engine = await useEngineStore.getState().getMultiCamEngine();
+ engine.loadGroups(useProjectStore.getState().project.multicamGroups ?? []);
+ return engine;
+}
+
+async function applyEngineGroup(
+ groupId: string,
+ existingEngine?: Awaited<ReturnType<typeof liveEngine>>,
+): Promise<Record<string, unknown>> {
+ const project = useProjectStore.getState().project;
+ const engine = existingEngine ?? await liveEngine();
+ const group = engine.getGroup(groupId);
+ if (!group?.outputTrackId) throw new Error("The multicam group has no generated output track");
+ const sources = resolveMulticamSources(project, group);
+ const outputTracks = engine.buildShotPlanTracks(
+ groupId,
+ group.outputTrackId,
+ new Map(sources.map((source) => [source.clip.id, source.clip])),
+ project.settings,
+ );
+ if (!outputTracks.length) throw new Error("The multicam shot plan produced no timeline tracks");
+ engine.setOutputTracks(groupId, outputTracks.map((track) => track.id));
+ const updated = engine.getGroup(groupId)!;
+ const result = await useProjectStore.getState().executeAction(
+ createMulticamApplyTracksAction({
+ project,
+ group: updated,
+ groups: engine.getAllGroups(),
+ outputTracks,
+ }),
+ );
+ if (!result.success) throw new Error(result.error?.message ?? "Could not apply multicam edit");
+ return {
+ groupId,
+ shots: updated.shotPlan?.shots.length ?? 0,
+ cuts: Math.max(0, (updated.switches?.length ?? 1) - 1),
+ outputTrackIds: updated.outputTrackIds ?? [updated.outputTrackId],
+ };
+}
+
+export function createMulticamHostBridge(
+ preview: (timeMs: number) => Promise<JobResult>,
+): MulticamHostBridge {
+ return {
+ async getManifest(groupId) {
+ const group = selectGroup(groupId);
+ if (!group.manifest) throw new Error(`Manifest is unavailable for ${group.name}`);
+ return { groupId: group.id, manifest: group.manifest };
+ },
+
+ async getActivityMap(groupId, range = {}) {
+ const value = await artifact(groupId);
+ const points = value.artifact.activity.points.filter(
+ (point) =>
+ point.endTime * 1_000 > (range.startMs ?? 0) &&
+ point.startTime * 1_000 < (range.endMs ?? value.artifact.durationMs),
+ );
+ const stride = Math.max(1, Math.ceil(points.length / 2_000));
+ return {
+ groupId: value.group.id,
+ activity: {
+ ...value.artifact.activity,
+ points: points.filter((_point, index) => index % stride === 0),
+ },
+ sampled: stride > 1,
+ };
+ },
+
+ async getTranscript(groupId, range = {}) {
+ const value = await artifact(groupId);
+ const startMs = range.startMs ?? 0;
+ const endMs = range.endMs ?? value.artifact.durationMs;
+ return {
+ groupId: value.group.id,
+ transcripts: Object.fromEntries(
+ Object.entries(value.artifact.transcripts ?? {}).map(([id, segments]) => [
+ id,
+ segments.filter((segment) => segment.endMs > startMs && segment.startMs < endMs),
+ ]),
+ ),
+ };
+ },
+
+ async setEditPolicy(groupId, updates) {
+ const value = await artifact(groupId);
+ const engine = await liveEngine();
+ const group = engine.getGroup(value.group.id);
+ if (!group?.manifest) throw new Error("The multicam manifest is unavailable");
+ const policy: MulticamShotPolicy = {
+ ...DEFAULT_MULTICAM_SHOT_POLICY,
+ ...group.editPolicy,
+ ...updates,
+ };
+ const participantIds = new Set(group.manifest.participants.map((entry) => entry.id));
+ const unknownPriority = policy.priorityParticipantIds.find((id) => !participantIds.has(id));
+ if (unknownPriority) throw new Error(`Unknown priority participant: ${unknownPriority}`);
+ group.editPolicy = policy;
+ group.shotPlan = incorporateMulticamReactionCues(
+ planMulticamShots(value.artifact.activity, group.manifest, policy),
+ group.manifest,
+ value.artifact.reactions ?? [],
+ );
+ engine.applyAutomaticEdit(
+ group.id,
+ {
+ duration: group.shotPlan.durationMs / 1_000,
+ segments: group.shotPlan.shots.map((shot) => ({
+ angleId: shot.layout.panels[0]?.cameraId ?? group.manifest!.sync.reference,
+ startTime: shot.startMs / 1_000,
+ endTime: shot.endMs / 1_000,
+ reason: shot.reason,
+ confidence: shot.confidence,
+ })),
+ },
+ group.automaticEdit?.policy ?? {
+ overlapStrategy: "hold",
+ minShotMs: group.manifest.constraints.min_shot_ms,
+ maxShotMs: group.manifest.constraints.max_shot_ms,
+ reactionShotMs: 1_800,
+ cutLeadMs: group.manifest.constraints.cut_lead_ms,
+ backchannelMaxMs: 700,
+ reactionShotAfterMs: group.manifest.constraints.reaction_shot_after_ms,
+ forbidJumpCutSameSubject: group.manifest.constraints.forbid_jump_cut_same_subject,
+ },
+ value.artifact.activity.windowMs,
+ );
+ return { ...(await applyEngineGroup(group.id, engine)), policy };
+ },
+
+ async annotateSegment(input) {
+ const project = useProjectStore.getState().project;
+ const groups = structuredClone(project.multicamGroups ?? []);
+ const group = groups.find((entry) => entry.id === input.groupId);
+ if (!group) throw new Error(`Multicam group not found: ${input.groupId}`);
+ if (input.startMs < 0 || input.endMs <= input.startMs || input.endMs > group.duration * 1_000) {
+ throw new Error(`Annotation range must be inside 0-${Math.round(group.duration * 1_000)} ms`);
+ }
+ group.annotations = [
+ ...(group.annotations ?? []),
+ {
+ id: crypto.randomUUID(),
+ startMs: input.startMs,
+ endMs: input.endMs,
+ note: input.note,
+ createdAt: Date.now(),
+ },
+ ];
+ const result = await useProjectStore.getState().executeAction({
+ type: "multicam/setAll",
+ id: crypto.randomUUID(),
+ timestamp: Date.now(),
+ params: { groups },
+ });
+ if (!result.success) throw new Error(result.error?.message ?? "Could not annotate segment");
+ return { groupId: group.id, annotation: group.annotations.at(-1) };
+ },
+
+ async getEditSummary(groupId) {
+ const value = await artifact(groupId);
+ const group = selectGroup(value.group.id);
+ return {
+ groupId: group.id,
+ name: group.name,
+ durationMs: value.artifact.durationMs,
+ participants: group.manifest?.participants.length ?? 0,
+ cameras: group.manifest?.cameras.length ?? group.angles.length,
+ shots: group.shotPlan?.shots.length ?? 0,
+ cuts: Math.max(0, (group.switches?.length ?? 1) - 1),
+ pendingReview: (group.switches ?? []).filter((entry) => entry.reviewStatus === "pending").length,
+ layouts: group.shotPlan?.shots.reduce<Record<string, number>>((counts, shot) => {
+ counts[shot.layout.template] = (counts[shot.layout.template] ?? 0) + 1;
+ return counts;
+ }, {}) ?? {},
+ annotations: group.annotations ?? [],
+ socialCandidates: extractMulticamSocialClips(value.artifact),
+ };
+ },
+
+ async overrideCut(input) {
+ const engine = await liveEngine();
+ const group = engine.getGroup(input.groupId);
+ if (!group) throw new Error(`Multicam group not found: ${input.groupId}`);
+ let changed = false;
+ if (input.operation === "accept") {
+ changed = engine.acceptSwitch(group.id, input.switchId);
+ } else if (input.operation === "reject") {
+ changed = engine.removeSwitch(group.id, input.switchId);
+ } else if (input.operation === "nudge") {
+ changed = engine.nudgeSwitch(group.id, input.switchId, (input.deltaMs ?? 0) / 1_000);
+ } else if (input.operation === "set-camera") {
+ const camera = group.manifest?.cameras.find((entry) => entry.id === input.cameraId);
+ const switchItem = group.switches?.find((entry) => entry.id === input.switchId);
+ if (camera && switchItem && group.angles.some((entry) => entry.id === camera.id)) {
+ switchItem.angleId = camera.id;
+ const shot = group.shotPlan?.shots.find(
+ (entry) => Math.abs(entry.startMs / 1_000 - switchItem.time) < 0.001,
+ );
+ if (shot?.layout.panels[0]) {
+ shot.layout = {
+ template: camera.type === "wide" ? "wide" : "solo",
+ panels: [{
+ cameraId: camera.id,
+ subject: camera.subject,
+ rect: { x: 0, y: 0, width: 1, height: 1 },
+ }],
+ };
+ }
+ changed = true;
+ }
+ }
+ if (!changed) throw new Error(`Cut override could not be applied: ${input.switchId}`);
+ return applyEngineGroup(group.id, engine);
+ },
+
+ async previewFrame(groupId, timeMs) {
+ const group = selectGroup(groupId);
+ if (timeMs < 0 || timeMs > group.duration * 1_000) {
+ throw new Error(`Preview time must be inside 0-${Math.round(group.duration * 1_000)} ms`);
+ }
+ return preview(timeMs);
+ },
+ };
+}
diff --git a/apps/web/src/services/api-proxy.compatible.test.ts b/apps/web/src/services/api-proxy.compatible.test.ts
new file mode 100644
index 00000000..e39b618a
--- /dev/null
+++ b/apps/web/src/services/api-proxy.compatible.test.ts
@@ -0,0 +1,124 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ apiFetch,
+ normalizeCompatibleBaseUrl,
+ normalizeOpenAICompatibleBaseUrl,
+} from "./api-proxy";
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("OpenAI-compatible API transport", () => {
+ it("normalizes base and complete Chat Completions URLs", () => {
+ expect(normalizeOpenAICompatibleBaseUrl("https://example.test/v1/")).toBe(
+ "https://example.test/v1",
+ );
+ expect(
+ normalizeOpenAICompatibleBaseUrl(
+ "http://localhost:11434/v1/chat/completions",
+ ),
+ ).toBe("http://localhost:11434/v1");
+ expect(
+ normalizeCompatibleBaseUrl("https://gateway.example/v1/messages"),
+ ).toBe("https://gateway.example/v1");
+ });
+
+ it("rejects unsafe or ambiguous endpoint URLs", () => {
+ expect(() => normalizeOpenAICompatibleBaseUrl("file:///tmp/model"))
+ .toThrow(/http/i);
+ expect(() => normalizeOpenAICompatibleBaseUrl("https://[email protected]/v1"))
+ .toThrow(/credentials/i);
+ expect(() => normalizeOpenAICompatibleBaseUrl("https://example.test/v1?key=x"))
+ .toThrow(/query/i);
+ });
+
+ it("calls a compatible endpoint directly with bearer authentication", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await apiFetch("openai-compatible", "/chat/completions", "secret", {
+ method: "POST",
+ baseUrl: "https://provider.example/v1",
+ headers: { "Content-Type": "application/json" },
+ body: "{}",
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://provider.example/v1/chat/completions",
+ expect.objectContaining({
+ method: "POST",
+ headers: {
+ Authorization: "Bearer secret",
+ "Content-Type": "application/json",
+ },
+ }),
+ );
+ });
+
+ it("supports endpoints that do not require a key", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await apiFetch("openai-compatible", "/chat/completions", "", {
+ baseUrl: "http://localhost:1234/v1",
+ });
+
+ const init = fetchMock.mock.calls[0][1] as globalThis.RequestInit;
+ expect(init.headers).not.toHaveProperty("Authorization");
+ });
+
+ it("does not allow caller headers to override compatible endpoint authentication", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await apiFetch("openai-compatible", "/chat/completions", "stored-key", {
+ baseUrl: "https://provider.example/v1",
+ headers: { authorization: "Bearer injected" },
+ });
+
+ const init = fetchMock.mock.calls[0][1] as globalThis.RequestInit;
+ expect(init.headers).toEqual({ Authorization: "Bearer stored-key" });
+ });
+
+ it("discovers models from OpenAI-compatible endpoints", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await apiFetch("openai-compatible", "/models", "stored-key", {
+ baseUrl: "https://provider.example/v1",
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://provider.example/v1/models",
+ expect.objectContaining({
+ headers: { Authorization: "Bearer stored-key" },
+ }),
+ );
+ });
+
+ it("supports Anthropic-compatible messages and model discovery", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await apiFetch("anthropic-compatible", "/messages", "stored-key", {
+ method: "POST",
+ baseUrl: "https://gateway.example/v1",
+ headers: { "Content-Type": "application/json" },
+ body: "{}",
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://gateway.example/v1/messages",
+ expect.objectContaining({
+ headers: {
+ "Content-Type": "application/json",
+ "anthropic-version": "2023-06-01",
+ "anthropic-dangerous-direct-browser-access": "true",
+ "x-api-key": "stored-key",
+ Authorization: "Bearer stored-key",
+ },
+ }),
+ );
+ });
+});
diff --git a/apps/web/src/services/api-proxy.desktop.test.ts b/apps/web/src/services/api-proxy.desktop.test.ts
index 8015315b..a2997b7d 100644
--- a/apps/web/src/services/api-proxy.desktop.test.ts
+++ b/apps/web/src/services/api-proxy.desktop.test.ts
@@ -46,4 +46,38 @@ describe("apiFetch desktop branch", () => {
body: undefined,
});
});
+
+ it("forwards a custom base URL for desktop-compatible endpoints", async () => {
+ await apiFetch("openai-compatible", "/chat/completions", "", {
+ method: "POST",
+ baseUrl: "http://localhost:11434/v1",
+ body: "{}",
+ });
+ expect(cloudFetch).toHaveBeenCalledWith(
+ "openai-compatible",
+ "/chat/completions",
+ {
+ method: "POST",
+ headers: undefined,
+ body: "{}",
+ baseUrl: "http://localhost:11434/v1",
+ },
+ );
+ });
+
+ it("forwards Anthropic-compatible model discovery", async () => {
+ await apiFetch("anthropic-compatible", "/models", "", {
+ baseUrl: "https://gateway.example/v1",
+ });
+ expect(cloudFetch).toHaveBeenCalledWith(
+ "anthropic-compatible",
+ "/models",
+ {
+ method: undefined,
+ headers: undefined,
+ body: undefined,
+ baseUrl: "https://gateway.example/v1",
+ },
+ );
+ });
});
diff --git a/apps/web/src/services/api-proxy.ts b/apps/web/src/services/api-proxy.ts
index 33499937..c3d0d2c2 100644
--- a/apps/web/src/services/api-proxy.ts
+++ b/apps/web/src/services/api-proxy.ts
@@ -2,8 +2,9 @@
* API proxy utility for third-party service calls.
*
* In development: calls third-party APIs directly (for convenience).
- * In production: routes through Cloudflare Pages Functions proxy so
- * API keys never leave the same origin.
+ * In production: built-in services route through Cloudflare Pages Functions.
+ * User-defined compatible endpoints are called directly to avoid
+ * turning the hosted proxy into an arbitrary-destination relay.
*/
const isDev = import.meta.env.DEV;
@@ -31,13 +32,55 @@ const DIRECT_CONFIG = {
},
} as const;
-export type ApiService = keyof typeof DIRECT_CONFIG;
+export type CompatibleApiService =
+ | "openai-compatible"
+ | "anthropic-compatible";
+export type ApiService = keyof typeof DIRECT_CONFIG | CompatibleApiService;
+
+export interface ApiFetchOptions extends globalThis.RequestInit {
+ /** Required only for user-defined compatible requests. */
+ readonly baseUrl?: string;
+}
+
+/**
+ * Accept either a `/v1`-style base URL or a complete `/chat/completions` URL.
+ * Credentials and query/hash fragments are rejected so secrets stay in the
+ * dedicated encrypted key field and URL joining remains deterministic.
+ */
+export function normalizeCompatibleBaseUrl(input: string): string {
+ const value = input.trim();
+ if (!value) throw new Error("Enter a compatible API base URL.");
+
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ throw new Error("Enter a valid API URL, including http:// or https://.");
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new Error("The compatible endpoint must use http:// or https://.");
+ }
+ if (url.username || url.password) {
+ throw new Error("Put credentials in the API key field, not in the endpoint URL.");
+ }
+ if (url.search || url.hash) {
+ throw new Error("The compatible endpoint URL cannot include a query string or fragment.");
+ }
+
+ let pathname = url.pathname.replace(/\/+$/, "");
+ pathname = pathname.replace(/\/(?:chat\/completions|messages|models)$/i, "");
+ url.pathname = pathname;
+ return url.toString().replace(/\/$/, "");
+}
+
+/** Backwards-compatible export for callers that used the original name. */
+export const normalizeOpenAICompatibleBaseUrl = normalizeCompatibleBaseUrl;
/**
* Fetch from a third-party API, automatically routing through the proxy
* in production builds.
*
- * @param service - Target service (elevenlabs, openai, anthropic)
+ * @param service - Target built-in service or a compatible endpoint
* @param path - API path including leading slash, e.g. "/models" or "/text-to-speech/voiceId"
* @param apiKey - Decrypted API key for the service
* @param options - Standard RequestInit (method, body, extra headers, etc.)
@@ -46,8 +89,9 @@ export async function apiFetch(
service: ApiService,
path: string,
apiKey: string,
- options: globalThis.RequestInit = {},
+ options: ApiFetchOptions = {},
): Promise<Response> {
+ const { baseUrl, ...requestOptions } = options;
const extraHeaders = (options.headers ?? {}) as Record<string, string>;
if (typeof window !== "undefined" && window.openreel?.platform === "desktop") {
@@ -55,6 +99,7 @@ export async function apiFetch(
method: options.method,
headers: options.headers as Record<string, string> | undefined,
body: typeof options.body === "string" ? options.body : undefined,
+ baseUrl,
});
return new Response(result.body, {
status: result.status,
@@ -63,11 +108,54 @@ export async function apiFetch(
});
}
+ if (
+ service === "openai-compatible" ||
+ service === "anthropic-compatible"
+ ) {
+ const allowedPaths =
+ service === "openai-compatible"
+ ? ["/chat/completions", "/models"]
+ : ["/messages", "/models"];
+ if (!allowedPaths.includes(path)) {
+ throw new Error(`Unsupported ${service} API path.`);
+ }
+ const normalizedBaseUrl = normalizeCompatibleBaseUrl(baseUrl ?? "");
+ const safeHeaders = Object.fromEntries(
+ Object.entries(extraHeaders).filter(
+ ([name]) =>
+ ![
+ "authorization",
+ "x-api-key",
+ "anthropic-version",
+ "anthropic-dangerous-direct-browser-access",
+ ].includes(name.toLowerCase()),
+ ),
+ );
+ const authHeaders: Record<string, string> = {};
+ if (service === "openai-compatible") {
+ if (apiKey) authHeaders.Authorization = `Bearer ${apiKey}`;
+ } else {
+ authHeaders["anthropic-version"] = "2023-06-01";
+ authHeaders["anthropic-dangerous-direct-browser-access"] = "true";
+ if (apiKey) {
+ authHeaders["x-api-key"] = apiKey;
+ authHeaders.Authorization = `Bearer ${apiKey}`;
+ }
+ }
+ return fetch(`${normalizedBaseUrl}${path}`, {
+ ...requestOptions,
+ headers: {
+ ...safeHeaders,
+ ...authHeaders,
+ },
+ });
+ }
+
if (isDev) {
const config = DIRECT_CONFIG[service];
const url = `${config.baseUrl}${path}`;
return fetch(url, {
- ...options,
+ ...requestOptions,
headers: {
...config.authHeaders(apiKey),
...extraHeaders,
@@ -78,7 +166,7 @@ export async function apiFetch(
// Production: route through same-origin proxy
const url = `/api/proxy/${service}${path}`;
return fetch(url, {
- ...options,
+ ...requestOptions,
headers: {
"x-proxy-api-key": apiKey,
...extraHeaders,
diff --git a/apps/web/src/services/auto-save.test.ts b/apps/web/src/services/auto-save.test.ts
index 2aec9349..20361faa 100644
--- a/apps/web/src/services/auto-save.test.ts
+++ b/apps/web/src/services/auto-save.test.ts
@@ -1,6 +1,9 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Project } from "@openreel/core";
-import { AutoSaveManager } from "./auto-save";
+import {
+ AutoSaveManager,
+ serializeProjectForAutoSave,
+} from "./auto-save";
import { createEmptyProject } from "../stores/project/project-helpers";
const project = (name: string): Project => ({
@@ -28,4 +31,61 @@ describe("AutoSaveManager", () => {
);
manager.stop();
});
+
+ it("strips runtime-only media payloads from serialized snapshots", () => {
+ const source = project("Media project");
+ const snapshot: Project = {
+ ...source,
+ mediaLibrary: {
+ items: [
+ {
+ id: "media-1",
+ name: "clip.mp4",
+ type: "video",
+ fileHandle: {} as FileSystemFileHandle,
+ blob: new Blob(["video"], { type: "video/mp4" }),
+ metadata: {
+ duration: 5,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 5,
+ },
+ thumbnailUrl: "blob:stale-thumbnail",
+ waveformData: new Float32Array([0.1, 0.2]),
+ filmstripThumbnails: [
+ { timestamp: 0, url: "blob:stale-filmstrip" },
+ ],
+ sourceFile: {
+ name: "clip.mp4",
+ size: 5,
+ lastModified: 123,
+ },
+ },
+ ],
+ },
+ };
+
+ const serialized = JSON.parse(serializeProjectForAutoSave(snapshot)) as {
+ mediaLibrary: { items: Array<Record<string, unknown>> };
+ };
+
+ expect(serialized.mediaLibrary.items[0]).toMatchObject({
+ blob: null,
+ fileHandle: null,
+ waveformData: null,
+ thumbnailUrl: null,
+ sourceFile: {
+ name: "clip.mp4",
+ size: 5,
+ lastModified: 123,
+ },
+ });
+ expect(serialized.mediaLibrary.items[0]).not.toHaveProperty(
+ "filmstripThumbnails",
+ );
+ });
});
diff --git a/apps/web/src/services/auto-save.ts b/apps/web/src/services/auto-save.ts
index 9d2ce05f..125531ae 100644
--- a/apps/web/src/services/auto-save.ts
+++ b/apps/web/src/services/auto-save.ts
@@ -36,6 +36,27 @@ const AUTO_SAVE_DB_NAME = "openreel-autosave";
const AUTO_SAVE_DB_VERSION = 1;
const AUTO_SAVE_STORE = "autosaves";
+export function serializeProjectForAutoSave(project: Project): string {
+ const mediaItems = project.mediaLibrary.items.map((item) => ({
+ ...item,
+ blob: null,
+ fileHandle: null,
+ waveformData: null,
+ thumbnailUrl: item.thumbnailUrl?.startsWith("blob:")
+ ? null
+ : item.thumbnailUrl,
+ filmstripThumbnails: undefined,
+ }));
+
+ return JSON.stringify({
+ ...project,
+ mediaLibrary: {
+ ...project.mediaLibrary,
+ items: mediaItems,
+ },
+ });
+}
+
type AutoSaveEventType = "saved" | "restored" | "error" | "recoveryAvailable";
type AutoSaveEventCallback = (data?: unknown) => void;
@@ -182,7 +203,7 @@ export class AutoSaveManager {
projectName: project.name,
timestamp: Date.now(),
slot: this.currentSlot,
- data: JSON.stringify(project),
+ data: serializeProjectForAutoSave(project),
};
await this.saveRecord(record);
diff --git a/apps/web/src/services/gpu-clip-submit.test.ts b/apps/web/src/services/gpu-clip-submit.test.ts
deleted file mode 100644
index d690b39d..00000000
--- a/apps/web/src/services/gpu-clip-submit.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-
-const h = vi.hoisted(() => ({
- submitClipJob: vi.fn(),
- isDesktopGpuAvailable: vi.fn(() => false),
- loadMediaBlob: vi.fn(),
- addPlaceholderMedia: vi.fn(),
- addJob: vi.fn(),
- getClip: vi.fn(),
- getMediaItem: vi.fn(),
- getSelectedClipIds: vi.fn(),
-}));
-
-vi.mock("../stores/project-store", () => ({
- useProjectStore: {
- getState: () => ({
- project: { id: "p1" },
- getClip: h.getClip,
- getMediaItem: h.getMediaItem,
- addPlaceholderMedia: h.addPlaceholderMedia,
- }),
- },
-}));
-vi.mock("../stores/ui-store", () => ({
- useUIStore: { getState: () => ({ getSelectedClipIds: h.getSelectedClipIds }) },
-}));
-vi.mock("../stores/gpu-job-store", () => ({
- useGpuJobStore: { getState: () => ({ addJob: h.addJob }) },
-}));
-vi.mock("./gpu-jobs", () => ({
- submitClipJob: h.submitClipJob,
- isDesktopGpuAvailable: h.isDesktopGpuAvailable,
-}));
-vi.mock("./media-storage", () => ({ loadMediaBlob: h.loadMediaBlob }));
-vi.mock("@openreel/core", async (importActual) => {
- const actual = await importActual<typeof import("@openreel/core")>();
- return {
- ...actual,
- materializeToTemp: vi.fn(),
- nativeMediaAvailable: () => false,
- getBridge: () => null,
- };
-});
-
-import { submitSelectedClipJob } from "./gpu-clip-submit";
-
-beforeEach(() => {
- vi.clearAllMocks();
- h.isDesktopGpuAvailable.mockReturnValue(false);
- h.getSelectedClipIds.mockReturnValue(["clip1"]);
- h.getClip.mockReturnValue({ mediaId: "m1" });
- h.getMediaItem.mockReturnValue({
- type: "image",
- name: "photo.png",
- blob: new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }),
- });
- h.submitClipJob.mockResolvedValue({ jobID: "job1" });
-});
-
-describe("submitSelectedClipJob", () => {
- it("merges extra params with context and registers the job (web blob path)", async () => {
- const res = await submitSelectedClipJob({
- kind: "object_removal",
- params: { mode: "erase", maskMode: "bbox", bbox: [0, 0, 1, 1] },
- suggestedName: "Object erase result",
- });
-
- expect(res.jobID).toBe("job1");
- expect(h.submitClipJob).toHaveBeenCalledTimes(1);
- const call = h.submitClipJob.mock.calls[0][0];
- expect(call.kind).toBe("object_removal");
- expect(call.params).toMatchObject({
- context: { projectID: "p1", quality: "balanced" },
- mode: "erase",
- maskMode: "bbox",
- bbox: [0, 0, 1, 1],
- });
- expect(call.blob).toBeInstanceOf(Blob);
- expect(call.srcPath).toBeUndefined();
- expect(call.filename).toBe("photo.png");
- // object_removal is a "replace" kind → no new library tile; the job targets
- // the clip's own source media so the result replaces it in place.
- expect(h.addPlaceholderMedia).not.toHaveBeenCalled();
- expect(res.mediaId).toBe("m1");
- expect(h.addJob).toHaveBeenCalledWith(
- expect.objectContaining({ jobID: "job1", kind: "object_removal", projectId: "p1", mediaId: "m1" }),
- );
- });
-
- it("adds a new library tile for a new-asset kind (audio separation)", async () => {
- await submitSelectedClipJob({ kind: "audio_separation" });
- expect(h.addPlaceholderMedia).toHaveBeenCalledTimes(1);
- const job = h.addJob.mock.calls[0][0];
- expect(job.mediaId).toMatch(/^gpu-audio_separation-/);
- });
-
- it("throws when no single clip is selected", async () => {
- h.getSelectedClipIds.mockReturnValue([]);
- await expect(submitSelectedClipJob({ kind: "upscale" })).rejects.toThrow("Select a clip first");
- });
-
- it("falls back to loadMediaBlob when the media item has no blob", async () => {
- h.getMediaItem.mockReturnValue({ type: "image", name: "x.png", blob: null });
- h.loadMediaBlob.mockResolvedValue(new Blob([new Uint8Array([9])], { type: "image/png" }));
- await submitSelectedClipJob({ kind: "upscale" });
- expect(h.loadMediaBlob).toHaveBeenCalledWith("m1");
- expect(h.submitClipJob).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/apps/web/src/services/gpu-clip-submit.ts b/apps/web/src/services/gpu-clip-submit.ts
deleted file mode 100644
index f6d607ed..00000000
--- a/apps/web/src/services/gpu-clip-submit.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { MediaItem } from "@openreel/core";
-import { materializeToTemp, nativeMediaAvailable, getBridge } from "@openreel/core";
-import { useProjectStore } from "../stores/project-store";
-import { useUIStore } from "../stores/ui-store";
-import { useGpuJobStore } from "../stores/gpu-job-store";
-import { submitClipJob, isDesktopGpuAvailable } from "./gpu-jobs";
-import { loadMediaBlob } from "./media-storage";
-import { outputForKind, applyModeForKind } from "../components/editor/ai-panel/ai-kinds.config";
-
-const EMPTY_METADATA = {
- duration: 0,
- width: 0,
- height: 0,
- frameRate: 0,
- codec: "",
- sampleRate: 0,
- channels: 0,
- fileSize: 0,
-} as const;
-
-export function buildPlaceholder(mediaId: string, name: string, type: MediaItem["type"]): MediaItem {
- return {
- id: mediaId,
- name,
- type,
- fileHandle: null,
- blob: null,
- metadata: { ...EMPTY_METADATA },
- thumbnailUrl: null,
- waveformData: null,
- isPlaceholder: true,
- isPending: true,
- };
-}
-
-export interface SubmitSelectedClipJobArgs {
- kind: string;
- params?: Record<string, unknown>;
- suggestedName?: string;
- requiresClip?: boolean;
-}
-
-export async function submitSelectedClipJob(
- args: SubmitSelectedClipJobArgs,
-): Promise<{ jobID: string; mediaId: string }> {
- const requiresClip = args.requiresClip ?? true;
- const project = useProjectStore.getState().project;
- if (!project) throw new Error("No project open");
-
- let srcPath: string | undefined;
- let blob: Blob | undefined;
- let filename: string | undefined;
- let contentType: string | undefined;
- let placeholderType: MediaItem["type"] = "video";
- let sourceClipId: string | undefined;
- let sourceMediaId: string | undefined;
- const newMediaId = `gpu-${args.kind}-${Date.now()}`;
-
- if (requiresClip) {
- const selectedClipIds = useUIStore.getState().getSelectedClipIds();
- if (selectedClipIds.length !== 1) throw new Error("Select a clip first");
- sourceClipId = selectedClipIds[0];
- const clip = useProjectStore.getState().getClip(selectedClipIds[0]);
- sourceMediaId = clip?.mediaId;
- if (!sourceMediaId) throw new Error("Select a clip first");
-
- const item = useProjectStore.getState().getMediaItem(sourceMediaId);
- if (item?.type) placeholderType = item.type;
-
- let loaded = item?.blob ?? null;
- if (!loaded) loaded = await loadMediaBlob(sourceMediaId);
- if (!loaded) throw new Error("Could not load clip media");
-
- filename = item?.name ?? "input";
- contentType = loaded.type || undefined;
-
- if (isDesktopGpuAvailable()) {
- if (!nativeMediaAvailable()) throw new Error("Native media bridge unavailable");
- const bridge = getBridge();
- if (!bridge) throw new Error("Native bridge unavailable");
- srcPath = await materializeToTemp(bridge, new File([loaded], filename, { type: contentType }));
- } else {
- blob = loaded;
- }
- }
-
- const suggestedName = args.suggestedName ?? `${args.kind} result`;
- const params: Record<string, unknown> = {
- context: { projectID: project.id, quality: "balanced" },
- ...(args.params ?? {}),
- };
-
- const { jobID } = await submitClipJob({ kind: args.kind, params, srcPath, blob, filename, contentType });
-
- const isMedia = outputForKind(args.kind) === "media";
- const replaceInPlace = isMedia && applyModeForKind(args.kind) === "replace" && !!sourceMediaId;
- const targetMediaId = replaceInPlace ? sourceMediaId! : newMediaId;
-
- // Only create a new library tile for genuinely-new-asset kinds (generated
- // music, audio stems, thumbnails). "replace" kinds overwrite the clip's own
- // source media in place — no new tile.
- if (isMedia && !replaceInPlace) {
- useProjectStore.getState().addPlaceholderMedia(buildPlaceholder(newMediaId, suggestedName, placeholderType));
- }
- useGpuJobStore.getState().addJob({
- jobID,
- mediaId: targetMediaId,
- projectId: project.id,
- kind: args.kind,
- suggestedName,
- sourceClipId,
- });
- return { jobID, mediaId: targetMediaId };
-}
diff --git a/apps/web/src/services/gpu-data-import.ts b/apps/web/src/services/gpu-data-import.ts
deleted file mode 100644
index 8871d30b..00000000
--- a/apps/web/src/services/gpu-data-import.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import type { Subtitle, Clip } from "@openreel/core";
-import { useProjectStore } from "../stores/project-store";
-import { DEFAULT_SUBTITLE_STYLE } from "../stores/project/subtitle-helpers";
-import { toast } from "../stores/notification-store";
-import { applyHighlightRanges } from "./highlight-apply";
-import { getMotionTrackingBridge } from "../bridges/motion-tracking-bridge";
-import type { PendingGpuJob } from "../stores/gpu-job-store";
-import type { AiKindOutput } from "../components/editor/ai-panel/ai-kinds.config";
-
-export interface RawManifest {
- subtitles?: unknown;
- trackingPaths?: unknown;
- highlights?: unknown;
- metadata?: Record<string, unknown>;
-}
-
-interface ClipWindow {
- clipStart: number;
- inPoint: number;
- outPoint: number;
-}
-
-function clipWindow(sourceClipId?: string): ClipWindow {
- const clip: Clip | undefined = sourceClipId
- ? useProjectStore.getState().getClip(sourceClipId)
- : undefined;
- return {
- clipStart: clip?.startTime ?? 0,
- inPoint: clip?.inPoint ?? 0,
- outPoint: clip?.outPoint ?? Number.POSITIVE_INFINITY,
- };
-}
-
-function toTimeline(mediaTime: number, w: ClipWindow): number | null {
- if (mediaTime < w.inPoint - 0.001 || mediaTime > w.outPoint + 0.001) return null;
- const clamped = Math.max(w.inPoint, Math.min(w.outPoint, mediaTime));
- return w.clipStart + (clamped - w.inPoint);
-}
-
-async function applySubtitles(raw: RawManifest, job: PendingGpuJob): Promise<number> {
- const subs = Array.isArray(raw.subtitles) ? raw.subtitles : [];
- const store = useProjectStore.getState();
- const w = clipWindow(job.sourceClipId);
- let count = 0;
- for (let i = 0; i < subs.length; i++) {
- const s = subs[i] as Record<string, unknown>;
- const text = typeof s.text === "string" ? s.text.trim() : "";
- const startTime = typeof s.startTime === "number" ? s.startTime : null;
- const endTime = typeof s.endTime === "number" ? s.endTime : null;
- if (!text || startTime === null || endTime === null) continue;
- const tlStart = toTimeline(startTime, w);
- if (tlStart === null) continue;
- const tlEnd = toTimeline(Math.max(endTime, startTime + 0.3), w) ?? tlStart + 0.3;
- const subtitle: Subtitle = {
- id: typeof s.id === "string" ? s.id : `gpu-sub-${Date.now()}-${i}`,
- text,
- startTime: tlStart,
- endTime: Math.max(tlStart + 0.3, tlEnd),
- style: { ...DEFAULT_SUBTITLE_STYLE },
- };
- await store.addSubtitle(subtitle);
- count++;
- }
- return count;
-}
-
-function applyScenes(raw: RawManifest, job: PendingGpuJob): number {
- const scenes = Array.isArray(raw.metadata?.scenes)
- ? (raw.metadata?.scenes as unknown[])
- : [];
- const store = useProjectStore.getState();
- const w = clipWindow(job.sourceClipId);
- let count = 0;
- for (const entry of scenes) {
- const sc = entry as Record<string, unknown>;
- const mediaTime = typeof sc.startTime === "number" ? sc.startTime : null;
- if (mediaTime === null) continue;
- const tl = toTimeline(mediaTime, w);
- if (tl === null || tl <= w.clipStart + 0.05) continue;
- count += 1;
- void store.addMarker(tl, `Scene ${count + 1}`, "#22d3ee");
- }
- return count;
-}
-
-async function applyHighlights(raw: RawManifest, job: PendingGpuJob): Promise<number> {
- if (!job.sourceClipId) return 0;
- const hs = Array.isArray(raw.highlights) ? raw.highlights : [];
- const ranges = hs
- .map((entry) => {
- const h = entry as Record<string, unknown>;
- return { start: Number(h.start), end: Number(h.end) };
- })
- .filter((r) => Number.isFinite(r.start) && Number.isFinite(r.end) && r.end > r.start);
- if (ranges.length === 0) return 0;
- return applyHighlightRanges(job.sourceClipId, ranges);
-}
-
-function applyTracking(raw: RawManifest, job: PendingGpuJob): number {
- if (!job.sourceClipId) return 0;
- const paths = Array.isArray(raw.trackingPaths) ? raw.trackingPaths : [];
- const path = paths[0] as Record<string, unknown> | undefined;
- const kfs = Array.isArray(path?.keyframes) ? (path?.keyframes as unknown[]) : [];
- const keyframes = kfs
- .map((entry) => {
- const k = entry as Record<string, unknown>;
- const bb = k.boundingBox as Record<string, number> | undefined;
- if (!bb) return null;
- return {
- frame: Number(k.frameIndex ?? 0),
- position: { x: bb.x + bb.width / 2, y: bb.y + bb.height / 2 },
- };
- })
- .filter((k): k is { frame: number; position: { x: number; y: number } } => k !== null);
- if (keyframes.length === 0) return 0;
- const firstBb = (kfs[0] as Record<string, unknown>).boundingBox as Record<string, number> | undefined;
- const region = firstBb
- ? { x: firstBb.x, y: firstBb.y, width: firstBb.width, height: firstBb.height }
- : { x: 0, y: 0, width: 1, height: 1 };
- const frameRate = Number(path?.frameRate ?? 30);
- getMotionTrackingBridge().ingestTrackingData(job.sourceClipId, keyframes, region, frameRate);
- return keyframes.length;
-}
-
-export async function applyGpuDataResult(
- output: AiKindOutput,
- raw: RawManifest,
- job: PendingGpuJob,
-): Promise<void> {
- switch (output) {
- case "subtitles": {
- const n = await applySubtitles(raw, job);
- if (n > 0) toast.success("Captions added", `${n} caption${n === 1 ? "" : "s"} added to the timeline.`);
- else toast.warning("No captions", "The transcription returned no captions.");
- return;
- }
- case "scenes": {
- const n = applyScenes(raw, job);
- if (n > 0) toast.success("Scenes detected", `Added ${n} scene marker${n === 1 ? "" : "s"}.`);
- else toast.info("No scene changes", "No scene cuts were detected.");
- return;
- }
- case "highlights": {
- const n = await applyHighlights(raw, job);
- if (n > 0) toast.success("Highlights applied", `Trimmed the clip to ${n} highlight${n === 1 ? "" : "s"}.`);
- else toast.info("No highlights", "No highlights were found to apply.");
- return;
- }
- case "tracking": {
- const n = applyTracking(raw, job);
- if (n > 0) toast.success("Tracking ready", "Attach an element to it in the Motion Tracking panel.");
- else toast.warning("Tracking failed", "No track was produced for the selected region.");
- return;
- }
- case "media":
- return;
- }
-}
diff --git a/apps/web/src/services/gpu-jobs.test.ts b/apps/web/src/services/gpu-jobs.test.ts
deleted file mode 100644
index 4e72fcac..00000000
--- a/apps/web/src/services/gpu-jobs.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { isTransientGpuError, gpuBackoffMs, TRANSIENT_GPU_CODES } from "./gpu-jobs";
-
-describe("gpu-jobs retry policy", () => {
- it("classifies 5xx/408/429 + network errors as transient", () => {
- expect(isTransientGpuError({ status: 503 })).toBe(true);
- expect(isTransientGpuError({ status: 500 })).toBe(true);
- expect(isTransientGpuError({ status: 408 })).toBe(true);
- expect(isTransientGpuError({ status: 429 })).toBe(true);
- expect(isTransientGpuError({ status: 404 })).toBe(false);
- expect(isTransientGpuError({})).toBe(true);
- expect(TRANSIENT_GPU_CODES.has(429)).toBe(true);
- });
- it("exponential backoff capped at 15s", () => {
- expect(gpuBackoffMs(0, 2000)).toBe(2000);
- expect(gpuBackoffMs(1, 2000)).toBe(4000);
- expect(gpuBackoffMs(2, 2000)).toBe(8000);
- expect(gpuBackoffMs(3, 2000)).toBe(15000);
- expect(gpuBackoffMs(10, 2000)).toBe(15000);
- });
-});
diff --git a/apps/web/src/services/gpu-jobs.ts b/apps/web/src/services/gpu-jobs.ts
deleted file mode 100644
index a2a6312b..00000000
--- a/apps/web/src/services/gpu-jobs.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { normalizeResultManifest, primaryArtifact, MEDIA_OPTIONAL_KINDS } from "@openreel/core";
-import { getWebGpuClient } from "./gpu-web-client";
-
-export const TRANSIENT_GPU_CODES: ReadonlySet<number> = new Set([
- 408, 429, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511,
-]);
-const POLL_BASE_MS = 2000;
-const BACKOFF_CAP_MS = 15000;
-
-export function isTransientGpuError(err: { status?: number }): boolean {
- if (typeof err.status !== "number") return true;
- return TRANSIENT_GPU_CODES.has(err.status);
-}
-
-export function gpuBackoffMs(attempt: number, baseMs: number = POLL_BASE_MS): number {
- const factor = 1 << Math.max(0, Math.min(attempt, 4));
- return Math.min(baseMs * factor, BACKOFF_CAP_MS);
-}
-
-export function isDesktopGpuAvailable(): boolean {
- return typeof window !== "undefined" && window.openreel?.platform === "desktop" && !!window.openreel.gpu;
-}
-
-export function isWebGpuAvailable(): boolean {
- return (
- typeof window !== "undefined" &&
- typeof fetch === "function" &&
- !isDesktopGpuAvailable()
- );
-}
-
-export function isGpuAvailable(): boolean {
- return isDesktopGpuAvailable() || isWebGpuAvailable();
-}
-
-export interface SubmitClipJobArgs {
- kind: string;
- params: Record<string, unknown>;
- srcPath?: string;
- filename?: string;
- contentType?: string;
- blob?: Blob;
-}
-
-export async function submitClipJob(args: SubmitClipJobArgs): Promise<{ jobID: string }> {
- if (isDesktopGpuAvailable()) {
- return submitClipJobDesktop(args);
- }
- if (isWebGpuAvailable()) {
- return submitClipJobWeb(args);
- }
- throw new Error("GPU jobs are not available in this environment");
-}
-
-async function submitClipJobDesktop(args: SubmitClipJobArgs): Promise<{ jobID: string }> {
- const gpu = window.openreel!.gpu;
- let mediaKey: string | undefined;
- let mediaFilename: string | undefined;
- if (args.srcPath && args.filename) {
- const uploaded = await gpu.uploadMedia({
- srcPath: args.srcPath,
- filename: args.filename,
- contentType: args.contentType,
- });
- mediaKey = uploaded.mediaKey;
- mediaFilename = args.filename;
- } else if (!MEDIA_OPTIONAL_KINDS.has(args.kind)) {
- throw new Error(`kind ${args.kind} requires media`);
- }
- const created = await gpu.submitJob({ kind: args.kind, params: args.params, mediaKey, mediaFilename });
- return { jobID: created.jobID };
-}
-
-async function submitClipJobWeb(args: SubmitClipJobArgs): Promise<{ jobID: string }> {
- const client = getWebGpuClient();
- let mediaKey: string | undefined;
- let mediaFilename: string | undefined;
- if (args.blob && args.filename) {
- const uploaded = await client.uploadMedia({
- blob: args.blob,
- filename: args.filename,
- contentType: args.contentType,
- });
- mediaKey = uploaded.mediaKey;
- mediaFilename = args.filename;
- } else if (!MEDIA_OPTIONAL_KINDS.has(args.kind)) {
- throw new Error(`kind ${args.kind} requires media`);
- }
- const created = await client.submitJob({ kind: args.kind, params: args.params, mediaKey, mediaFilename });
- return { jobID: created.jobID };
-}
-
-export { normalizeResultManifest, primaryArtifact };
diff --git a/apps/web/src/services/gpu-result-import.test.ts b/apps/web/src/services/gpu-result-import.test.ts
deleted file mode 100644
index 78147173..00000000
--- a/apps/web/src/services/gpu-result-import.test.ts
+++ /dev/null
@@ -1,218 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import { importGpuResult, importGpuStems } from "./gpu-result-import";
-import { useProjectStore } from "../stores/project-store";
-import { saveMediaBlob } from "./media-storage";
-import type { PendingGpuJob } from "../stores/gpu-job-store";
-import type { MediaItem } from "@openreel/core";
-
-vi.mock("./media-storage", () => ({
- saveMediaBlob: vi.fn(async () => undefined),
-}));
-
-vi.mock("../stores/engine-store", () => ({
- useEngineStore: { getState: () => ({ videoEngine: null }) },
-}));
-
-const replaceMediaAsset = vi.fn<
- [mediaId: string, file: File, sourceFolder?: string],
- Promise<{ success: boolean; actionId?: string; error?: { message: string } }>
->(async () => ({ success: true, actionId: "act-1" }));
-
-const addPlaceholderMedia = vi.fn();
-
-const getMediaItem = vi.fn<[mediaId: string], MediaItem | undefined>(
- (mediaId) =>
- ({
- id: mediaId,
- type: "video",
- isPlaceholder: true,
- metadata: { duration: 5 },
- }) as unknown as MediaItem,
-);
-
-vi.spyOn(useProjectStore, "getState").mockReturnValue({
- replaceMediaAsset,
- getMediaItem,
- addPlaceholderMedia,
- project: { id: "project-1" },
-} as unknown as ReturnType<typeof useProjectStore.getState>);
-
-function makeJob(overrides: Partial<PendingGpuJob> = {}): PendingGpuJob {
- return {
- jobID: "job-1",
- mediaId: "media-1",
- projectId: "project-1",
- kind: "upscale",
- suggestedName: "Upscaled.png",
- createdAt: Date.now(),
- retries: 0,
- failed: false,
- ...overrides,
- };
-}
-
-describe("importGpuResult", () => {
- beforeEach(() => {
- replaceMediaAsset.mockClear();
- getMediaItem.mockClear();
- addPlaceholderMedia.mockClear();
- vi.mocked(saveMediaBlob).mockClear();
- replaceMediaAsset.mockResolvedValue({ success: true, actionId: "act-1" });
- getMediaItem.mockImplementation(
- (mediaId) =>
- ({ id: mediaId, type: "video", isPlaceholder: true, metadata: { duration: 5 } }) as unknown as MediaItem,
- );
- });
-
- it("routes an image artifact through replaceMediaAsset with the mime type preserved", async () => {
- const job = makeJob({ suggestedName: "Result.png" });
- await importGpuResult({
- job,
- bytes: new Uint8Array([1, 2, 3]).buffer,
- mime: "image/png",
- relativePath: "out.png",
- });
-
- expect(replaceMediaAsset).toHaveBeenCalledTimes(1);
- const [mediaId, file] = replaceMediaAsset.mock.calls[0];
- expect(mediaId).toBe("media-1");
- expect(file).toBeInstanceOf(File);
- expect(file.type).toBe("image/png");
- expect(file.name).toBe("Result.png");
- });
-
- it("routes a video artifact through replaceMediaAsset with the video mime preserved", async () => {
- const job = makeJob({ suggestedName: "Result.mp4" });
- await importGpuResult({
- job,
- bytes: new Uint8Array([4, 5, 6]).buffer,
- mime: "video/mp4",
- relativePath: "out.mp4",
- });
-
- expect(replaceMediaAsset).toHaveBeenCalledTimes(1);
- const [mediaId, file] = replaceMediaAsset.mock.calls[0];
- expect(mediaId).toBe("media-1");
- expect(file).toBeInstanceOf(File);
- expect(file.type).toBe("video/mp4");
- expect(file.name).toBe("Result.mp4");
- });
-
- it("persists the resolved blob to IndexedDB after a successful replace", async () => {
- const job = makeJob({ suggestedName: "Result.mp4" });
- await importGpuResult({
- job,
- bytes: new Uint8Array([4, 5, 6]).buffer,
- mime: "video/mp4",
- relativePath: "out.mp4",
- });
-
- expect(saveMediaBlob).toHaveBeenCalledTimes(1);
- const [projectId, mediaId, blob] = vi.mocked(saveMediaBlob).mock.calls[0];
- expect(projectId).toBe("project-1");
- expect(mediaId).toBe("media-1");
- expect(blob).toBeInstanceOf(File);
- });
-
- it("falls back to the relativePath basename when suggestedName is empty", async () => {
- const job = makeJob({ suggestedName: "" });
- await importGpuResult({
- job,
- bytes: new Uint8Array([7]).buffer,
- mime: "image/png",
- relativePath: "nested/dir/frame.png",
- });
-
- const [, file] = replaceMediaAsset.mock.calls[0];
- expect(file.name).toBe("frame.png");
- });
-
- it("imports as a new asset when the result type would break the target clip", async () => {
- getMediaItem.mockImplementation(
- (id) =>
- ({ id, type: "video", isPlaceholder: false, metadata: { duration: 5 } }) as unknown as MediaItem,
- );
- const job = makeJob({ mediaId: "source-video", kind: "voice_enhance", suggestedName: "Enhanced" });
- await importGpuResult({
- job,
- bytes: new Uint8Array([1]).buffer,
- mime: "audio/wav",
- relativePath: "voice.wav",
- });
- expect(addPlaceholderMedia).toHaveBeenCalledTimes(1);
- const [mediaId] = replaceMediaAsset.mock.calls[0];
- expect(mediaId).not.toBe("source-video");
- expect(mediaId).toMatch(/^gpu-result-voice_enhance-/);
- });
-
- it("throws when replaceMediaAsset fails so the poller can flag the placeholder", async () => {
- replaceMediaAsset.mockResolvedValueOnce({
- success: false,
- error: { message: "decode failed" },
- });
- const job = makeJob({ suggestedName: "Result.mp4" });
-
- await expect(
- importGpuResult({
- job,
- bytes: new Uint8Array([4, 5, 6]).buffer,
- mime: "video/mp4",
- relativePath: "out.mp4",
- }),
- ).rejects.toThrow("decode failed");
-
- expect(saveMediaBlob).not.toHaveBeenCalled();
- });
-});
-
-describe("importGpuStems", () => {
- const demucsStems = [
- { bytes: new Uint8Array([1]).buffer, mime: "audio/wav", relativePath: "stems/bass.wav" },
- { bytes: new Uint8Array([2]).buffer, mime: "audio/wav", relativePath: "stems/drums.wav" },
- { bytes: new Uint8Array([3]).buffer, mime: "audio/wav", relativePath: "stems/other.wav" },
- { bytes: new Uint8Array([4]).buffer, mime: "audio/wav", relativePath: "stems/vocals.wav" },
- ];
-
- beforeEach(() => {
- replaceMediaAsset.mockClear();
- getMediaItem.mockClear();
- addPlaceholderMedia.mockClear();
- vi.mocked(saveMediaBlob).mockClear();
- replaceMediaAsset.mockResolvedValue({ success: true, actionId: "act-1" });
- getMediaItem.mockImplementation(
- (mediaId) =>
- ({ id: mediaId, type: "audio", isPlaceholder: true, metadata: { duration: 5 } }) as unknown as MediaItem,
- );
- });
-
- it("imports every stem as its own labeled audio item (not just the silent bass)", async () => {
- const job = makeJob({ kind: "audio_separation", suggestedName: "Clip result" });
- await importGpuStems({ job, stems: demucsStems });
-
- expect(replaceMediaAsset).toHaveBeenCalledTimes(4);
- const names = replaceMediaAsset.mock.calls.map(([, file]) => file.name);
- expect(names).toEqual([
- "Clip — Bass.wav",
- "Clip — Drums.wav",
- "Clip — Other.wav",
- "Clip — Vocals.wav",
- ]);
- });
-
- it("reuses the job placeholder for the first stem and fresh ids for the rest", async () => {
- const job = makeJob({ mediaId: "stem-media", kind: "audio_separation", suggestedName: "Clip" });
- await importGpuStems({ job, stems: demucsStems });
-
- const ids = replaceMediaAsset.mock.calls.map(([mediaId]) => mediaId);
- expect(ids[0]).toBe("stem-media");
- expect(ids.slice(1)).toEqual(["stem-media-drums", "stem-media-other", "stem-media-vocals"]);
- expect(addPlaceholderMedia).toHaveBeenCalledTimes(3);
- expect(saveMediaBlob).toHaveBeenCalledTimes(4);
- });
-
- it("throws if a stem fails to import", async () => {
- replaceMediaAsset.mockResolvedValueOnce({ success: false, error: { message: "bad wav" } });
- const job = makeJob({ kind: "audio_separation" });
- await expect(importGpuStems({ job, stems: demucsStems })).rejects.toThrow("bad wav");
- });
-});
diff --git a/apps/web/src/services/gpu-result-import.ts b/apps/web/src/services/gpu-result-import.ts
deleted file mode 100644
index be9feedd..00000000
--- a/apps/web/src/services/gpu-result-import.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import type { MediaItem } from "@openreel/core";
-import { useProjectStore } from "../stores/project-store";
-import { useEngineStore } from "../stores/engine-store";
-import { saveMediaBlob } from "./media-storage";
-import { buildPlaceholder } from "./gpu-clip-submit";
-import type { PendingGpuJob } from "../stores/gpu-job-store";
-
-function mediaKindFromMime(mime: string): MediaItem["type"] | null {
- if (mime.startsWith("video/")) return "video";
- if (mime.startsWith("image/")) return "image";
- if (mime.startsWith("audio/")) return "audio";
- return null;
-}
-
-const STEM_LABELS: Record<string, string> = {
- vocals: "Vocals",
- drums: "Drums",
- bass: "Bass",
- other: "Other",
- no_vocals: "Instrumental",
-};
-
-function stemLabelFromPath(relativePath: string): string {
- const base = relativePath.split("/").pop()?.replace(/\.[^.]+$/, "") ?? "stem";
- return STEM_LABELS[base] ?? base.charAt(0).toUpperCase() + base.slice(1);
-}
-
-export async function importGpuResult(args: {
- job: PendingGpuJob;
- bytes: ArrayBuffer;
- mime: string;
- relativePath: string;
-}): Promise<void> {
- const name =
- args.job.suggestedName || args.relativePath.split("/").pop() || "AI Result";
- const file = new File([args.bytes], name, { type: args.mime });
-
- const store = useProjectStore.getState();
- const target = store.getMediaItem(args.job.mediaId);
-
- // Guard: a "replace" kind targets the clip's own source media. If the result
- // is a different media type than that clip (e.g. a stale worker returned bare
- // audio for a video clip), replacing in place would break the clip — import
- // the result as a new library item instead.
- const resultKind = mediaKindFromMime(args.mime);
- const mismatch =
- target != null &&
- !target.isPlaceholder &&
- resultKind != null &&
- target.type !== resultKind;
-
- let targetId = args.job.mediaId;
- if (mismatch) {
- targetId = `gpu-result-${args.job.kind}-${Date.now()}`;
- store.addPlaceholderMedia(buildPlaceholder(targetId, name, resultKind ?? "video"));
- }
-
- const result = await store.replaceMediaAsset(targetId, file);
- if (!result.success) {
- throw new Error(result.error?.message ?? "Failed to import GPU result");
- }
-
- // The blob was swapped under a stable media id, so decode caches keyed by that
- // id are stale — invalidate them so the timeline re-decodes the new media.
- if (!mismatch) {
- const videoEngine = useEngineStore.getState().videoEngine;
- videoEngine?.invalidateMedia(targetId);
- videoEngine?.clearCache();
- }
-
- const item = store.getMediaItem(targetId);
- if (item) {
- const projectId = store.project?.id;
- if (projectId) {
- await saveMediaBlob(projectId, targetId, file, item.metadata);
- }
- }
-}
-
-/**
- * Import multiple result artifacts (e.g. demucs stems) as separate, labeled
- * audio library items. The first artifact reuses the job's placeholder tile;
- * the rest get fresh ids. Without this, audio_separation imported only the
- * primaryArtifact (alphabetically-first = bass), which is often silent.
- */
-export async function importGpuStems(args: {
- job: PendingGpuJob;
- stems: Array<{ bytes: ArrayBuffer; mime: string; relativePath: string }>;
-}): Promise<void> {
- if (args.stems.length === 0) throw new Error("No stems to import");
-
- const store = useProjectStore.getState();
- const projectId = store.project?.id;
- const base = (args.job.suggestedName ?? "Audio").replace(/\s*result$/i, "").trim() || "Audio";
-
- for (let index = 0; index < args.stems.length; index += 1) {
- const stem = args.stems[index];
- const label = stemLabelFromPath(stem.relativePath);
- const fileName = `${base} — ${label}.wav`;
- const file = new File([stem.bytes], fileName, { type: stem.mime || "audio/wav" });
-
- const targetId =
- index === 0 ? args.job.mediaId : `${args.job.mediaId}-${label.toLowerCase()}`;
- if (index > 0) {
- store.addPlaceholderMedia(buildPlaceholder(targetId, fileName, "audio"));
- }
-
- const result = await store.replaceMediaAsset(targetId, file);
- if (!result.success) {
- throw new Error(result.error?.message ?? `Failed to import ${label} stem`);
- }
-
- const item = store.getMediaItem(targetId);
- if (item && projectId) {
- await saveMediaBlob(projectId, targetId, file, item.metadata);
- }
- }
-}
diff --git a/apps/web/src/services/gpu-web-client.test.ts b/apps/web/src/services/gpu-web-client.test.ts
deleted file mode 100644
index d345a260..00000000
--- a/apps/web/src/services/gpu-web-client.test.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { describe, it, expect, vi, afterEach } from "vitest";
-import {
- WebGpuTokenProvider,
- WebGpuJobClient,
- normalizePresign,
- buildSubmitBody,
- GpuRequestError,
-} from "./gpu-web-client";
-
-function jsonRes(body: unknown, init: { ok?: boolean; status?: number } = {}): Response {
- return {
- ok: init.ok ?? true,
- status: init.status ?? 200,
- json: async () => body,
- headers: new Headers(),
- } as unknown as Response;
-}
-
-function binRes(bytes: ArrayBuffer, mime: string): Response {
- return {
- ok: true,
- status: 200,
- headers: new Headers({ "content-type": mime }),
- arrayBuffer: async () => bytes,
- } as unknown as Response;
-}
-
-const stubTokenProvider = () => ({
- getToken: vi.fn().mockResolvedValue("tok"),
- invalidate: vi.fn(),
-});
-
-function makeClient(tokenProvider: ReturnType<typeof stubTokenProvider>): WebGpuJobClient {
- return new WebGpuJobClient({
- gpuBaseUrl: "https://gpu",
- brokerBaseUrl: "https://broker",
- bundleId: "com.openreel.video",
- tokenProvider,
- });
-}
-
-afterEach(() => {
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
-});
-
-describe("normalizePresign", () => {
- it("maps putUrl/objectKey to uploadUrl/mediaKey", () => {
- const out = normalizePresign({ putUrl: "https://r2/put", objectKey: "jobs/a/b/in.mp4" });
- expect(out.uploadUrl).toBe("https://r2/put");
- expect(out.mediaKey).toBe("jobs/a/b/in.mp4");
- expect(out.headers).toEqual({});
- });
-
- it("also accepts uploadURL/mediaKey aliases", () => {
- const out = normalizePresign({ uploadURL: "https://r2/put", mediaKey: "jobs/x" });
- expect(out.uploadUrl).toBe("https://r2/put");
- expect(out.mediaKey).toBe("jobs/x");
- });
-
- it("throws when fields missing", () => {
- expect(() => normalizePresign({})).toThrow();
- });
-});
-
-describe("buildSubmitBody", () => {
- it("wraps request with mediaKey when media present", () => {
- const body = JSON.parse(buildSubmitBody({ kind: "upscale", params: { a: 1 }, mediaKey: "jobs/x", mediaFilename: "in.mp4" }));
- expect(body).toEqual({ request: { kind: "upscale", params: { a: 1 } }, mediaKey: "jobs/x", mediaFilename: "in.mp4" });
- });
-
- it("sends bare request when no media", () => {
- const body = JSON.parse(buildSubmitBody({ kind: "musicGeneration", params: { prompt: "x" } }));
- expect(body).toEqual({ kind: "musicGeneration", params: { prompt: "x" } });
- });
-});
-
-describe("WebGpuTokenProvider", () => {
- it("mints via challenge then token and caches", async () => {
- const exp = Math.floor(Date.now() / 1000) + 600;
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(jsonRes({ challengeId: "c1" }))
- .mockResolvedValueOnce(jsonRes({ token: "tok", exp }));
- vi.stubGlobal("fetch", fetchMock);
-
- const tp = new WebGpuTokenProvider("https://broker", "com.openreel.video", "inst-1");
- expect(await tp.getToken()).toBe("tok");
- expect(fetchMock).toHaveBeenCalledTimes(2);
-
- const challengeBody = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(challengeBody).toEqual({ platform: "desktop", instanceId: "inst-1" });
- expect(fetchMock.mock.calls[0][1].headers["X-Bundle-ID"]).toBe("com.openreel.video");
-
- expect(await tp.getToken()).toBe("tok");
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-
- it("throws GpuRequestError when challenge fails", async () => {
- const fetchMock = vi.fn().mockResolvedValueOnce(jsonRes({}, { ok: false, status: 403 }));
- vi.stubGlobal("fetch", fetchMock);
- const tp = new WebGpuTokenProvider("https://broker", "b", "inst");
- await expect(tp.getToken()).rejects.toBeInstanceOf(GpuRequestError);
- });
-});
-
-describe("WebGpuJobClient", () => {
- it("uploads a blob via presigned PUT and returns mediaKey", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(jsonRes({ putUrl: "https://r2/put", objectKey: "jobs/sub/uuid/in.mp4" }))
- .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers() } as unknown as Response);
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient(stubTokenProvider());
- const blob = new Blob([new Uint8Array([1, 2, 3])], { type: "video/mp4" });
- const { mediaKey } = await client.uploadMedia({ blob, filename: "in.mp4", contentType: "video/mp4" });
-
- expect(mediaKey).toBe("jobs/sub/uuid/in.mp4");
- expect(fetchMock.mock.calls[0][0]).toBe("https://broker/auth/upload-url");
- const putCall = fetchMock.mock.calls[1];
- expect(putCall[0]).toBe("https://r2/put");
- expect(putCall[1].method).toBe("PUT");
- expect(putCall[1].headers["Content-Type"]).toBe("video/mp4");
- expect(putCall[1].body).toBe(blob);
- });
-
- it("submits a job with request+mediaKey body and auth headers", async () => {
- const fetchMock = vi.fn().mockResolvedValueOnce(jsonRes({ jobID: "j1", status: "queued" }));
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient(stubTokenProvider());
- const created = await client.submitJob({ kind: "upscale", params: { a: 1 }, mediaKey: "jobs/x", mediaFilename: "in.mp4" });
-
- expect(created.jobID).toBe("j1");
- expect(fetchMock.mock.calls[0][0]).toBe("https://gpu/jobs");
- const body = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(body).toEqual({ request: { kind: "upscale", params: { a: 1 } }, mediaKey: "jobs/x", mediaFilename: "in.mp4" });
- expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe("Bearer tok");
- expect(fetchMock.mock.calls[0][1].headers["X-Bundle-ID"]).toBe("com.openreel.video");
- });
-
- it("throws retryable GpuRequestError on 503 queue full", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce({ ok: false, status: 503, headers: new Headers({ "retry-after": "5" }) } as unknown as Response);
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient(stubTokenProvider());
- await expect(client.submitJob({ kind: "upscale", params: {}, mediaKey: "jobs/x" })).rejects.toMatchObject({
- status: 503,
- retryAfterSeconds: 5,
- });
- });
-
- it("invalidates token and retries once on 401", async () => {
- const tokenProvider = stubTokenProvider();
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce({ ok: false, status: 401, headers: new Headers() } as unknown as Response)
- .mockResolvedValueOnce(jsonRes({ jobID: "j1", status: "processing" }));
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient(tokenProvider);
- const status = await client.jobStatus("j1");
-
- expect(status.status).toBe("processing");
- expect(tokenProvider.invalidate).toHaveBeenCalledTimes(1);
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-
- it("downloads an artifact as bytes + mime", async () => {
- const bytes = new Uint8Array([9, 8, 7]).buffer;
- const fetchMock = vi.fn().mockResolvedValueOnce(binRes(bytes, "image/png"));
- vi.stubGlobal("fetch", fetchMock);
-
- const client = makeClient(stubTokenProvider());
- const out = await client.downloadArtifact("j1", "out/result.png");
-
- expect(out.mime).toBe("image/png");
- expect(new Uint8Array(out.bytes)).toEqual(new Uint8Array([9, 8, 7]));
- expect(fetchMock.mock.calls[0][0]).toBe("https://gpu/jobs/j1/artifacts/out/result.png");
- });
-});
diff --git a/apps/web/src/services/gpu-web-client.ts b/apps/web/src/services/gpu-web-client.ts
deleted file mode 100644
index 34fa7962..00000000
--- a/apps/web/src/services/gpu-web-client.ts
+++ /dev/null
@@ -1,267 +0,0 @@
-import type { AiCloudJobCreated, AiCloudJobStatusResponse } from "@openreel/core";
-
-const BUNDLE_ID = "com.openreel.video";
-const INSTANCE_ID_STORAGE_KEY = "openreel.gpu.instanceId";
-const REFRESH_LEEWAY_SECONDS = 60;
-
-function trimTrailingSlash(value: string): string {
- return value.replace(/\/+$/, "");
-}
-
-function brokerBaseUrl(): string {
- const fromEnv = import.meta.env?.VITE_OPENREEL_AUTH_BROKER_BASE_URL as string | undefined;
- return trimTrailingSlash(fromEnv && fromEnv.length > 0 ? fromEnv : "https://api.openreel.video");
-}
-
-function gpuBaseUrl(): string {
- const fromEnv = import.meta.env?.VITE_OPENREEL_GPU_BASE_URL as string | undefined;
- return trimTrailingSlash(fromEnv && fromEnv.length > 0 ? fromEnv : "https://ai.openreel.video");
-}
-
-function nowSeconds(): number {
- return Math.floor(Date.now() / 1000);
-}
-
-function getInstanceId(): string {
- try {
- const existing = localStorage.getItem(INSTANCE_ID_STORAGE_KEY);
- if (existing) return existing;
- const id = crypto.randomUUID();
- localStorage.setItem(INSTANCE_ID_STORAGE_KEY, id);
- return id;
- } catch {
- return crypto.randomUUID();
- }
-}
-
-export class GpuRequestError extends Error {
- constructor(
- message: string,
- readonly status: number,
- readonly retryAfterSeconds?: number,
- ) {
- super(message);
- this.name = "GpuRequestError";
- }
-}
-
-interface NormalizedPresign {
- uploadUrl: string;
- mediaKey: string;
- downloadUrl?: string;
- headers: Record<string, string>;
-}
-
-export function normalizePresign(raw: Record<string, unknown>): NormalizedPresign {
- const uploadUrl = (raw.uploadURL ?? raw.putUrl) as string | undefined;
- const mediaKey = (raw.mediaKey ?? raw.objectKey) as string | undefined;
- if (!uploadUrl || !mediaKey) {
- throw new Error("presign response missing putUrl/uploadURL or objectKey/mediaKey");
- }
- const downloadUrl = (raw.getUrl ?? raw.downloadURL ?? raw.downloadUrl) as string | undefined;
- const headers = (raw.headers as Record<string, string> | undefined) ?? {};
- return { uploadUrl, mediaKey, downloadUrl, headers };
-}
-
-interface SubmitArgs {
- kind: string;
- params: Record<string, unknown>;
- mediaKey?: string;
- mediaFilename?: string;
-}
-
-export function buildSubmitBody(args: SubmitArgs): string {
- const request = { kind: args.kind, params: args.params };
- if (args.mediaKey) {
- return JSON.stringify({ request, mediaKey: args.mediaKey, mediaFilename: args.mediaFilename });
- }
- return JSON.stringify(request);
-}
-
-export class WebGpuTokenProvider {
- private cached: { token: string; exp: number } | null = null;
- private inflight: Promise<string> | null = null;
-
- constructor(
- private readonly broker: string,
- private readonly bundleId: string,
- private readonly instanceId: string,
- ) {}
-
- invalidate(): void {
- this.cached = null;
- }
-
- async getToken(): Promise<string> {
- if (this.cached && this.cached.exp - nowSeconds() > REFRESH_LEEWAY_SECONDS) {
- return this.cached.token;
- }
- if (this.inflight) return this.inflight;
- this.inflight = this.mint().finally(() => {
- this.inflight = null;
- });
- return this.inflight;
- }
-
- private headers(): Record<string, string> {
- return {
- "Content-Type": "application/json",
- Accept: "application/json",
- "X-Bundle-ID": this.bundleId,
- };
- }
-
- private async mint(): Promise<string> {
- const challengeRes = await fetch(`${this.broker}/auth/challenge`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform: "desktop", instanceId: this.instanceId }),
- });
- if (!challengeRes.ok) {
- throw new GpuRequestError(`auth challenge failed: ${challengeRes.status}`, challengeRes.status);
- }
- const challenge = (await challengeRes.json()) as { challengeId?: string };
- if (!challenge.challengeId) {
- throw new Error("auth challenge missing challengeId");
- }
-
- const tokenRes = await fetch(`${this.broker}/auth/token`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform: "desktop", challengeId: challenge.challengeId }),
- });
- if (!tokenRes.ok) {
- throw new GpuRequestError(`auth token mint failed: ${tokenRes.status}`, tokenRes.status);
- }
- const minted = (await tokenRes.json()) as { token?: string; exp?: number };
- if (!minted.token || typeof minted.exp !== "number") {
- throw new Error("auth token response malformed");
- }
- this.cached = { token: minted.token, exp: minted.exp };
- return minted.token;
- }
-}
-
-export interface WebGpuJobClientDeps {
- gpuBaseUrl: string;
- brokerBaseUrl: string;
- bundleId: string;
- tokenProvider: Pick<WebGpuTokenProvider, "getToken" | "invalidate">;
-}
-
-export class WebGpuJobClient {
- constructor(private readonly deps: WebGpuJobClientDeps) {}
-
- private async authHeaders(): Promise<Record<string, string>> {
- const token = await this.deps.tokenProvider.getToken();
- return {
- Authorization: `Bearer ${token}`,
- "X-Bundle-ID": this.deps.bundleId,
- Accept: "application/json",
- };
- }
-
- private async authedFetch(url: string, init: NonNullable<Parameters<typeof fetch>[1]>): Promise<Response> {
- const baseHeaders = (init.headers as Record<string, string> | undefined) ?? {};
- let res = await fetch(url, { ...init, headers: { ...baseHeaders, ...(await this.authHeaders()) } });
- if (res.status === 401) {
- this.deps.tokenProvider.invalidate();
- res = await fetch(url, { ...init, headers: { ...baseHeaders, ...(await this.authHeaders()) } });
- }
- return res;
- }
-
- async uploadMedia(args: { blob: Blob; filename: string; contentType?: string }): Promise<{ mediaKey: string; downloadUrl?: string }> {
- const presignRes = await this.authedFetch(`${this.deps.brokerBaseUrl}/auth/upload-url`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ filename: args.filename, contentType: args.contentType }),
- });
- if (!presignRes.ok) {
- throw new GpuRequestError(`presign failed: ${presignRes.status}`, presignRes.status);
- }
- const presign = normalizePresign((await presignRes.json()) as Record<string, unknown>);
- const putHeaders: Record<string, string> = { ...presign.headers };
- const contentType = args.contentType || args.blob.type;
- if (contentType && !putHeaders["Content-Type"] && !putHeaders["content-type"]) {
- putHeaders["Content-Type"] = contentType;
- }
- const putRes = await fetch(presign.uploadUrl, {
- method: "PUT",
- headers: putHeaders,
- body: args.blob,
- });
- if (!putRes.ok) {
- throw new GpuRequestError(`upload PUT failed: ${putRes.status}`, putRes.status);
- }
- return { mediaKey: presign.mediaKey, downloadUrl: presign.downloadUrl };
- }
-
- async submitJob(args: SubmitArgs): Promise<AiCloudJobCreated> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: buildSubmitBody(args),
- });
- if (res.status === 503) {
- const retryAfter = Number(res.headers.get("retry-after"));
- throw new GpuRequestError("queue full", 503, Number.isFinite(retryAfter) ? retryAfter : undefined);
- }
- if (!res.ok) {
- throw new GpuRequestError(`submit failed: ${res.status}`, res.status);
- }
- return (await res.json()) as AiCloudJobCreated;
- }
-
- async jobStatus(jobID: string): Promise<AiCloudJobStatusResponse> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}`, { method: "GET" });
- if (!res.ok) {
- throw new GpuRequestError(`status failed: ${res.status}`, res.status);
- }
- return (await res.json()) as AiCloudJobStatusResponse;
- }
-
- async fetchManifest(jobID: string): Promise<Record<string, unknown>> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}/manifest`, { method: "GET" });
- if (!res.ok) {
- throw new GpuRequestError(`manifest failed: ${res.status}`, res.status);
- }
- return (await res.json()) as Record<string, unknown>;
- }
-
- async downloadArtifact(jobID: string, relativePath: string): Promise<{ bytes: ArrayBuffer; mime: string }> {
- const res = await this.authedFetch(
- `${this.deps.gpuBaseUrl}/jobs/${jobID}/artifacts/${relativePath}`,
- { method: "GET" },
- );
- if (!res.ok) {
- throw new GpuRequestError(`artifact download failed: ${res.status}`, res.status);
- }
- const mime = res.headers.get("content-type") ?? "application/octet-stream";
- const bytes = await res.arrayBuffer();
- return { bytes, mime };
- }
-
- async cancelJob(jobID: string): Promise<AiCloudJobStatusResponse> {
- const res = await this.authedFetch(`${this.deps.gpuBaseUrl}/jobs/${jobID}`, { method: "DELETE" });
- if (!res.ok) {
- throw new GpuRequestError(`cancel failed: ${res.status}`, res.status);
- }
- return (await res.json()) as AiCloudJobStatusResponse;
- }
-}
-
-let cachedClient: WebGpuJobClient | null = null;
-
-export function getWebGpuClient(): WebGpuJobClient {
- if (cachedClient) return cachedClient;
- const broker = brokerBaseUrl();
- const tokenProvider = new WebGpuTokenProvider(broker, BUNDLE_ID, getInstanceId());
- cachedClient = new WebGpuJobClient({
- gpuBaseUrl: gpuBaseUrl(),
- brokerBaseUrl: broker,
- bundleId: BUNDLE_ID,
- tokenProvider,
- });
- return cachedClient;
-}
diff --git a/apps/web/src/services/highlight-service.ts b/apps/web/src/services/highlight-service.ts
index a0fb241b..18f5800d 100644
--- a/apps/web/src/services/highlight-service.ts
+++ b/apps/web/src/services/highlight-service.ts
@@ -1,7 +1,6 @@
import {
analyzeAudioForHighlights,
type TranscriptWord,
- type AudioSegmentMetrics,
} from "@openreel/core";
export interface HighlightResult {
@@ -28,8 +27,6 @@ const DEFAULT_PREFERENCES: HighlightPreferences = {
type ProgressCallback = (phase: string, progress: number, message: string) => void;
-const API_BASE = import.meta.env.VITE_CLOUD_API_URL || "https://api.openreel.video";
-
export async function extractHighlights(
audioBuffer: AudioBuffer,
transcript: TranscriptWord[],
@@ -41,41 +38,55 @@ export async function extractHighlights(
onProgress?.("analyze", 10, "Analyzing audio energy...");
const analysis = analyzeAudioForHighlights(audioBuffer, transcript);
- onProgress?.("analyze", 30, "Preparing data for AI...");
- const energyData = analysis.segments
- .filter((seg) => !seg.isSilence)
- .map((seg: AudioSegmentMetrics) => ({
- start: seg.start,
- end: seg.end,
- rmsDb: seg.rmsDb,
- peakDb: seg.peakDb,
- }));
+ onProgress?.("rank", 35, "Ranking energetic moments locally...");
+ const usable = analysis.segments.filter((segment) => !segment.isSilence);
+ if (usable.length === 0) return [];
- onProgress?.("ai", 40, "Sending to AI for highlight detection...");
+ const windowDuration = Math.min(
+ prefs.maxClipDuration,
+ Math.max(prefs.minClipDuration, 15),
+ );
+ const maxRms = Math.max(...usable.map((segment) => segment.rmsDb));
+ const minRms = Math.min(...usable.map((segment) => segment.rmsDb));
+ const rmsRange = Math.max(maxRms - minRms, 1);
- const response = await fetch(`${API_BASE}/highlights`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- transcript: transcript.map((w) => ({
- text: w.text,
- start: w.start,
- end: w.end,
- })),
- energy: energyData,
- duration: analysis.duration,
- preferences: prefs,
- }),
+ const candidates = usable.map((anchor) => {
+ const start = Math.min(
+ Math.max(0, anchor.start - windowDuration / 3),
+ Math.max(0, analysis.duration - windowDuration),
+ );
+ const end = Math.min(analysis.duration, start + windowDuration);
+ const windowSegments = usable.filter(
+ (segment) => segment.end > start && segment.start < end,
+ );
+ const energy =
+ windowSegments.reduce(
+ (total, segment) => total + (segment.rmsDb - minRms) / rmsRange,
+ 0,
+ ) / Math.max(windowSegments.length, 1);
+ const speech =
+ windowSegments.reduce((total, segment) => total + segment.speechRate, 0) /
+ Math.max(windowSegments.length, 1);
+ const score = Math.min(10, Math.max(1, 1 + energy * 7 + Math.min(speech, 2) * 1));
+ return { start, end, score };
});
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- throw new Error((errorData as { error?: string }).error || `API error: ${response.status}`);
+ const selected: HighlightResult[] = [];
+ for (const candidate of candidates.sort((a, b) => b.score - a.score)) {
+ const overlaps = selected.some(
+ (item) => candidate.start < item.end && candidate.end > item.start,
+ );
+ if (overlaps) continue;
+ selected.push({
+ ...candidate,
+ title: `Highlight ${selected.length + 1}`,
+ reason: transcript.length > 0
+ ? "Strong local audio energy and speech activity"
+ : "Strong local audio energy",
+ });
+ if (selected.length >= prefs.targetClipCount) break;
}
- onProgress?.("ai", 80, "Processing AI response...");
- const data = (await response.json()) as { highlights: HighlightResult[] };
-
- onProgress?.("done", 100, "Highlights ready");
- return data.highlights;
+ onProgress?.("done", 100, "Local highlights ready");
+ return selected.sort((a, b) => a.start - b.start);
}
diff --git a/apps/web/src/services/multicam-analysis-store.ts b/apps/web/src/services/multicam-analysis-store.ts
new file mode 100644
index 00000000..879de389
--- /dev/null
+++ b/apps/web/src/services/multicam-analysis-store.ts
@@ -0,0 +1,36 @@
+import { createStore, del, get, set } from "idb-keyval";
+import {
+ deserializeOrma,
+ serializeOrma,
+ type OrmaArtifact,
+} from "@openreel/core";
+
+const store = createStore("openreel-multicam-analysis", "orma-artifacts");
+
+export const multicamArtifactId = (projectId: string, groupId: string): string =>
+ `${projectId}/${groupId}.orma`;
+
+export async function saveMulticamArtifact(
+ projectId: string,
+ groupId: string,
+ artifact: OrmaArtifact,
+): Promise<string> {
+ const id = multicamArtifactId(projectId, groupId);
+ await set(id, serializeOrma(artifact), store);
+ return id;
+}
+
+export async function loadMulticamArtifact(
+ projectId: string,
+ groupId: string,
+): Promise<OrmaArtifact | undefined> {
+ const serialized = await get<string>(multicamArtifactId(projectId, groupId), store);
+ return serialized ? deserializeOrma(serialized) : undefined;
+}
+
+export async function removeMulticamArtifact(
+ projectId: string,
+ groupId: string,
+): Promise<void> {
+ await del(multicamArtifactId(projectId, groupId), store);
+}
diff --git a/apps/web/src/services/multicam-face-reactions.ts b/apps/web/src/services/multicam-face-reactions.ts
new file mode 100644
index 00000000..9a969084
--- /dev/null
+++ b/apps/web/src/services/multicam-face-reactions.ts
@@ -0,0 +1,107 @@
+import type {
+ MulticamFaceSignal,
+ MulticamManifest,
+ MulticamReactionCue,
+} from "@openreel/core";
+import { detectMulticamReactionCues } from "@openreel/core";
+import type { ResolvedMulticamSource } from "../components/editor/inspector/multicam-workflow";
+
+const FACE_MODEL =
+ "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task";
+const VISION_WASM =
+ "https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm";
+
+function waitFor(video: HTMLVideoElement, event: "loadedmetadata" | "seeked"): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ video.removeEventListener(event, complete);
+ video.removeEventListener("error", failed);
+ };
+ const complete = () => {
+ cleanup();
+ resolve();
+ };
+ const failed = () => {
+ cleanup();
+ reject(new Error("Could not decode a camera for face reaction analysis."));
+ };
+ video.addEventListener(event, complete, { once: true });
+ video.addEventListener("error", failed, { once: true });
+ });
+}
+
+/** Samples close-up cameras locally with MediaPipe Face Landmarker. */
+export async function analyzeMulticamFaceReactions(
+ sources: readonly ResolvedMulticamSource[],
+ manifest: MulticamManifest,
+ durationSeconds: number,
+ options: { intervalMs?: number; onProgress?: (message: string) => void } = {},
+): Promise<MulticamReactionCue[]> {
+ const { FaceLandmarker, FilesetResolver } = await import("@mediapipe/tasks-vision");
+ const fileset = await FilesetResolver.forVisionTasks(VISION_WASM);
+ const landmarker = await FaceLandmarker.createFromOptions(fileset, {
+ baseOptions: { modelAssetPath: FACE_MODEL, delegate: "GPU" },
+ runningMode: "VIDEO",
+ numFaces: 1,
+ outputFaceBlendshapes: true,
+ });
+ const intervalMs = Math.max(250, options.intervalMs ?? 1_000);
+ const signals: MulticamFaceSignal[] = [];
+ let detectorTimestamp = 0;
+ try {
+ for (const camera of manifest.cameras) {
+ if (camera.subject === "all" || camera.subject.includes("+")) continue;
+ const source = sources.find(
+ (entry) => entry.angle.id === camera.id || entry.clip.id === camera.clipId,
+ );
+ if (!source?.media.blob) continue;
+ const url = URL.createObjectURL(source.media.blob);
+ const video = document.createElement("video");
+ video.muted = true;
+ video.preload = "auto";
+ video.src = url;
+ try {
+ await waitFor(video, "loadedmetadata");
+ let previousNose: { x: number; y: number } | undefined;
+ for (let timelineMs = 0; timelineMs < durationSeconds * 1_000; timelineMs += intervalMs) {
+ const sourceTime =
+ source.clip.inPoint +
+ source.angle.offset +
+ (timelineMs / 1_000) * Math.max(0.01, source.clip.speed ?? 1);
+ if (sourceTime < 0 || sourceTime >= video.duration) continue;
+ video.currentTime = sourceTime;
+ await waitFor(video, "seeked");
+ detectorTimestamp += intervalMs;
+ const result = landmarker.detectForVideo(video, detectorTimestamp);
+ const face = result.faceLandmarks[0];
+ const categories = result.faceBlendshapes[0]?.categories ?? [];
+ if (!face) continue;
+ const score = (name: string) =>
+ categories.find((entry) => entry.categoryName === name)?.score ?? 0;
+ const nose = face[1] ? { x: face[1].x, y: face[1].y } : undefined;
+ const headMotion = nose && previousNose
+ ? Math.min(1, Math.hypot(nose.x - previousNose.x, nose.y - previousNose.y) * 8)
+ : 0;
+ previousNose = nose;
+ signals.push({
+ participantId: camera.subject,
+ timeMs: timelineMs,
+ smile: (score("mouthSmileLeft") + score("mouthSmileRight")) / 2,
+ surprise: Math.max(score("browInnerUp"), score("jawOpen")),
+ headMotion,
+ });
+ options.onProgress?.(
+ `${camera.id} face cues · ${Math.round((timelineMs / (durationSeconds * 1_000)) * 100)}%`,
+ );
+ }
+ } finally {
+ video.removeAttribute("src");
+ video.load();
+ URL.revokeObjectURL(url);
+ }
+ }
+ } finally {
+ landmarker.close();
+ }
+ return detectMulticamReactionCues(signals);
+}
diff --git a/apps/web/src/services/multicam-transcription.test.ts b/apps/web/src/services/multicam-transcription.test.ts
new file mode 100644
index 00000000..4cee2fe3
--- /dev/null
+++ b/apps/web/src/services/multicam-transcription.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from "vitest";
+import { whisperChunksToMulticamTranscript } from "./multicam-transcription";
+
+describe("multicam transcription", () => {
+ it("normalizes Whisper timestamps and removes empty chunks", () => {
+ expect(whisperChunksToMulticamTranscript([
+ { text: " Hello ", timestamp: [0.25, 1.5] },
+ { text: " ", timestamp: [1.5, 2] },
+ { text: "world", timestamp: [2, null] },
+ ])).toEqual([
+ { text: "Hello", startMs: 250, endMs: 1_500 },
+ { text: "world", startMs: 2_000, endMs: 5_000 },
+ ]);
+ });
+});
diff --git a/apps/web/src/services/multicam-transcription.ts b/apps/web/src/services/multicam-transcription.ts
new file mode 100644
index 00000000..b60a8711
--- /dev/null
+++ b/apps/web/src/services/multicam-transcription.ts
@@ -0,0 +1,74 @@
+import type { MulticamTranscriptSegment } from "@openreel/core";
+import { audioBufferToWhisperSamples } from "../utils/whisper-audio";
+import type { WhisperModelKey } from "../workers/whisper-models";
+
+interface WorkerChunk {
+ text: string;
+ timestamp: [number | null, number | null];
+}
+
+export function whisperChunksToMulticamTranscript(
+ chunks: readonly WorkerChunk[],
+): MulticamTranscriptSegment[] {
+ return chunks.flatMap((chunk) => {
+ const text = chunk.text.trim();
+ if (!text) return [];
+ const start = Math.max(0, chunk.timestamp[0] ?? 0);
+ const end = Math.max(start, chunk.timestamp[1] ?? start + 3);
+ return [{ startMs: Math.round(start * 1_000), endMs: Math.round(end * 1_000), text }];
+ });
+}
+
+export async function transcribeMulticamChannels(
+ buffers: ReadonlyMap<string, AudioBuffer>,
+ options: {
+ model?: WhisperModelKey;
+ language?: string;
+ onStatus?: (angleId: string, message: string) => void;
+ } = {},
+): Promise<Record<string, MulticamTranscriptSegment[]>> {
+ const worker = new Worker(
+ new URL("../workers/whisper-worker.ts", import.meta.url),
+ { type: "module" },
+ );
+ try {
+ const transcripts: Record<string, MulticamTranscriptSegment[]> = {};
+ for (const [angleId, buffer] of buffers) {
+ const requestId = crypto.randomUUID();
+ options.onStatus?.(angleId, "Loading local Whisper model…");
+ const result = await new Promise<{ chunks: WorkerChunk[] }>((resolve, reject) => {
+ const handleMessage = (event: MessageEvent<Record<string, unknown>>) => {
+ if (event.data.requestId !== requestId) return;
+ const type = event.data.type;
+ if (type === "model-progress") {
+ const progress = Number(event.data.progress ?? 0);
+ options.onStatus?.(
+ angleId,
+ `Loading local Whisper model · ${Math.round((progress > 1 ? progress / 100 : progress) * 100)}%`,
+ );
+ } else if (type === "transcription-progress") {
+ options.onStatus?.(angleId, "Transcribing locally…");
+ } else if (type === "result") {
+ worker.removeEventListener("message", handleMessage);
+ resolve({ chunks: (event.data.chunks as WorkerChunk[] | undefined) ?? [] });
+ } else if (type === "error") {
+ worker.removeEventListener("message", handleMessage);
+ reject(new Error(String(event.data.message ?? "Local transcription failed.")));
+ }
+ };
+ worker.addEventListener("message", handleMessage);
+ worker.postMessage({
+ requestId,
+ type: "transcribe",
+ audio: audioBufferToWhisperSamples(buffer),
+ model: options.model ?? "fast",
+ language: options.language,
+ });
+ });
+ transcripts[angleId] = whisperChunksToMulticamTranscript(result.chunks);
+ }
+ return transcripts;
+ } finally {
+ worker.terminate();
+ }
+}
diff --git a/apps/web/src/services/secure-storage.desktop.test.ts b/apps/web/src/services/secure-storage.desktop.test.ts
index 34db9841..0292d4b2 100644
--- a/apps/web/src/services/secure-storage.desktop.test.ts
+++ b/apps/web/src/services/secure-storage.desktop.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
saveSecret,
getSecret,
+ hasSecret,
deleteSecret,
isSessionUnlocked,
isMasterPasswordSet,
@@ -48,6 +49,12 @@ describe("secure-storage desktop branch", () => {
expect(await getSecret("missing")).toBeNull();
});
+ it("checks key existence without exposing it to the caller", async () => {
+ await expect(hasSecret("openai")).resolves.toBe(true);
+ keychain.get.mockResolvedValueOnce(null);
+ await expect(hasSecret("missing")).resolves.toBe(false);
+ });
+
it("deleteSecret routes to keychain.delete", async () => {
await deleteSecret("openai");
expect(keychain.delete).toHaveBeenCalledWith("openai");
diff --git a/apps/web/src/services/secure-storage.ts b/apps/web/src/services/secure-storage.ts
index 9dd1bc5a..8c3b2380 100644
--- a/apps/web/src/services/secure-storage.ts
+++ b/apps/web/src/services/secure-storage.ts
@@ -491,6 +491,21 @@ export async function getSecret(id: string): Promise<string | null> {
return await decrypt(record.encryptedData, iv, derivedKey);
}
+/** Check whether a secret exists without exposing its value to UI code. */
+export async function hasSecret(id: string): Promise<boolean> {
+ const kc = desktopKeychain();
+ if (kc) return (await kc.get(id)) !== null;
+
+ const db = await getDatabase();
+ const record = await idbTransaction<SecureRecord | undefined>(
+ db,
+ STORE_SECRETS,
+ "readonly",
+ (store) => store.get(id),
+ );
+ return record !== undefined;
+}
+
/**
* Delete a secret.
*/
diff --git a/apps/web/src/stores/chat-history-store.test.ts b/apps/web/src/stores/chat-history-store.test.ts
new file mode 100644
index 00000000..4528ca7c
--- /dev/null
+++ b/apps/web/src/stores/chat-history-store.test.ts
@@ -0,0 +1,78 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { conversationTitle, useChatHistoryStore } from "./chat-history-store";
+import type { ChatMessage } from "./chat-store";
+
+const messages: ChatMessage[] = [
+ {
+ id: "user-1",
+ role: "user",
+ text: "Create a strong opening title for this short video",
+ toolCalls: [],
+ },
+ {
+ id: "assistant-1",
+ role: "assistant",
+ text: "Done.",
+ toolCalls: [],
+ },
+];
+
+describe("chat history store", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ useChatHistoryStore.getState().clearHistory();
+ });
+
+ it("creates a concise title from the first user request", () => {
+ expect(conversationTitle(messages)).toBe(
+ "Create a strong opening title for this short video",
+ );
+ });
+
+ it("saves and updates a project-scoped conversation", () => {
+ const save = useChatHistoryStore.getState().saveConversation;
+ save({
+ id: "chat-1",
+ projectId: "project-a",
+ title: "Opening title",
+ createdAt: 1,
+ updatedAt: 2,
+ messages,
+ usage: { inputTokens: 10, outputTokens: 5 },
+ });
+ save({
+ id: "chat-1",
+ projectId: "project-a",
+ title: "Opening title updated",
+ createdAt: 1,
+ updatedAt: 3,
+ messages,
+ usage: { inputTokens: 20, outputTokens: 8 },
+ });
+
+ expect(useChatHistoryStore.getState().conversations).toEqual([
+ expect.objectContaining({
+ id: "chat-1",
+ projectId: "project-a",
+ title: "Opening title updated",
+ updatedAt: 3,
+ }),
+ ]);
+ });
+
+ it("removes a saved conversation", () => {
+ useChatHistoryStore.getState().saveConversation({
+ id: "chat-1",
+ projectId: "project-a",
+ title: "Opening title",
+ createdAt: 1,
+ updatedAt: 2,
+ messages,
+ usage: { inputTokens: 0, outputTokens: 0 },
+ });
+
+ useChatHistoryStore.getState().deleteConversation("chat-1");
+
+ expect(useChatHistoryStore.getState().conversations).toEqual([]);
+ });
+});
diff --git a/apps/web/src/stores/chat-history-store.ts b/apps/web/src/stores/chat-history-store.ts
new file mode 100644
index 00000000..8c747a08
--- /dev/null
+++ b/apps/web/src/stores/chat-history-store.ts
@@ -0,0 +1,101 @@
+import { create } from "zustand";
+import { persist } from "zustand/middleware";
+import type { ChatMessage, TokenUsage } from "./chat-store";
+
+export interface SavedChatConversation {
+ readonly id: string;
+ readonly projectId: string;
+ readonly title: string;
+ readonly createdAt: number;
+ readonly updatedAt: number;
+ readonly messages: ChatMessage[];
+ readonly usage: TokenUsage;
+ readonly error?: string;
+}
+
+interface ChatHistoryState {
+ conversations: SavedChatConversation[];
+ saveConversation: (conversation: SavedChatConversation) => void;
+ deleteConversation: (conversationId: string) => void;
+ clearHistory: () => void;
+}
+
+const MAX_CONVERSATIONS = 30;
+const MAX_MESSAGES_PER_CONVERSATION = 100;
+
+function compactValue(value: unknown, depth = 0): unknown {
+ if (depth >= 3) return "[Details omitted]";
+ if (typeof value === "string") {
+ return value.length > 2_000 ? `${value.slice(0, 2_000)}…` : value;
+ }
+ if (Array.isArray(value)) {
+ return value.slice(0, 20).map((item) => compactValue(item, depth + 1));
+ }
+ if (typeof value === "object" && value !== null) {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .slice(0, 30)
+ .map(([key, item]) => [key, compactValue(item, depth + 1)]),
+ );
+ }
+ return value;
+}
+
+function compactMessages(messages: ChatMessage[]): ChatMessage[] {
+ return messages.slice(-MAX_MESSAGES_PER_CONVERSATION).map((message) => ({
+ ...message,
+ toolCalls: message.toolCalls.map((call) => ({
+ ...call,
+ args: compactValue(call.args) as Record<string, unknown>,
+ result: call.result
+ ? {
+ ok: call.result.ok,
+ summary: call.result.summary,
+ error: call.result.error,
+ }
+ : undefined,
+ })),
+ }));
+}
+
+export function conversationTitle(messages: ChatMessage[]): string {
+ const firstRequest = messages.find(
+ (message) => message.role === "user" && message.text.trim(),
+ )?.text;
+ if (!firstRequest) return "New conversation";
+ const title = firstRequest.replace(/\s+/g, " ").trim();
+ return title.length > 56 ? `${title.slice(0, 55)}…` : title;
+}
+
+export const useChatHistoryStore = create<ChatHistoryState>()(
+ persist(
+ (set) => ({
+ conversations: [],
+ saveConversation: (conversation) =>
+ set((state) => ({
+ conversations: [
+ {
+ ...conversation,
+ messages: compactMessages(conversation.messages),
+ },
+ ...state.conversations.filter(
+ (item) => item.id !== conversation.id,
+ ),
+ ]
+ .sort((a, b) => b.updatedAt - a.updatedAt)
+ .slice(0, MAX_CONVERSATIONS),
+ })),
+ deleteConversation: (conversationId) =>
+ set((state) => ({
+ conversations: state.conversations.filter(
+ (item) => item.id !== conversationId,
+ ),
+ })),
+ clearHistory: () => set({ conversations: [] }),
+ }),
+ {
+ name: "openreel-ai-chat-history",
+ version: 1,
+ },
+ ),
+);
diff --git a/apps/web/src/stores/chat-store.test.ts b/apps/web/src/stores/chat-store.test.ts
index 0b10857e..8186c8ad 100644
--- a/apps/web/src/stores/chat-store.test.ts
+++ b/apps/web/src/stores/chat-store.test.ts
@@ -5,12 +5,15 @@ const h = vi.hoisted(() => ({
runTurn: vi.fn(),
getSecret: vi.fn(async () => "test-key"),
isSessionUnlocked: vi.fn(() => true),
+ makeBYOKClient: vi.fn(() => ({ complete: vi.fn() })),
undo: vi.fn(async () => ({ success: true })),
- projectState: { hasOpenProject: true },
+ projectState: { hasOpenProject: true, projectId: "project-a" },
undoStackSize: 0,
settings: {
- defaultLlmProvider: "openai",
- llmModel: "gpt-4o",
+ defaultLlmProvider: "openai-compatible" as string | null,
+ llmBaseUrl: "https://gateway.example/v1",
+ llmModel: "account-tool-model",
+ configuredServices: ["openai-compatible"] as string[],
agentAutoConfirm: false,
agentDryRun: false,
},
@@ -21,6 +24,7 @@ vi.mock("@openreel/agent", () => ({
toAnthropicTools: () => [],
toOpenAITools: () => [],
buildSystemPrompt: () => "system",
+ selectToolsForPrompt: () => [],
}));
vi.mock("../services/secure-storage", () => ({
@@ -33,12 +37,7 @@ vi.mock("../services/agent/live-host", () => ({
}));
vi.mock("../services/agent/llm-transport", () => ({
- makeBYOKClient: () => ({ complete: vi.fn() }),
-}));
-
-vi.mock("../services/agent/models", () => ({
- defaultModelFor: () => "gpt-4o",
- modelsFor: () => [{ id: "gpt-4o", label: "GPT-4o" }],
+ makeBYOKClient: h.makeBYOKClient,
}));
vi.mock("./settings-store", () => ({
@@ -51,6 +50,7 @@ vi.mock("./project-store", () => ({
useProjectStore: {
getState: () => ({
hasOpenProject: h.projectState.hasOpenProject,
+ project: { id: h.projectState.projectId },
undo: h.undo,
actionExecutor: {
getHistory: () => ({ getUndoStackSize: () => h.undoStackSize }),
@@ -60,6 +60,7 @@ vi.mock("./project-store", () => ({
}));
import { useChatStore } from "./chat-store";
+import { useChatHistoryStore } from "./chat-history-store";
type RunTurnImpl = (input: RunTurnInput) => Promise<RunTurnResult>;
type RunTurnImplLoose = (
@@ -78,11 +79,17 @@ const store = () => useChatStore.getState();
describe("chat-store", () => {
beforeEach(() => {
store().reset();
+ useChatHistoryStore.getState().clearHistory();
vi.clearAllMocks();
h.getSecret.mockResolvedValue("test-key");
h.isSessionUnlocked.mockReturnValue(true);
h.undo.mockResolvedValue({ success: true });
h.projectState.hasOpenProject = true;
+ h.projectState.projectId = "project-a";
+ h.settings.defaultLlmProvider = "openai-compatible";
+ h.settings.llmBaseUrl = "https://gateway.example/v1";
+ h.settings.llmModel = "account-tool-model";
+ h.settings.configuredServices = ["openai-compatible"];
h.settings.agentAutoConfirm = false;
h.settings.agentDryRun = false;
h.undoStackSize = 0;
@@ -141,6 +148,231 @@ describe("chat-store", () => {
});
});
+ it("saves completed conversations and starts a fresh chat", async () => {
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "Done!",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("Create an opening title");
+ const saved = useChatHistoryStore.getState().conversations[0];
+ expect(saved).toMatchObject({
+ projectId: "project-a",
+ title: "Create an opening title",
+ });
+
+ store().newChat();
+
+ expect(store().messages).toEqual([]);
+ expect(store().currentConversationId).toBeNull();
+ expect(useChatHistoryStore.getState().conversations[0].id).toBe(saved.id);
+ });
+
+ it("opens a saved conversation for viewing and follow-up", async () => {
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "Done!",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+ await store().send("Fix the intro");
+ const savedId = useChatHistoryStore.getState().conversations[0].id;
+ store().newChat();
+
+ store().openConversation(savedId);
+
+ expect(store().currentConversationId).toBe(savedId);
+ expect(store().messages[0].text).toBe("Fix the intro");
+ expect(store().conversation[0]).toEqual({
+ role: "user",
+ content: "Fix the intro",
+ });
+ });
+
+ it("uses the final result text even when an adapter emits no text event", async () => {
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "## Finished\n\n- Updated the intro",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("update intro");
+
+ expect(store().messages.at(-1)?.text).toBe("## Finished\n\n- Updated the intro");
+ });
+
+ it("explains empty model replies and output-limit stops", async () => {
+ h.runTurn
+ .mockImplementationOnce(
+ impl(async ({ messages }) => ({
+ text: "",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ )
+ .mockImplementationOnce(
+ impl(async ({ messages }) => ({
+ text: "Partial",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "budget",
+ committed: true,
+ })),
+ );
+
+ await store().send("first");
+ expect(store().messages.at(-1)?.notice).toMatch(/empty response/i);
+
+ await store().send("second");
+ expect(store().messages.at(-1)?.text).toBe("Partial");
+ expect(store().messages.at(-1)?.notice).toMatch(/response or token limit/i);
+ });
+
+ it("passes a custom provider model ID through to the BYOK client", async () => {
+ h.settings.llmModel = "gpt-custom-account-model";
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "ok",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("hello");
+
+ expect(h.makeBYOKClient).toHaveBeenCalledWith(
+ expect.objectContaining({
+ provider: "openai-compatible",
+ model: "gpt-custom-account-model",
+ }),
+ );
+ });
+
+ it("runs against a keyless OpenAI-compatible endpoint", async () => {
+ h.settings.defaultLlmProvider = "openai-compatible";
+ h.settings.llmBaseUrl = "http://localhost:11434/v1/";
+ h.settings.llmModel = "llama3.2";
+ h.settings.configuredServices = [];
+ h.isSessionUnlocked.mockReturnValue(false);
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "ok",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("hello local model");
+
+ expect(h.getSecret).not.toHaveBeenCalled();
+ expect(h.makeBYOKClient).toHaveBeenCalledWith(
+ expect.objectContaining({
+ provider: "openai-compatible",
+ model: "llama3.2",
+ baseUrl: "http://localhost:11434/v1",
+ apiKey: "",
+ }),
+ );
+ expect(h.runTurn).toHaveBeenCalledOnce();
+ });
+
+ it("blocks a compatible provider until endpoint and model are configured", async () => {
+ h.settings.defaultLlmProvider = "openai-compatible";
+ h.settings.llmModel = "";
+
+ await store().send("hello");
+
+ expect(h.runTurn).not.toHaveBeenCalled();
+ expect(store().error).toMatch(/model id/i);
+ });
+
+ it("requires the user to choose an API format", async () => {
+ h.settings.defaultLlmProvider = null;
+
+ await store().send("hello");
+
+ expect(h.runTurn).not.toHaveBeenCalled();
+ expect(store().error).toMatch(/api format/i);
+ });
+
+ it("runs against an Anthropic-compatible endpoint", async () => {
+ h.settings.defaultLlmProvider = "anthropic-compatible";
+ h.settings.llmBaseUrl = "https://anthropic-gateway.example/v1/messages";
+ h.settings.llmModel = "gateway/claude-tool-model";
+ h.settings.configuredServices = [];
+ h.isSessionUnlocked.mockReturnValue(false);
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "ok",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+
+ await store().send("hello compatible model");
+
+ expect(h.makeBYOKClient).toHaveBeenCalledWith(
+ expect.objectContaining({
+ provider: "anthropic-compatible",
+ model: "gateway/claude-tool-model",
+ baseUrl: "https://anthropic-gateway.example/v1",
+ apiKey: "",
+ }),
+ );
+ expect(h.runTurn).toHaveBeenCalledOnce();
+ });
+
+ it("clears the conversation when the open project changes", async () => {
+ h.runTurn.mockImplementation(
+ impl(async ({ messages }) => ({
+ text: "ok",
+ messages,
+ toolCalls: 0,
+ stoppedReason: "end_turn",
+ committed: true,
+ })),
+ );
+ store().setProjectContext("project-a");
+ await store().send("edit project A");
+ expect(store().messages.length).toBeGreaterThan(0);
+
+ store().setProjectContext("project-b");
+
+ expect(store().projectId).toBe("project-b");
+ expect(store().messages).toHaveLength(0);
+ expect(store().conversation).toHaveLength(0);
+ });
+
+ it("returns to an actionable error state when a turn throws", async () => {
+ h.runTurn.mockRejectedValue(new Error("provider unavailable"));
+
+ await store().send("hello");
+
+ expect(store().status).toBe("error");
+ expect(store().error).toBe("provider unavailable");
+ expect(store().abortController).toBeNull();
+ });
+
it("accumulates token usage across turns", async () => {
h.runTurn.mockImplementation(
impl(async ({ messages }) => ({
diff --git a/apps/web/src/stores/chat-store.ts b/apps/web/src/stores/chat-store.ts
index 65954677..76f1de8f 100644
--- a/apps/web/src/stores/chat-store.ts
+++ b/apps/web/src/stores/chat-store.ts
@@ -4,6 +4,7 @@ import {
toAnthropicTools,
toOpenAITools,
buildSystemPrompt,
+ selectToolsForPrompt,
} from "@openreel/agent";
import type {
AgentEvent,
@@ -15,7 +16,11 @@ import type {
import { isSessionUnlocked, getSecret } from "../services/secure-storage";
import { getLiveEditorHost, runExclusive } from "../services/agent/host-singleton";
import { makeBYOKClient } from "../services/agent/llm-transport";
-import { defaultModelFor, modelsFor } from "../services/agent/models";
+import { normalizeCompatibleBaseUrl } from "../services/api-proxy";
+import {
+ conversationTitle,
+ useChatHistoryStore,
+} from "./chat-history-store";
import { useSettingsStore } from "./settings-store";
import { useProjectStore } from "./project-store";
@@ -36,6 +41,7 @@ export interface ChatMessage {
readonly role: "user" | "assistant";
readonly text: string;
readonly toolCalls: ToolCallView[];
+ readonly notice?: string;
}
interface PendingConfirm {
@@ -58,12 +64,19 @@ interface ChatState {
lastTurnCommitted: boolean;
lastTurnUndoSize: number | null;
usage: TokenUsage;
+ projectId: string | null;
+ currentConversationId: string | null;
+ conversationStartedAt: number | null;
send: (text: string) => Promise<void>;
resolveConfirm: (decision: ConfirmDecision) => void;
stop: () => void;
undoLastTurn: () => Promise<void>;
clearError: () => void;
+ setProjectContext: (projectId: string | null) => void;
+ newChat: () => void;
+ openConversation: (conversationId: string) => void;
+ deleteConversation: (conversationId: string) => void;
reset: () => void;
}
@@ -86,6 +99,36 @@ function undoStackSize(): number | null {
}
}
+function conversationFromMessages(messages: ChatMessage[]): LoopMessage[] {
+ return messages.flatMap((message): LoopMessage[] => {
+ if (!message.text.trim()) return [];
+ return message.role === "user"
+ ? [{ role: "user", content: message.text }]
+ : [{ role: "assistant", content: message.text, toolUses: [] }];
+ });
+}
+
+function saveConversationSnapshot(state: ChatState): void {
+ if (
+ !state.currentConversationId ||
+ !state.projectId ||
+ !state.messages.some((message) => message.role === "user")
+ ) {
+ return;
+ }
+ const now = Date.now();
+ useChatHistoryStore.getState().saveConversation({
+ id: state.currentConversationId,
+ projectId: state.projectId,
+ title: conversationTitle(state.messages),
+ createdAt: state.conversationStartedAt ?? now,
+ updatedAt: now,
+ messages: state.messages,
+ usage: state.usage,
+ error: state.error ?? undefined,
+ });
+}
+
export const useChatStore = create<ChatState>((set, get) => ({
messages: [],
status: "idle",
@@ -96,6 +139,9 @@ export const useChatStore = create<ChatState>((set, get) => ({
lastTurnCommitted: false,
lastTurnUndoSize: null,
usage: { inputTokens: 0, outputTokens: 0 },
+ projectId: null,
+ currentConversationId: null,
+ conversationStartedAt: null,
send: async (text: string) => {
const trimmed = text.trim();
@@ -109,30 +155,52 @@ export const useChatStore = create<ChatState>((set, get) => ({
return;
}
- const provider = useSettingsStore.getState().defaultLlmProvider;
- const storedModel = useSettingsStore.getState().llmModel;
- const model = modelsFor(provider).some((m) => m.id === storedModel)
- ? storedModel
- : defaultModelFor(provider);
+ const projectState = useProjectStore.getState();
+ const currentProjectId = projectState.project?.id ?? null;
+ if (current.projectId && currentProjectId && current.projectId !== currentProjectId) {
+ get().setProjectContext(currentProjectId);
+ }
- if (!isDesktop() && !isSessionUnlocked()) {
- set({ error: "Unlock secure storage to use your API key." });
+ const settings = useSettingsStore.getState();
+ const provider = settings.defaultLlmProvider;
+ if (!provider) {
+ set({ error: "Choose an API format in AI settings." });
return;
}
- let apiKey = "";
- try {
- apiKey = isDesktop() ? "" : ((await getSecret(provider)) ?? "");
- } catch {
- set({ error: "Unlock secure storage to use your API key." });
+ const model = settings.llmModel.trim();
+ if (!model) {
+ set({ error: "Enter or choose a model ID in AI settings." });
return;
}
- if (!isDesktop() && !apiKey) {
- set({
- error: `No ${provider} API key configured. Add it in Settings → API Keys.`,
- });
+ let baseUrl: string;
+ try {
+ baseUrl = normalizeCompatibleBaseUrl(settings.llmBaseUrl);
+ } catch (error) {
+ set({ error: error instanceof Error ? error.message : "Enter a valid compatible endpoint URL." });
return;
}
+ const keyRequired = settings.configuredServices.includes(provider);
+ if (!isDesktop() && keyRequired && !isSessionUnlocked()) {
+ set({ error: "Unlock secure storage to use your API key." });
+ return;
+ }
+ let apiKey = "";
+ if (!isDesktop() && keyRequired) {
+ try {
+ apiKey = (await getSecret(provider)) ?? "";
+ } catch {
+ set({ error: "Unlock secure storage to use your API key." });
+ return;
+ }
+ if (!apiKey) {
+ set({ error: "The configured endpoint API key could not be loaded." });
+ return;
+ }
+ }
+ const active = get();
+ const conversationId = active.currentConversationId ?? genId();
+ const conversationStartedAt = active.conversationStartedAt ?? Date.now();
const userMessage: ChatMessage = {
id: genId(),
role: "user",
@@ -156,6 +224,9 @@ export const useChatStore = create<ChatState>((set, get) => ({
error: null,
abortController: controller,
pendingConfirm: null,
+ projectId: currentProjectId,
+ currentConversationId: conversationId,
+ conversationStartedAt,
}));
const updateAssistant = (fn: (m: ChatMessage) => ChatMessage): void => {
@@ -216,36 +287,94 @@ export const useChatStore = create<ChatState>((set, get) => ({
provider,
model,
apiKey,
+ baseUrl,
signal: controller.signal,
});
+ const priorToolNames = get().conversation.flatMap((message) =>
+ message.role === "assistant" ? message.toolUses.map((tool) => tool.name) : [],
+ );
+ const routingContext = get()
+ .conversation.filter(
+ (message): message is Extract<LoopMessage, { role: "user" }> =>
+ message.role === "user",
+ )
+ .slice(-5)
+ .map((message) => message.content)
+ .join("\n");
+ const selectedToolNames = selectToolsForPrompt(routingContext, {
+ maxTools: 120,
+ priorToolNames,
+ });
const tools =
- provider === "anthropic" ? toAnthropicTools() : toOpenAITools();
+ provider === "anthropic-compatible"
+ ? toAnthropicTools(selectedToolNames)
+ : toOpenAITools(selectedToolNames);
const autoConfirm = useSettingsStore.getState().agentAutoConfirm;
const dryRun = useSettingsStore.getState().agentDryRun;
- const result = await runExclusive(() =>
- runTurn({
- host,
- llm,
- tools,
- system: buildSystemPrompt(host),
- messages: get().conversation,
- dryRun,
- confirmGate: autoConfirm
- ? () => "approve_for_turn"
- : (call) =>
- new Promise<ConfirmDecision>((resolve) => {
- set({ status: "awaiting_confirm", pendingConfirm: { call, resolve } });
- }),
- onEvent,
- turnLabel: "AI edit",
- }),
- );
+ let result;
+ try {
+ result = await runExclusive(() =>
+ runTurn({
+ host,
+ llm,
+ tools,
+ system: buildSystemPrompt(host, selectedToolNames),
+ messages: get().conversation,
+ dryRun,
+ confirmGate: autoConfirm
+ ? () => "approve_for_turn"
+ : (call) =>
+ new Promise<ConfirmDecision>((resolve) => {
+ set({ status: "awaiting_confirm", pendingConfirm: { call, resolve } });
+ }),
+ onEvent,
+ turnLabel: "AI edit",
+ }),
+ );
+ } catch (error) {
+ if (activeSeq !== seq) return;
+ set({
+ status: controller.signal.aborted ? "idle" : "error",
+ error: controller.signal.aborted
+ ? null
+ : error instanceof Error
+ ? error.message
+ : "The AI turn failed.",
+ abortController: null,
+ pendingConfirm: null,
+ });
+ saveConversationSnapshot(get());
+ return;
+ }
// A reset() (or a newer turn) during the run supersedes this completion.
if (activeSeq !== seq) return;
const wasAborted = controller.signal.aborted;
+ const stopNotice =
+ result.stoppedReason === "max_steps"
+ ? "I stopped after reaching this turn's step limit. Ask me to continue if more work is needed."
+ : result.stoppedReason === "max_tool_calls"
+ ? "I stopped after reaching this turn's tool-call limit. Ask me to continue if more work is needed."
+ : result.stoppedReason === "budget"
+ ? "The model stopped at its response or token limit. Ask me to continue, or increase the model's output limit."
+ : undefined;
set((state) => ({
+ messages: state.messages.map((message) => {
+ if (message.id !== assistantId) return message;
+ const finalText = result.text || message.text;
+ const emptyNotice =
+ !finalText && result.stoppedReason === "end_turn"
+ ? message.toolCalls.length > 0
+ ? "The edits finished, but the model did not provide a written summary."
+ : "The model returned an empty response. Try again or choose another model."
+ : undefined;
+ return {
+ ...message,
+ text: finalText,
+ notice: stopNotice ?? emptyNotice,
+ };
+ }),
conversation: result.messages,
status: wasAborted
? "idle"
@@ -266,6 +395,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
? (state.error ?? "The AI turn failed.")
: state.error,
}));
+ saveConversationSnapshot(get());
},
resolveConfirm: (decision: ConfirmDecision) => {
@@ -298,6 +428,97 @@ export const useChatStore = create<ChatState>((set, get) => ({
clearError: () => set({ error: null }),
+ setProjectContext: (projectId: string | null) => {
+ const state = get();
+ if (state.projectId === projectId) return;
+ if (state.projectId !== null && (state.messages.length > 0 || state.conversation.length > 0)) {
+ saveConversationSnapshot(state);
+ }
+ state.pendingConfirm?.resolve("reject");
+ state.abortController?.abort();
+ activeSeq++;
+ set({
+ messages: [],
+ conversation: [],
+ status: "idle",
+ pendingConfirm: null,
+ error: null,
+ abortController: null,
+ lastTurnCommitted: false,
+ lastTurnUndoSize: null,
+ usage: { inputTokens: 0, outputTokens: 0 },
+ projectId,
+ currentConversationId: null,
+ conversationStartedAt: null,
+ });
+ },
+
+ newChat: () => {
+ const state = get();
+ if (state.status === "running" || state.status === "awaiting_confirm") return;
+ saveConversationSnapshot(state);
+ activeSeq++;
+ set({
+ messages: [],
+ conversation: [],
+ status: "idle",
+ pendingConfirm: null,
+ error: null,
+ abortController: null,
+ lastTurnCommitted: false,
+ lastTurnUndoSize: null,
+ usage: { inputTokens: 0, outputTokens: 0 },
+ currentConversationId: null,
+ conversationStartedAt: null,
+ });
+ },
+
+ openConversation: (conversationId: string) => {
+ const state = get();
+ if (state.status === "running" || state.status === "awaiting_confirm") return;
+ const saved = useChatHistoryStore
+ .getState()
+ .conversations.find((item) => item.id === conversationId);
+ if (!saved || (state.projectId && saved.projectId !== state.projectId)) return;
+ if (state.currentConversationId !== conversationId) {
+ saveConversationSnapshot(state);
+ }
+ activeSeq++;
+ set({
+ messages: saved.messages,
+ conversation: conversationFromMessages(saved.messages),
+ status: "idle",
+ pendingConfirm: null,
+ error: saved.error ?? null,
+ abortController: null,
+ lastTurnCommitted: false,
+ lastTurnUndoSize: null,
+ usage: saved.usage,
+ projectId: saved.projectId,
+ currentConversationId: saved.id,
+ conversationStartedAt: saved.createdAt,
+ });
+ },
+
+ deleteConversation: (conversationId: string) => {
+ useChatHistoryStore.getState().deleteConversation(conversationId);
+ if (get().currentConversationId !== conversationId) return;
+ activeSeq++;
+ set({
+ messages: [],
+ conversation: [],
+ status: "idle",
+ pendingConfirm: null,
+ error: null,
+ abortController: null,
+ lastTurnCommitted: false,
+ lastTurnUndoSize: null,
+ usage: { inputTokens: 0, outputTokens: 0 },
+ currentConversationId: null,
+ conversationStartedAt: null,
+ });
+ },
+
reset: () => {
get().pendingConfirm?.resolve("reject");
get().abortController?.abort();
@@ -313,6 +534,9 @@ export const useChatStore = create<ChatState>((set, get) => ({
lastTurnCommitted: false,
lastTurnUndoSize: null,
usage: { inputTokens: 0, outputTokens: 0 },
+ projectId: null,
+ currentConversationId: null,
+ conversationStartedAt: null,
});
},
}));
diff --git a/apps/web/src/stores/gpu-job-store.test.ts b/apps/web/src/stores/gpu-job-store.test.ts
deleted file mode 100644
index 761d4ea7..00000000
--- a/apps/web/src/stores/gpu-job-store.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, it, expect, beforeEach } from "vitest";
-import { useGpuJobStore } from "./gpu-job-store";
-
-beforeEach(() => {
- useGpuJobStore.setState({ jobs: [] });
-});
-
-describe("gpu-job-store", () => {
- it("adds and lists jobs for a project", () => {
- useGpuJobStore.getState().addJob({ jobID: "j1", mediaId: "m1", projectId: "p1", kind: "upscale", suggestedName: "Upscaled" });
- useGpuJobStore.getState().addJob({ jobID: "j2", mediaId: "m2", projectId: "p2", kind: "denoise", suggestedName: "Denoised" });
- const p1 = useGpuJobStore.getState().getJobsForProject("p1");
- expect(p1.map((j) => j.jobID)).toEqual(["j1"]);
- expect(p1[0].retries).toBe(0);
- expect(p1[0].failed).toBe(false);
- });
- it("increments retries and marks failed", () => {
- useGpuJobStore.getState().addJob({ jobID: "j1", mediaId: "m1", projectId: "p1", kind: "upscale", suggestedName: "x" });
- useGpuJobStore.getState().incrementRetry("j1");
- expect(useGpuJobStore.getState().jobs[0].retries).toBe(1);
- useGpuJobStore.getState().markFailed("j1");
- expect(useGpuJobStore.getState().jobs[0].failed).toBe(true);
- useGpuJobStore.getState().retryJob("j1");
- expect(useGpuJobStore.getState().jobs[0].failed).toBe(false);
- expect(useGpuJobStore.getState().jobs[0].retries).toBe(0);
- });
- it("resets retries to zero without clearing failed", () => {
- useGpuJobStore.getState().addJob({ jobID: "j1", mediaId: "m1", projectId: "p1", kind: "upscale", suggestedName: "x" });
- useGpuJobStore.getState().incrementRetry("j1");
- useGpuJobStore.getState().incrementRetry("j1");
- useGpuJobStore.getState().markFailed("j1");
- useGpuJobStore.getState().resetRetries("j1");
- expect(useGpuJobStore.getState().jobs[0].retries).toBe(0);
- expect(useGpuJobStore.getState().jobs[0].failed).toBe(true);
- });
- it("removes jobs", () => {
- useGpuJobStore.getState().addJob({ jobID: "j1", mediaId: "m1", projectId: "p1", kind: "upscale", suggestedName: "x" });
- useGpuJobStore.getState().removeJob("j1");
- expect(useGpuJobStore.getState().jobs).toHaveLength(0);
- });
-});
diff --git a/apps/web/src/stores/gpu-job-store.ts b/apps/web/src/stores/gpu-job-store.ts
deleted file mode 100644
index a3d3247d..00000000
--- a/apps/web/src/stores/gpu-job-store.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { create } from "zustand";
-import { persist } from "zustand/middleware";
-
-export interface PendingGpuJob {
- jobID: string;
- mediaId: string;
- projectId: string;
- kind: string;
- suggestedName: string;
- sourceClipId?: string;
- createdAt: number;
- retries: number;
- failed: boolean;
-}
-
-interface GpuJobState {
- jobs: PendingGpuJob[];
- addJob: (
- job: Omit<PendingGpuJob, "retries" | "failed" | "createdAt"> & {
- createdAt?: number;
- },
- ) => void;
- removeJob: (jobID: string) => void;
- incrementRetry: (jobID: string) => void;
- resetRetries: (jobID: string) => void;
- markFailed: (jobID: string) => void;
- retryJob: (jobID: string) => void;
- getJobsForProject: (projectId: string) => PendingGpuJob[];
-}
-
-export const useGpuJobStore = create<GpuJobState>()(
- persist(
- (set, get) => ({
- jobs: [],
-
- addJob: (job) =>
- set((s) => ({
- jobs: [
- ...s.jobs,
- {
- ...job,
- createdAt: job.createdAt ?? Date.now(),
- retries: 0,
- failed: false,
- },
- ],
- })),
-
- removeJob: (jobID) =>
- set((s) => ({ jobs: s.jobs.filter((j) => j.jobID !== jobID) })),
-
- incrementRetry: (jobID) =>
- set((s) => ({
- jobs: s.jobs.map((j) =>
- j.jobID === jobID ? { ...j, retries: j.retries + 1 } : j,
- ),
- })),
-
- resetRetries: (jobID) =>
- set((s) => ({
- jobs: s.jobs.map((j) =>
- j.jobID === jobID ? { ...j, retries: 0 } : j,
- ),
- })),
-
- markFailed: (jobID) =>
- set((s) => ({
- jobs: s.jobs.map((j) =>
- j.jobID === jobID ? { ...j, failed: true } : j,
- ),
- })),
-
- retryJob: (jobID) =>
- set((s) => ({
- jobs: s.jobs.map((j) =>
- j.jobID === jobID ? { ...j, retries: 0, failed: false } : j,
- ),
- })),
-
- getJobsForProject: (projectId) =>
- get().jobs.filter((j) => j.projectId === projectId),
- }),
- { name: "gpu-pending-jobs" },
- ),
-);
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index 670bb986..19dd0501 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -833,6 +833,169 @@ describe("ProjectStore", () => {
});
});
+ describe("universal timeline placement", () => {
+ const mixedPlacementProject = (): Project =>
+ ({
+ id: "mixed-placement",
+ name: "Mixed placement",
+ createdAt: 0,
+ modifiedAt: 0,
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48_000,
+ channels: 2,
+ },
+ mediaLibrary: {
+ items: [
+ {
+ id: "video-media",
+ name: "Video",
+ type: "video",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 5,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ {
+ id: "image-media",
+ name: "Image",
+ type: "image",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 0,
+ width: 1280,
+ height: 720,
+ frameRate: 0,
+ codec: "png",
+ sampleRate: 0,
+ channels: 0,
+ fileSize: 1,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ ],
+ },
+ timeline: {
+ duration: 5,
+ subtitles: [],
+ markers: [],
+ tracks: [
+ {
+ id: "target",
+ type: "video",
+ name: "Track 1",
+ clips: [
+ {
+ id: "existing",
+ mediaId: "video-media",
+ trackId: "target",
+ startTime: 0,
+ duration: 5,
+ inPoint: 0,
+ outPoint: 5,
+ effects: [],
+ audioEffects: [],
+ keyframes: [],
+ transform: {},
+ volume: 1,
+ },
+ ],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ },
+ }) as unknown as Project;
+
+ it("auto-stacks an occupied drop and undoes the clip and row together", async () => {
+ useProjectStore.getState().loadProject(mixedPlacementProject());
+
+ const result = await useProjectStore
+ .getState()
+ .placeMediaClip("image-media", "target", 1);
+
+ expect(result.success).toBe(true);
+ let project = useProjectStore.getState().project;
+ expect(project.timeline.tracks).toHaveLength(2);
+ expect(project.timeline.tracks[0].mode).toBe("standard");
+ expect(project.timeline.tracks[0].clips[0]?.mediaId).toBe("image-media");
+ expect(project.capabilities).toContain("universal-tracks-v1");
+
+ await useProjectStore.getState().undo();
+ project = useProjectStore.getState().project;
+ expect(project.timeline.tracks).toHaveLength(1);
+ expect(project.timeline.tracks[0].id).toBe("target");
+ expect(project.timeline.tracks[0].clips.map((clip) => clip.id)).toEqual([
+ "existing",
+ ]);
+ });
+
+ it("moves a text item onto any unlocked row and restores it on undo", async () => {
+ const project = {
+ ...mixedPlacementProject(),
+ timeline: {
+ ...mixedPlacementProject().timeline,
+ tracks: [
+ ...mixedPlacementProject().timeline.tracks,
+ {
+ id: "destination",
+ type: "audio" as const,
+ name: "Destination",
+ clips: [],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ },
+ textClips: [
+ {
+ id: "title",
+ trackId: "target",
+ startTime: 0,
+ duration: 1,
+ text: "Title",
+ },
+ ],
+ } as unknown as Project;
+ useProjectStore.getState().loadProject(project);
+
+ const result = await useProjectStore
+ .getState()
+ .moveTimelineItem("title", 2, "destination");
+ expect(result.success).toBe(true);
+ expect(useProjectStore.getState().project.textClips?.[0]).toMatchObject({
+ trackId: "destination",
+ startTime: 2,
+ });
+
+ await useProjectStore.getState().undo();
+ expect(useProjectStore.getState().project.textClips?.[0]).toMatchObject({
+ trackId: "target",
+ startTime: 0,
+ });
+ });
+ });
+
describe("video effects", () => {
const createProjectWithVideoClip = (): Project => ({
id: "effects-project",
@@ -1765,14 +1928,29 @@ describe("ProjectStore", () => {
startTime: 10,
trackId: textTrack.id,
});
- expect(useProjectStore.getState().getShapeClip(pastedIds[1])).toMatchObject({
+ const pastedShape = useProjectStore
+ .getState()
+ .getShapeClip(pastedIds[1]);
+ expect(pastedShape).toMatchObject({
startTime: 12,
- trackId: graphicsTrack.id,
});
+ expect(pastedShape?.trackId).not.toBe(textTrack.id);
+ const stackedTrack = useProjectStore
+ .getState()
+ .project.timeline.tracks.find((track) => track.id === pastedShape?.trackId);
+ expect(stackedTrack?.mode).toBe("standard");
+ expect(
+ useProjectStore.getState().project.timeline.tracks.indexOf(stackedTrack!),
+ ).toBeLessThan(
+ useProjectStore.getState().project.timeline.tracks.findIndex(
+ (track) => track.id === textTrack.id,
+ ),
+ );
await useProjectStore.getState().undo();
expect(useProjectStore.getState().project.textClips).toHaveLength(1);
expect(useProjectStore.getState().project.shapeClips).toHaveLength(1);
+ expect(useProjectStore.getState().project.timeline.tracks).toHaveLength(2);
});
});
@@ -1866,6 +2044,44 @@ describe("ProjectStore", () => {
expect(audioTracks[0].clips[0].mediaId).toBe("video-media-1");
});
+ it("should preserve the video clip source range in separated audio", async () => {
+ const project = createProjectWithVideoClip(1);
+ const videoTrack = project.timeline.tracks[0];
+ const trimmedVideoClip = {
+ ...videoTrack.clips[0],
+ startTime: 4,
+ duration: 3,
+ inPoint: 2,
+ outPoint: 5,
+ speed: 1.5,
+ reversed: true,
+ };
+ const trimmedProject = {
+ ...project,
+ timeline: {
+ ...project.timeline,
+ tracks: [{ ...videoTrack, clips: [trimmedVideoClip] }],
+ },
+ };
+
+ useProjectStore.getState().loadProject(trimmedProject);
+ const result = await useProjectStore.getState().separateAudio("video-clip-1");
+
+ expect(result.success).toBe(true);
+ const audioClip = useProjectStore
+ .getState()
+ .project.timeline.tracks.find((track) => track.type === "audio")
+ ?.clips[0];
+ expect(audioClip).toMatchObject({
+ startTime: 4,
+ duration: 3,
+ inPoint: 2,
+ outPoint: 5,
+ speed: 1.5,
+ reversed: true,
+ });
+ });
+
it("should create multiple audio clips when media has multiple audio tracks", async () => {
useProjectStore.getState().loadProject(createProjectWithVideoClip(3));
const result = await useProjectStore.getState().separateAudio("video-clip-1");
@@ -2040,7 +2256,7 @@ Second caption`;
const state = useProjectStore.getState();
const captionsTrack = state.project.timeline.tracks.find(
- (track) => track.type === "text" && track.name === "Captions",
+ (track) => track.role === "captions" && track.name === "Captions",
);
expect(captionsTrack).toBeDefined();
@@ -2074,7 +2290,7 @@ Ignored block`;
const state = useProjectStore.getState();
const captionsTrack = state.project.timeline.tracks.find(
- (track) => track.type === "text" && track.name === "Captions",
+ (track) => track.role === "captions" && track.name === "Captions",
);
const captionClips = state
.getAllTextClips()
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 8de9a411..2d5dc59d 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -41,12 +41,15 @@ import {
getBuiltInEditingTemplate,
getBuiltInEditingTemplates,
getMotionPreset,
+ getTrackItems,
motionEngine,
normalizeGeneratedShaders,
normalizeProjectMotionFields,
reflowMotionAutoLayoutGroups,
registerProjectGeneratedShaders,
+ resolveTimelinePlacement,
resolveEditingTemplate,
+ withUniversalTracksCapability,
} from "@openreel/core";
import { createMarkerSlice } from "./project/marker-slice";
import { createSubtitleSlice } from "./project/subtitle-slice";
@@ -56,6 +59,7 @@ import { createProjectStoreHelpers } from "./project/store-helpers";
import { createTextGraphicsSlice } from "./project/text-graphics-slice";
import { createHistorySlice } from "./project/history-slice";
import { createClipSlice } from "./project/clip-slice";
+import { createTimelineItemSlice } from "./project/timeline-item-slice";
import { v4 as uuidv4 } from "uuid";
import type {
VideoEffect,
@@ -85,7 +89,10 @@ import {
loadFileHandle,
loadDirectoryHandle,
} from "../services/media-storage";
-import { restoreMediaItem } from "../utils/media-recovery";
+import {
+ createMissingMediaItem,
+ restoreMediaItem,
+} from "../utils/media-recovery";
import { projectManager } from "../services/project-manager";
import {
planCreationObjectEdit,
@@ -165,6 +172,12 @@ export interface ProjectState {
addTrack: (
trackType: "video" | "audio" | "image" | "text" | "graphics",
position?: number,
+ options?: {
+ mode?: "standard";
+ role?: Track["role"];
+ name?: string;
+ trackId?: string;
+ },
) => Promise<ActionResult>;
duplicateTrack: (trackId: string) => Promise<ActionResult>;
removeTrack: (trackId: string) => Promise<ActionResult>;
@@ -187,6 +200,16 @@ export interface ProjectState {
mediaId: string,
startTime?: number,
) => Promise<ActionResult>;
+ placeMediaClip: (
+ mediaId: string,
+ targetTrackId: string | undefined,
+ startTime: number,
+ ) => Promise<ActionResult>;
+ moveTimelineItem: (
+ itemId: string,
+ startTime: number,
+ targetTrackId?: string,
+ ) => Promise<ActionResult>;
removeClip: (clipId: string) => Promise<ActionResult>;
moveClip: (
clipId: string,
@@ -936,34 +959,7 @@ export const useProjectStore = create<ProjectState>()(
};
const trackHasAnyClips = (project: Project, trackId: string): boolean => {
- const track = project.timeline.tracks.find((candidate) => candidate.id === trackId);
- if (!track) {
- return false;
- }
-
- if (track.clips.length > 0) {
- return true;
- }
-
- if (track.type === "text") {
- const titleEngine = useEngineStore.getState().getTitleEngine();
- return titleEngine?.getAllTextClips().some((clip) => clip.trackId === trackId) ?? false;
- }
-
- if (track.type === "graphics") {
- const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
- if (!graphicsEngine) {
- return false;
- }
-
- return [
- ...graphicsEngine.getAllShapeClips(),
- ...graphicsEngine.getAllSVGClips(),
- ...graphicsEngine.getAllStickerClips(),
- ].some((clip) => clip.trackId === trackId);
- }
-
- return false;
+ return getTrackItems(project, trackId).length > 0;
};
const buildEditingTemplateKeyframes = (
@@ -1080,10 +1076,13 @@ export const useProjectStore = create<ProjectState>()(
return null;
}
+ const mediaItem = project.mediaLibrary.items.find(
+ (item) => item.id === ownerClip.mediaId,
+ );
const targetType =
- track.type === "image"
+ mediaItem?.type === "image"
? "image"
- : track.type === "video"
+ : mediaItem?.type === "video"
? "video"
: null;
@@ -1114,9 +1113,6 @@ export const useProjectStore = create<ProjectState>()(
return null;
}
- const mediaItem = project.mediaLibrary.items.find(
- (item) => item.id === ownerClip.mediaId,
- );
const assetUrls = project.mediaLibrary.items.reduce<Record<string, string>>(
(urls, item) => {
const url = item.originalUrl ?? item.thumbnailUrl ?? undefined;
@@ -2013,6 +2009,7 @@ export const useProjectStore = create<ProjectState>()(
// Clip actions
...createClipSlice(set, get),
+ ...createTimelineItemSlice(set, get, helpers),
addClipTransition: async (transition: Transition) => {
const { project, actionExecutor } = get();
@@ -2195,23 +2192,12 @@ export const useProjectStore = create<ProjectState>()(
const sourceTrack = currentProject.timeline.tracks.find(
(track) => track.id === item.clip.trackId,
);
- const expectedTrackType =
- item.kind === "text"
- ? "text"
- : item.kind === "media"
- ? sourceTrack?.type
- : "graphics";
- const isCompatible = (track: Track) =>
- !track.locked &&
- (!expectedTrackType || track.type === expectedTrackType);
const destinationTrack =
- (sourceTrack && isCompatible(sourceTrack)
- ? sourceTrack
- : undefined) ??
currentProject.timeline.tracks.find(
- (track) => track.id === trackId && isCompatible(track),
+ (track) => track.id === trackId && !track.locked,
) ??
- currentProject.timeline.tracks.find(isCompatible);
+ (sourceTrack && !sourceTrack.locked ? sourceTrack : undefined) ??
+ currentProject.timeline.tracks.find((track) => !track.locked);
if (!destinationTrack) {
results.push({
@@ -2224,12 +2210,56 @@ export const useProjectStore = create<ProjectState>()(
continue;
}
+ const newTrackId = uuidv4();
+ const placement = resolveTimelinePlacement(currentProject, {
+ targetTrackId: destinationTrack.id,
+ startTime: newStartTime,
+ duration: item.clip.duration,
+ policy: "stack-above",
+ newTrackId,
+ });
+ if (!placement.ok) {
+ results.push({
+ success: false,
+ error: {
+ code:
+ placement.reason === "track-locked"
+ ? "TRACK_LOCKED"
+ : placement.reason === "track-not-found"
+ ? "TRACK_NOT_FOUND"
+ : "OVERLAP_DETECTED",
+ message: `Could not place ${item.kind} clip`,
+ },
+ });
+ continue;
+ }
+ if (placement.createdTrack) {
+ const trackResult = await actionExecutor.execute(
+ {
+ type: "track/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ trackType: "video",
+ trackId: placement.createdTrack.id,
+ position: placement.createdTrack.position,
+ mode: "standard",
+ },
+ },
+ currentProject,
+ );
+ if (!trackResult.success) {
+ results.push(trackResult);
+ continue;
+ }
+ }
+
if (item.kind !== "media") {
const pasted = get().pasteOverlayClip(
item.kind,
item.clip,
- newStartTime,
- destinationTrack.id,
+ placement.startTime,
+ placement.trackId,
);
if (pasted) {
results.push({ success: true });
@@ -2246,24 +2276,26 @@ export const useProjectStore = create<ProjectState>()(
continue;
}
- const beforeIds = new Set(
- destinationTrack.clips.map((clip) => clip.id),
+ const placedTrack = currentProject.timeline.tracks.find(
+ (track) => track.id === placement.trackId,
);
+ const beforeIds = new Set(placedTrack?.clips.map((clip) => clip.id));
const action: Action = {
type: "clip/add",
id: uuidv4(),
timestamp: Date.now(),
params: {
- trackId: destinationTrack.id,
+ clipId: uuidv4(),
+ trackId: placement.trackId,
mediaId: item.clip.mediaId,
- startTime: newStartTime,
+ startTime: placement.startTime,
sourceClip: item.clip,
},
};
const result = await actionExecutor.execute(action, currentProject);
results.push(result);
if (result.success) {
- const pasted = destinationTrack.clips.find(
+ const pasted = placedTrack?.clips.find(
(clip) => !beforeIds.has(clip.id),
);
if (pasted) pastedIds.push(pasted.id);
@@ -2274,7 +2306,10 @@ export const useProjectStore = create<ProjectState>()(
}
set({
- project: { ...get().project, modifiedAt: Date.now() },
+ project: withUniversalTracksCapability({
+ ...get().project,
+ modifiedAt: Date.now(),
+ }),
lastPastedClipIds: pastedIds,
});
return results;
@@ -2956,9 +2991,17 @@ export const useProjectStore = create<ProjectState>()(
const blobMap = new Map(storedMedia.map((m) => [m.id, m.blob]));
const restoredItems = await Promise.all(
- recoveredProject.mediaLibrary.items.map((item) =>
- restoreMediaItem(item, blobMap.get(item.id)),
- ),
+ recoveredProject.mediaLibrary.items.map(async (item) => {
+ try {
+ return await restoreMediaItem(item, blobMap.get(item.id));
+ } catch (error) {
+ console.warn(
+ `[ProjectStore] Failed to restore media ${item.name}; marking it missing:`,
+ error,
+ );
+ return createMissingMediaItem(item);
+ }
+ }),
);
const projectWithMedia: Project = {
diff --git a/apps/web/src/stores/project/clip-slice.ts b/apps/web/src/stores/project/clip-slice.ts
index 8b6caa93..c12ffe94 100644
--- a/apps/web/src/stores/project/clip-slice.ts
+++ b/apps/web/src/stores/project/clip-slice.ts
@@ -196,6 +196,11 @@ export function createClipSlice(set: Set, get: Get): ClipSlice {
trackId: targetTrack.id,
mediaId: videoClip.mediaId,
startTime: videoClip.startTime,
+ duration: videoClip.duration,
+ inPoint: videoClip.inPoint,
+ outPoint: videoClip.outPoint,
+ speed: videoClip.speed,
+ reversed: videoClip.reversed,
audioTrackIndex: trackIdx,
},
};
diff --git a/apps/web/src/stores/project/history-slice.ts b/apps/web/src/stores/project/history-slice.ts
index a7bc2a28..73a8d46c 100644
--- a/apps/web/src/stores/project/history-slice.ts
+++ b/apps/web/src/stores/project/history-slice.ts
@@ -6,6 +6,7 @@ import type {
SVGClip,
StickerClip,
} from "@openreel/core";
+import { getTrackItems } from "@openreel/core";
import type { ProjectState } from "../project-store";
import type { ProjectStoreHelpers } from "./store-helpers";
import type {
@@ -197,23 +198,7 @@ export function createHistorySlice(
);
if (track) {
- let trackHasClips = false;
- if (track.type === "text") {
- const textClips =
- useEngineStore.getState().getTitleEngine()?.getAllTextClips() ||
- [];
- trackHasClips = textClips.some((c) => c.trackId === trackId);
- } else if (track.type === "graphics") {
- const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
- const shapeClips = graphicsEngine?.getAllShapeClips() || [];
- const svgClips = graphicsEngine?.getAllSVGClips() || [];
- const stickerClips = graphicsEngine?.getAllStickerClips() || [];
- trackHasClips = [...shapeClips, ...svgClips, ...stickerClips].some(
- (c) => c.trackId === trackId,
- );
- } else {
- trackHasClips = track.clips.length > 0;
- }
+ const trackHasClips = getTrackItems(get().project, trackId).length > 0;
if (!trackHasClips) {
const lastEntry = get().actionHistory.peekUndo();
@@ -230,11 +215,15 @@ export function createHistorySlice(
const actionTrackType = lastAction?.params?.trackType as
| string
| undefined;
+ const actionTrackId = lastAction?.params?.trackId as
+ | string
+ | undefined;
if (
lastAction &&
lastAction.type === "track/add" &&
- actionTrackType === expectedTrackType
+ (actionTrackId === trackId ||
+ (!actionTrackId && actionTrackType === expectedTrackType))
) {
const trackUndoResult = await actionExecutor.undo(get().project);
if (trackUndoResult.success) {
diff --git a/apps/web/src/stores/project/insert-timeline-overlay.ts b/apps/web/src/stores/project/insert-timeline-overlay.ts
new file mode 100644
index 00000000..5f5d0f9d
--- /dev/null
+++ b/apps/web/src/stores/project/insert-timeline-overlay.ts
@@ -0,0 +1,64 @@
+import { v4 as uuidv4 } from "uuid";
+import { resolveTimelinePlacement } from "@openreel/core";
+import { useProjectStore } from "../project-store";
+
+/**
+ * Put a newly-authored visual item on an available timeline row. Occupied
+ * rows stack above automatically and track creation stays in the same history
+ * transaction as the item creation.
+ */
+export async function insertTimelineOverlay<T>(
+ startTime: number,
+ duration: number,
+ create: (trackId: string) => T | null,
+ preferredTrackId?: string,
+): Promise<T | null> {
+ const initialState = useProjectStore.getState();
+ const initialProject = initialState.project;
+ const preferredTrack = preferredTrackId
+ ? initialProject.timeline.tracks.find(
+ (track) => track.id === preferredTrackId,
+ )
+ : undefined;
+ if (preferredTrackId && (!preferredTrack || preferredTrack.locked)) {
+ return null;
+ }
+ const targetTrack =
+ preferredTrack ??
+ initialProject.timeline.tracks.find((track) => !track.locked);
+ const newTrackId = `track-${uuidv4()}`;
+ const placement = targetTrack
+ ? resolveTimelinePlacement(initialProject, {
+ targetTrackId: targetTrack.id,
+ startTime,
+ duration,
+ policy: "stack-above",
+ newTrackId,
+ })
+ : {
+ ok: true as const,
+ trackId: newTrackId,
+ startTime: Math.max(0, startTime),
+ createdTrack: { id: newTrackId, position: 0 },
+ };
+
+ if (!placement.ok) return null;
+
+ initialState.beginHistoryGroup("Place timeline item");
+ try {
+ if (placement.createdTrack) {
+ const result = await useProjectStore.getState().addTrack(
+ "video",
+ placement.createdTrack.position,
+ {
+ mode: "standard",
+ trackId: placement.createdTrack.id,
+ },
+ );
+ if (!result.success) return null;
+ }
+ return create(placement.trackId);
+ } finally {
+ useProjectStore.getState().endHistoryGroup();
+ }
+}
diff --git a/apps/web/src/stores/project/media-slice.ts b/apps/web/src/stores/project/media-slice.ts
index 794b8e0e..683cac34 100644
--- a/apps/web/src/stores/project/media-slice.ts
+++ b/apps/web/src/stores/project/media-slice.ts
@@ -124,6 +124,8 @@ export function createMediaSlice(set: Set, get: Get): MediaSlice {
sampleRate: processedMedia.metadata.sampleRate || 0,
channels: processedMedia.metadata.channels || 0,
fileSize: file.size,
+ hasVideo: processedMedia.metadata.hasVideo,
+ hasAudio: processedMedia.metadata.hasAudio,
},
thumbnailUrl,
waveformData: processedMedia.waveformData?.peaks || null,
@@ -332,6 +334,8 @@ export function createMediaSlice(set: Set, get: Get): MediaSlice {
sampleRate: processedMedia.metadata.sampleRate || 0,
channels: processedMedia.metadata.channels || 0,
fileSize: file.size,
+ hasVideo: processedMedia.metadata.hasVideo,
+ hasAudio: processedMedia.metadata.hasAudio,
},
thumbnailUrl,
waveformData: processedMedia.waveformData?.peaks || null,
diff --git a/apps/web/src/stores/project/store-helpers.ts b/apps/web/src/stores/project/store-helpers.ts
index a46edfb0..9a9f7e6c 100644
--- a/apps/web/src/stores/project/store-helpers.ts
+++ b/apps/web/src/stores/project/store-helpers.ts
@@ -14,6 +14,7 @@ import {
getAdjustmentLayerEngine,
multicamEngine,
getNestedSequenceEngine,
+ withUniversalTracksCapability,
} from "@openreel/core";
import type { ProjectState } from "../project-store";
import type { ClipHistoryEntryType } from "./index";
@@ -34,7 +35,7 @@ export interface ProjectStoreHelpers {
recordOverlayCreate(
prefix: string,
field: OverlayField,
- clip: { id: string },
+ clip: { id: string; trackId: string },
): void;
recordOverlayUpdate(
prefix: string,
@@ -97,7 +98,7 @@ export function createProjectStoreHelpers(
const recordOverlayCreate = (
prefix: string,
field: OverlayField,
- clip: { id: string },
+ clip: { id: string; trackId: string },
): void => {
const { project, actionExecutor } = get();
const actionId = uuidv4();
@@ -114,11 +115,19 @@ export function createProjectStoreHelpers(
timestamp: Date.now(),
params: { clipId: clip.id },
};
- const nextProject = {
+ const rawNextProject = {
...project,
[field]: [...overlayList(project, field), snap],
modifiedAt: Date.now(),
} as Project;
+ const ownerTrack = project.timeline.tracks.find(
+ (track) => track.id === clip.trackId,
+ );
+ const expectedTrackType = prefix === "text" ? "text" : "graphics";
+ const nextProject =
+ ownerTrack?.mode === "standard" || ownerTrack?.type !== expectedTrackType
+ ? withUniversalTracksCapability(rawNextProject)
+ : rawNextProject;
set({
project: {
...nextProject,
diff --git a/apps/web/src/stores/project/subtitle-slice.ts b/apps/web/src/stores/project/subtitle-slice.ts
index c572256d..cba38d05 100644
--- a/apps/web/src/stores/project/subtitle-slice.ts
+++ b/apps/web/src/stores/project/subtitle-slice.ts
@@ -19,41 +19,32 @@ export type SubtitleSlice = Pick<
| "getSubtitleStylePresets"
>;
-export function createSubtitleSlice(set: Set, get: Get): SubtitleSlice {
+export function createSubtitleSlice(_set: Set, get: Get): SubtitleSlice {
return {
addSubtitle: async (subtitle, metadata) => {
const { project, addTrack, createTextClip } = get();
let captionsTrack = project.timeline.tracks.find(
- (t) => t.type === "text" && t.name === "Captions",
+ (track) =>
+ track.role === "captions" || track.name === "Captions",
);
if (!captionsTrack) {
- const result = await addTrack("text");
+ const existingTrackIds = new Set(
+ project.timeline.tracks.map((track) => track.id),
+ );
+ const result = await addTrack("video", undefined, {
+ mode: "standard",
+ role: "captions",
+ name: "Captions",
+ });
if (!result?.success) return;
const updatedProject = get().project;
- const newTracks = updatedProject.timeline.tracks.filter(
- (t) =>
- t.type === "text" &&
- !project.timeline.tracks.some((old) => old.id === t.id),
+ captionsTrack = updatedProject.timeline.tracks.find(
+ (track) =>
+ track.role === "captions" && !existingTrackIds.has(track.id),
);
- captionsTrack = newTracks[0];
-
- if (captionsTrack) {
- set((state) => ({
- project: {
- ...state.project,
- timeline: {
- ...state.project.timeline,
- tracks: state.project.timeline.tracks.map((t) =>
- t.id === captionsTrack!.id ? { ...t, name: "Captions" } : t,
- ),
- },
- },
- }));
- captionsTrack = { ...captionsTrack, name: "Captions" };
- }
}
if (!captionsTrack) return;
@@ -170,7 +161,10 @@ export function createSubtitleSlice(set: Set, get: Get): SubtitleSlice {
const { project } = get();
const captionsTrackIds = new Set(
project.timeline.tracks
- .filter((track) => track.type === "text" && track.name === "Captions")
+ .filter(
+ (track) =>
+ track.role === "captions" || track.name === "Captions",
+ )
.map((track) => track.id),
);
const subtitles = get()
@@ -208,7 +202,10 @@ export function createSubtitleSlice(set: Set, get: Get): SubtitleSlice {
}
const captionsTrackIds = new Set(
get().project.timeline.tracks
- .filter((track) => track.type === "text" && track.name === "Captions")
+ .filter(
+ (track) =>
+ track.role === "captions" || track.name === "Captions",
+ )
.map((track) => track.id),
);
for (const clip of get().getAllTextClips()) {
diff --git a/apps/web/src/stores/project/text-graphics-slice.ts b/apps/web/src/stores/project/text-graphics-slice.ts
index 93fdc395..90c61884 100644
--- a/apps/web/src/stores/project/text-graphics-slice.ts
+++ b/apps/web/src/stores/project/text-graphics-slice.ts
@@ -536,16 +536,13 @@ export function createTextGraphicsSlice(
const destinationTrack = get().project.timeline.tracks.find(
(track) => track.id === destinationTrackId,
);
- const expectedTrackType = kind === "text" ? "text" : "graphics";
if (
!destinationTrack ||
- destinationTrack.locked ||
- destinationTrack.type !== expectedTrackType
+ destinationTrack.locked
) {
console.warn("[ProjectStore] Cannot paste overlay to destination track", {
kind,
destinationTrackId,
- destinationTrackType: destinationTrack?.type,
destinationTrackLocked: destinationTrack?.locked,
});
return null;
diff --git a/apps/web/src/stores/project/timeline-item-slice.ts b/apps/web/src/stores/project/timeline-item-slice.ts
new file mode 100644
index 00000000..c3c2877b
--- /dev/null
+++ b/apps/web/src/stores/project/timeline-item-slice.ts
@@ -0,0 +1,207 @@
+import { v4 as uuidv4 } from "uuid";
+import type { StoreApi } from "zustand";
+import type { Action, ActionResult } from "@openreel/core";
+import {
+ resolveTimelineItem,
+ resolveTimelinePlacement,
+ withUniversalTracksCapability,
+} from "@openreel/core";
+import type { ProjectState } from "../project-store";
+import type { ProjectStoreHelpers } from "./store-helpers";
+
+type Get = StoreApi<ProjectState>["getState"];
+type Set = StoreApi<ProjectState>["setState"];
+
+export type TimelineItemSlice = Pick<
+ ProjectState,
+ "placeMediaClip" | "moveTimelineItem"
+>;
+
+const failure = (
+ code: "INVALID_PARAMS" | "TRACK_NOT_FOUND" | "TRACK_LOCKED" | "OVERLAP_DETECTED",
+ message: string,
+): ActionResult => ({ success: false, error: { code, message } });
+
+export function createTimelineItemSlice(
+ set: Set,
+ get: Get,
+ helpers: ProjectStoreHelpers,
+): TimelineItemSlice {
+ const executePlacement = async (
+ actions: Action[],
+ description: string,
+ ): Promise<ActionResult> => {
+ const { project, actionExecutor } = get();
+ const projectCopy = structuredClone(project);
+ const history = actionExecutor.getHistory();
+ history.beginGroup(description);
+ let results: ActionResult[] = [];
+ try {
+ results = await actionExecutor.executeMany(actions, projectCopy);
+ } finally {
+ history.endGroup();
+ }
+ const failed = results.find((result) => !result.success);
+ if (failed) return failed;
+
+ const nextProject = withUniversalTracksCapability({
+ ...projectCopy,
+ modifiedAt: Date.now(),
+ });
+ set({ project: nextProject });
+ helpers.syncOverlayEnginesFromProject();
+ return results.at(-1) ?? { success: true };
+ };
+
+ return {
+ placeMediaClip: async (mediaId, targetTrackId, startTime) => {
+ const { project } = get();
+ const mediaItem = project.mediaLibrary.items.find(
+ (item) => item.id === mediaId,
+ );
+ if (!mediaItem) return failure("INVALID_PARAMS", "Media item not found");
+
+ const duration =
+ mediaItem.metadata.duration > 0 ? mediaItem.metadata.duration : 5;
+ const newTrackId = uuidv4();
+ const placement = targetTrackId
+ ? resolveTimelinePlacement(project, {
+ targetTrackId,
+ startTime,
+ duration,
+ policy: "stack-above",
+ newTrackId,
+ })
+ : {
+ ok: true as const,
+ trackId: newTrackId,
+ startTime: Math.max(0, startTime),
+ createdTrack: {
+ id: newTrackId,
+ position: project.timeline.tracks.length,
+ },
+ };
+
+ if (!placement.ok) {
+ if (placement.reason === "track-not-found") {
+ return failure("TRACK_NOT_FOUND", "Destination track not found");
+ }
+ if (placement.reason === "track-locked") {
+ return failure("TRACK_LOCKED", "Destination track is locked");
+ }
+ return failure("OVERLAP_DETECTED", "The destination interval is occupied");
+ }
+
+ const actions: Action[] = [];
+ if (placement.createdTrack) {
+ actions.push({
+ type: "track/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ trackType: "video",
+ trackId: placement.createdTrack.id,
+ position: placement.createdTrack.position,
+ mode: "standard",
+ },
+ });
+ }
+ actions.push({
+ type: "clip/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ clipId: uuidv4(),
+ trackId: placement.trackId,
+ mediaId,
+ startTime: placement.startTime,
+ duration,
+ },
+ });
+ return executePlacement(actions, "Place media");
+ },
+
+ moveTimelineItem: async (itemId, startTime, targetTrackId) => {
+ const { project } = get();
+ const resolved = resolveTimelineItem(project, itemId);
+ if (!resolved) return failure("INVALID_PARAMS", "Timeline item not found");
+ const sourceTrack = project.timeline.tracks.find(
+ (track) => track.id === resolved.trackId,
+ );
+ if (sourceTrack?.locked) {
+ return failure("TRACK_LOCKED", "Source track is locked");
+ }
+
+ const requestedTrackId = targetTrackId ?? resolved.trackId;
+ const placement = resolveTimelinePlacement(project, {
+ targetTrackId: requestedTrackId,
+ startTime,
+ duration: resolved.duration,
+ policy: targetTrackId ? "stack-above" : "gap",
+ excludeItemIds: [itemId],
+ newTrackId: uuidv4(),
+ });
+ if (!placement.ok) {
+ if (placement.reason === "track-not-found") {
+ return failure("TRACK_NOT_FOUND", "Destination track not found");
+ }
+ if (placement.reason === "track-locked") {
+ return failure("TRACK_LOCKED", "Destination track is locked");
+ }
+ return failure("OVERLAP_DETECTED", "The destination interval is occupied");
+ }
+
+ const actions: Action[] = [];
+ if (placement.createdTrack) {
+ actions.push({
+ type: "track/add",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ trackType: "video",
+ trackId: placement.createdTrack.id,
+ position: placement.createdTrack.position,
+ mode: "standard",
+ },
+ });
+ }
+ if (resolved.kind === "media") {
+ actions.push({
+ type: "clip/move",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ clipId: itemId,
+ startTime: placement.startTime,
+ trackId: placement.trackId,
+ },
+ });
+ } else if (
+ resolved.kind === "text" ||
+ resolved.kind === "shape" ||
+ resolved.kind === "svg" ||
+ resolved.kind === "sticker"
+ ) {
+ actions.push({
+ type: `${resolved.kind}/update`,
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ clipId: itemId,
+ updates: {
+ startTime: placement.startTime,
+ trackId: placement.trackId,
+ },
+ },
+ });
+ } else {
+ return failure(
+ "INVALID_PARAMS",
+ "This timeline item cannot be moved from the timeline yet",
+ );
+ }
+
+ return executePlacement(actions, "Move timeline item");
+ },
+ };
+}
diff --git a/apps/web/src/stores/project/track-slice.ts b/apps/web/src/stores/project/track-slice.ts
index f14ae330..ce23b61b 100644
--- a/apps/web/src/stores/project/track-slice.ts
+++ b/apps/web/src/stores/project/track-slice.ts
@@ -1,6 +1,7 @@
import { v4 as uuidv4 } from "uuid";
import type { StoreApi } from "zustand";
import type { Action, Project } from "@openreel/core";
+import { withUniversalTracksCapability } from "@openreel/core";
import type { ProjectState } from "../project-store";
type Get = StoreApi<ProjectState>["getState"];
@@ -24,14 +25,15 @@ export type TrackSlice = Pick<
export function createTrackSlice(set: Set, get: Get): TrackSlice {
return {
- addTrack: async (trackType, position) => {
+ addTrack: async (trackType, position, options) => {
const { project, actionExecutor } = get();
const projectCopy = structuredClone(project);
+ const trackId = options?.trackId ?? `track-${uuidv4()}`;
const action: Action = {
type: "track/add",
id: uuidv4(),
timestamp: Date.now(),
- params: { trackType, position },
+ params: { trackType, position, ...options, trackId },
};
const result = await actionExecutor.execute(action, projectCopy);
if (result.success) {
@@ -39,7 +41,12 @@ export function createTrackSlice(set: Set, get: Get): TrackSlice {
...projectCopy,
modifiedAt: Date.now(),
};
- set({ project: finalProject });
+ set({
+ project:
+ options?.mode === "standard"
+ ? withUniversalTracksCapability(finalProject)
+ : finalProject,
+ });
}
return result;
},
diff --git a/apps/web/src/stores/project/types.ts b/apps/web/src/stores/project/types.ts
index f8f16599..78ef2ec7 100644
--- a/apps/web/src/stores/project/types.ts
+++ b/apps/web/src/stores/project/types.ts
@@ -143,6 +143,12 @@ export interface ProjectState {
addTrack: (
trackType: "video" | "audio" | "image" | "text" | "graphics",
position?: number,
+ options?: {
+ mode?: "standard";
+ role?: Track["role"];
+ name?: string;
+ trackId?: string;
+ },
) => Promise<ActionResult>;
duplicateTrack: (trackId: string) => Promise<ActionResult>;
removeTrack: (trackId: string) => Promise<ActionResult>;
@@ -159,6 +165,16 @@ export interface ProjectState {
mediaId: string,
startTime: number,
) => Promise<ActionResult>;
+ placeMediaClip: (
+ mediaId: string,
+ targetTrackId: string | undefined,
+ startTime: number,
+ ) => Promise<ActionResult>;
+ moveTimelineItem: (
+ itemId: string,
+ startTime: number,
+ targetTrackId?: string,
+ ) => Promise<ActionResult>;
removeClip: (clipId: string) => Promise<ActionResult>;
moveClip: (
clipId: string,
diff --git a/apps/web/src/stores/settings-store.test.ts b/apps/web/src/stores/settings-store.test.ts
new file mode 100644
index 00000000..7012659c
--- /dev/null
+++ b/apps/web/src/stores/settings-store.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { useSettingsStore } from "./settings-store";
+
+describe("settings store migrations", () => {
+ afterEach(() => {
+ localStorage.clear();
+ useSettingsStore.setState({
+ autoSave: true,
+ defaultLlmProvider: null,
+ llmBaseUrl: "",
+ llmModel: "",
+ });
+ });
+
+ it("removes legacy preset selections without discarding other preferences", async () => {
+ localStorage.setItem(
+ "openreel-settings",
+ JSON.stringify({
+ version: 5,
+ state: {
+ autoSave: false,
+ defaultLlmProvider: "openai",
+ llmModel: "previously-preselected-model",
+ },
+ }),
+ );
+
+ await useSettingsStore.persist.rehydrate();
+
+ expect(useSettingsStore.getState()).toMatchObject({
+ autoSave: false,
+ defaultLlmProvider: null,
+ llmBaseUrl: "",
+ llmModel: "",
+ });
+ });
+
+ it("migrates an explicitly configured compatible endpoint", async () => {
+ localStorage.setItem(
+ "openreel-settings",
+ JSON.stringify({
+ version: 6,
+ state: {
+ defaultLlmProvider: "openai-compatible",
+ llmModel: "ignored-preset-model",
+ openaiCompatibleBaseUrl: "http://localhost:11434/v1",
+ openaiCompatibleModel: "qwen-tool-model",
+ },
+ }),
+ );
+
+ await useSettingsStore.persist.rehydrate();
+
+ expect(useSettingsStore.getState()).toMatchObject({
+ defaultLlmProvider: "openai-compatible",
+ llmBaseUrl: "http://localhost:11434/v1",
+ llmModel: "qwen-tool-model",
+ });
+ });
+});
diff --git a/apps/web/src/stores/settings-store.ts b/apps/web/src/stores/settings-store.ts
index ac85962c..8aba22cf 100644
--- a/apps/web/src/stores/settings-store.ts
+++ b/apps/web/src/stores/settings-store.ts
@@ -7,6 +7,7 @@ export interface ServiceConfig {
readonly label: string;
readonly description: string;
readonly docsUrl?: string;
+ readonly keyOptional?: boolean;
}
/**
@@ -21,16 +22,16 @@ export const SERVICE_REGISTRY: readonly ServiceConfig[] = [
docsUrl: "https://elevenlabs.io/docs/api-reference",
},
{
- id: "openai",
- label: "OpenAI",
- description: "GPT models for script generation and AI features",
- docsUrl: "https://platform.openai.com/docs/api-reference",
+ id: "openai-compatible",
+ label: "OpenAI-compatible endpoint",
+ description: "Any OpenAI-compatible API host; API key optional",
+ keyOptional: true,
},
{
- id: "anthropic",
- label: "Anthropic",
- description: "Claude models for AI-assisted editing",
- docsUrl: "https://docs.anthropic.com/en/docs",
+ id: "anthropic-compatible",
+ label: "Anthropic-compatible endpoint",
+ description: "Any Anthropic Messages-compatible API host; API key optional",
+ keyOptional: true,
},
{
id: "kie-ai",
@@ -46,11 +47,15 @@ export const SERVICE_REGISTRY: readonly ServiceConfig[] = [
},
] as const;
-export type TtsProvider = "piper" | "elevenlabs";
-export type LlmProvider = "openai" | "anthropic";
+export type TtsProvider = "elevenlabs";
+export type LlmProvider = "openai-compatible" | "anthropic-compatible";
export type AggregatorProvider = "kie-ai" | "freepik";
export type SettingsTab = "general" | "api-keys" | "mcp";
+function isLlmProvider(value: unknown): value is LlmProvider {
+ return value === "openai-compatible" || value === "anthropic-compatible";
+}
+
export interface SettingsState {
// General preferences
autoSave: boolean;
@@ -59,8 +64,9 @@ export interface SettingsState {
// AI/Service preferences
defaultTtsProvider: TtsProvider;
- defaultLlmProvider: LlmProvider;
- /** Selected model id for the agent chat (per the current LLM provider). */
+ defaultLlmProvider: LlmProvider | null;
+ /** User-defined compatible endpoint and model for the agent chat. */
+ llmBaseUrl: string;
llmModel: string;
defaultAggregator: AggregatorProvider;
elevenLabsModel: string;
@@ -89,7 +95,8 @@ export interface SettingsState {
setAutoSaveInterval: (minutes: number) => void;
setLanguage: (lang: string) => void;
setDefaultTtsProvider: (provider: TtsProvider) => void;
- setDefaultLlmProvider: (provider: LlmProvider) => void;
+ setDefaultLlmProvider: (provider: LlmProvider | null) => void;
+ setLlmBaseUrl: (url: string) => void;
setLlmModel: (model: string) => void;
setMcpAutoAllowTrustedLocal: (enabled: boolean) => void;
setAgentAutoConfirm: (enabled: boolean) => void;
@@ -117,9 +124,10 @@ export const useSettingsStore = create<SettingsState>()(
autoSaveInterval: 5,
language: "en",
- defaultTtsProvider: "piper" as TtsProvider,
- defaultLlmProvider: "openai" as LlmProvider,
- llmModel: "gpt-4o",
+ defaultTtsProvider: "elevenlabs" as TtsProvider,
+ defaultLlmProvider: null,
+ llmBaseUrl: "",
+ llmModel: "",
defaultAggregator: "kie-ai" as AggregatorProvider,
elevenLabsModel: "eleven_v3",
favoriteVoices: [],
@@ -146,9 +154,11 @@ export const useSettingsStore = create<SettingsState>()(
setDefaultTtsProvider: (provider: TtsProvider) =>
set({ defaultTtsProvider: provider }),
- setDefaultLlmProvider: (provider: LlmProvider) =>
+ setDefaultLlmProvider: (provider: LlmProvider | null) =>
set({ defaultLlmProvider: provider }),
+ setLlmBaseUrl: (url: string) => set({ llmBaseUrl: url }),
+
setLlmModel: (model: string) => set({ llmModel: model }),
setMcpAutoAllowTrustedLocal: (enabled: boolean) =>
@@ -221,10 +231,37 @@ export const useSettingsStore = create<SettingsState>()(
}),
{
name: "openreel-settings",
- version: 2,
+ version: 7,
migrate: (persisted, version) => {
const next = (persisted ?? {}) as Record<string, unknown>;
if (version < 2) next.mcpAutoAllowTrustedLocal = true;
+ if (version < 3 && (!next.llmModel || next.llmModel === "gpt-4o")) {
+ next.llmModel = "gpt-5.6-sol";
+ }
+ if (version < 5 || next.defaultTtsProvider === "piper") {
+ next.defaultTtsProvider = "elevenlabs";
+ }
+ const previousProvider = next.defaultLlmProvider;
+ if (!isLlmProvider(previousProvider)) {
+ next.defaultLlmProvider = null;
+ next.llmBaseUrl = "";
+ next.llmModel = "";
+ } else {
+ next.llmBaseUrl =
+ typeof next.llmBaseUrl === "string"
+ ? next.llmBaseUrl
+ : previousProvider === "openai-compatible" &&
+ typeof next.openaiCompatibleBaseUrl === "string"
+ ? next.openaiCompatibleBaseUrl
+ : "";
+ next.llmModel =
+ previousProvider === "openai-compatible" &&
+ typeof next.openaiCompatibleModel === "string"
+ ? next.openaiCompatibleModel
+ : typeof next.llmModel === "string"
+ ? next.llmModel
+ : "";
+ }
return next as unknown as SettingsState;
},
partialize: (state) => ({
@@ -233,6 +270,7 @@ export const useSettingsStore = create<SettingsState>()(
language: state.language,
defaultTtsProvider: state.defaultTtsProvider,
defaultLlmProvider: state.defaultLlmProvider,
+ llmBaseUrl: state.llmBaseUrl,
llmModel: state.llmModel,
defaultAggregator: state.defaultAggregator,
elevenLabsModel: state.elevenLabsModel,
diff --git a/apps/web/src/stores/ui-store.ts b/apps/web/src/stores/ui-store.ts
index 94f30ecf..a6f12876 100644
--- a/apps/web/src/stores/ui-store.ts
+++ b/apps/web/src/stores/ui-store.ts
@@ -9,7 +9,6 @@ export type PanelId =
| "audioMixer"
| "colorGrading"
| "subtitles"
- | "ai"
| "agentChat";
export type SelectionType =
@@ -202,7 +201,6 @@ const DEFAULT_PANELS: Record<PanelId, PanelState> = {
audioMixer: { visible: false, width: 300 },
colorGrading: { visible: false, width: 400 },
subtitles: { visible: false, width: 300 },
- ai: { visible: false, width: 300 },
agentChat: { visible: false, width: 380 },
};
diff --git a/apps/web/src/types/global.d.ts b/apps/web/src/types/global.d.ts
index 39859b76..a968c2c4 100644
--- a/apps/web/src/types/global.d.ts
+++ b/apps/web/src/types/global.d.ts
@@ -228,20 +228,21 @@ declare global {
};
cloud: {
fetch(
- service: "elevenlabs" | "openai" | "anthropic",
+ service:
+ | "elevenlabs"
+ | "openai"
+ | "anthropic"
+ | "openai-compatible"
+ | "anthropic-compatible",
path: string,
- options?: { method?: string; headers?: Record<string, string>; body?: string },
+ options?: {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: string;
+ baseUrl?: string;
+ },
): Promise<{ status: number; statusText: string; headers: Record<string, string>; body: ArrayBuffer }>;
};
- gpu: {
- uploadMedia(args: { srcPath: string; filename: string; contentType?: string }): Promise<{ mediaKey: string; downloadUrl?: string }>;
- uploadExport(args: { bytes: ArrayBuffer | Uint8Array; filename: string; contentType?: string }): Promise<{ mediaKey: string; downloadUrl?: string }>;
- submitJob(args: { kind: string; params: Record<string, unknown>; mediaKey?: string; mediaFilename?: string }): Promise<{ jobID: string; status: string; manifestURL?: string }>;
- jobStatus(jobID: string): Promise<{ jobID: string; status: string; progress?: number; message?: string; manifestURL?: string; error?: string; queuePosition?: number; pendingAhead?: number }>;
- fetchManifest(jobID: string): Promise<Record<string, unknown>>;
- downloadArtifact(jobID: string, relativePath: string): Promise<{ tempPath: string; mime: string }>;
- cancelJob(jobID: string): Promise<{ jobID: string; status: string }>;
- };
win: {
minimize(): Promise<void>;
toggleMaximize(): Promise<void>;
diff --git a/apps/web/src/utils/media-recovery.test.ts b/apps/web/src/utils/media-recovery.test.ts
new file mode 100644
index 00000000..ed648cef
--- /dev/null
+++ b/apps/web/src/utils/media-recovery.test.ts
@@ -0,0 +1,129 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { MediaItem } from "@openreel/core";
+import {
+ createMissingMediaItem,
+ generateThumbnailFromBlob,
+ restoreMediaItem,
+} from "./media-recovery";
+
+function mockCreateObjectURL(
+ implementation: (blob: Blob) => string = () => "blob:thumbnail",
+) {
+ const mock = vi.fn(implementation);
+ Object.defineProperty(URL, "createObjectURL", {
+ configurable: true,
+ writable: true,
+ value: mock,
+ });
+ return mock;
+}
+
+function mediaItem(overrides: Partial<MediaItem> = {}): MediaItem {
+ return {
+ id: "media-1",
+ name: "clip.png",
+ type: "image",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 0,
+ width: 1920,
+ height: 1080,
+ frameRate: 0,
+ codec: "png",
+ sampleRate: 0,
+ channels: 0,
+ fileSize: 5,
+ },
+ thumbnailUrl: "blob:stale-thumbnail",
+ waveformData: null,
+ filmstripThumbnails: [
+ { timestamp: 0, url: "blob:stale-filmstrip" },
+ ],
+ sourceFile: {
+ name: "clip.png",
+ size: 5,
+ lastModified: 123,
+ },
+ ...overrides,
+ };
+}
+
+describe("media recovery", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ Reflect.deleteProperty(URL, "createObjectURL");
+ });
+
+ it("marks a JSON blob placeholder as missing without creating an object URL", async () => {
+ const createObjectURL = mockCreateObjectURL();
+ const item = mediaItem({
+ blob: {} as Blob,
+ fileHandle: {} as FileSystemFileHandle,
+ waveformData: {} as Float32Array,
+ });
+
+ const restored = await restoreMediaItem(item, undefined);
+
+ expect(restored).toMatchObject({
+ id: "media-1",
+ fileHandle: null,
+ blob: null,
+ thumbnailUrl: null,
+ waveformData: null,
+ isPlaceholder: true,
+ });
+ expect(restored.filmstripThumbnails).toBeUndefined();
+ expect(restored.sourceFile).toEqual(item.sourceFile);
+ expect(createObjectURL).not.toHaveBeenCalled();
+ });
+
+ it("restores an IndexedDB blob instead of the serialized placeholder", async () => {
+ const storedBlob = new Blob(["image"], { type: "image/png" });
+ const createObjectURL = mockCreateObjectURL(
+ () => "blob:restored-thumbnail",
+ );
+ const item = mediaItem({ blob: {} as Blob, isPlaceholder: true });
+
+ const restored = await restoreMediaItem(item, storedBlob);
+
+ expect(restored.blob).toBe(storedBlob);
+ expect(restored.thumbnailUrl).toBe("blob:restored-thumbnail");
+ expect(restored.isPlaceholder).toBe(false);
+ expect(createObjectURL).toHaveBeenCalledWith(storedBlob);
+ });
+
+ it("keeps recovered media usable when thumbnail regeneration fails", async () => {
+ const storedBlob = new Blob(["image"], { type: "image/png" });
+ mockCreateObjectURL(() => {
+ throw new TypeError("thumbnail failure");
+ });
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ const restored = await restoreMediaItem(mediaItem(), storedBlob);
+
+ expect(restored.blob).toBe(storedBlob);
+ expect(restored.thumbnailUrl).toBeNull();
+ expect(restored.isPlaceholder).toBe(false);
+ });
+
+ it("rejects non-Blob input at the thumbnail boundary", async () => {
+ const createObjectURL = mockCreateObjectURL();
+
+ await expect(
+ generateThumbnailFromBlob({} as Blob, "image"),
+ ).resolves.toBeNull();
+ expect(createObjectURL).not.toHaveBeenCalled();
+ });
+
+ it("creates a relinkable placeholder while preserving source hints", () => {
+ const item = mediaItem();
+
+ expect(createMissingMediaItem(item)).toMatchObject({
+ id: item.id,
+ blob: null,
+ isPlaceholder: true,
+ sourceFile: item.sourceFile,
+ });
+ });
+});
diff --git a/apps/web/src/utils/media-recovery.ts b/apps/web/src/utils/media-recovery.ts
index ca69540b..55a7e906 100644
--- a/apps/web/src/utils/media-recovery.ts
+++ b/apps/web/src/utils/media-recovery.ts
@@ -4,6 +4,10 @@ export async function generateThumbnailFromBlob(
blob: Blob,
type: "video" | "audio" | "image",
): Promise<string | null> {
+ if (!(blob instanceof Blob)) {
+ return null;
+ }
+
if (type === "audio") {
return null;
}
@@ -75,26 +79,56 @@ export async function generateThumbnailFromBlob(
});
}
+export function createMissingMediaItem(item: MediaItem): MediaItem {
+ return {
+ ...item,
+ fileHandle: null,
+ blob: null,
+ thumbnailUrl: item.thumbnailUrl?.startsWith("blob:")
+ ? null
+ : item.thumbnailUrl,
+ waveformData: null,
+ filmstripThumbnails: undefined,
+ isPlaceholder: true,
+ };
+}
+
export async function restoreMediaItem(
item: MediaItem,
storedBlob: Blob | undefined,
): Promise<MediaItem> {
- const blob = storedBlob || item.blob;
+ const blob =
+ storedBlob instanceof Blob
+ ? storedBlob
+ : item.blob instanceof Blob
+ ? item.blob
+ : null;
if (!blob) {
- return item;
+ return createMissingMediaItem(item);
}
let thumbnailUrl = item.thumbnailUrl;
if (!thumbnailUrl || thumbnailUrl.startsWith("blob:")) {
- thumbnailUrl = await generateThumbnailFromBlob(blob, item.type);
+ try {
+ thumbnailUrl = await generateThumbnailFromBlob(blob, item.type);
+ } catch (error) {
+ console.warn(
+ `[MediaRecovery] Failed to regenerate thumbnail for ${item.name}:`,
+ error,
+ );
+ thumbnailUrl = null;
+ }
}
return {
...item,
+ fileHandle: null,
blob,
thumbnailUrl,
+ waveformData: null,
filmstripThumbnails: undefined,
+ isPlaceholder: false,
};
}
diff --git a/apps/web/src/utils/timeline-item-actions.test.ts b/apps/web/src/utils/timeline-item-actions.test.ts
index d97bf7bc..d220dea4 100644
--- a/apps/web/src/utils/timeline-item-actions.test.ts
+++ b/apps/web/src/utils/timeline-item-actions.test.ts
@@ -36,16 +36,37 @@ function createStore(overrides: Partial<ProjectState> = {}): ProjectState {
}
describe("timeline item actions", () => {
- it("routes sticker deletion to the sticker action", async () => {
- const sticker = { id: "sticker-1" };
+ it.each([
+ ["media", "getClip", "removeClip"],
+ ["text", "getTextClip", "deleteTextClip"],
+ ["shape", "getShapeClip", "deleteShapeClip"],
+ ["svg", "getSVGClip", "deleteSVGClip"],
+ ["sticker", "getStickerClip", "deleteStickerClip"],
+ ] as const)("routes %s deletion to its matching action", async (
+ kind,
+ getter,
+ remover,
+ ) => {
+ const id = `${kind}-1`;
const store = createStore({
- getStickerClip: vi.fn().mockReturnValue(sticker),
+ [getter]: vi.fn().mockReturnValue({ id }),
});
- await expect(deleteTimelineItem(store, sticker.id)).resolves.toBe(true);
- expect(store.deleteStickerClip).toHaveBeenCalledWith(sticker.id);
- expect(store.deleteShapeClip).not.toHaveBeenCalled();
- expect(store.removeClip).not.toHaveBeenCalled();
+ await expect(deleteTimelineItem(store, id)).resolves.toBe(true);
+ expect(store[remover]).toHaveBeenCalledWith(id);
+
+ const otherRemovers = [
+ "removeClip",
+ "deleteTextClip",
+ "deleteShapeClip",
+ "deleteSVGClip",
+ "deleteStickerClip",
+ ] as const;
+ for (const otherRemover of otherRemovers) {
+ if (otherRemover !== remover) {
+ expect(store[otherRemover]).not.toHaveBeenCalled();
+ }
+ }
});
it("duplicates both media and overlay timeline items", async () => {
diff --git a/apps/web/src/workers/multicam-analysis-worker.ts b/apps/web/src/workers/multicam-analysis-worker.ts
new file mode 100644
index 00000000..645a7172
--- /dev/null
+++ b/apps/web/src/workers/multicam-analysis-worker.ts
@@ -0,0 +1,34 @@
+/// <reference lib="webworker" />
+
+import {
+ analyzeMulticamDrift,
+ type MulticamDriftAnalysisOptions,
+} from "@openreel/core";
+
+interface DriftRequest {
+ requestId: string;
+ type: "drift";
+ reference: Float32Array;
+ target: Float32Array;
+ sampleRate: number;
+ options?: MulticamDriftAnalysisOptions;
+}
+
+self.onmessage = (event: MessageEvent<DriftRequest>) => {
+ const { requestId, reference, target, sampleRate, options } = event.data;
+ try {
+ self.postMessage({
+ requestId,
+ type: "result",
+ model: analyzeMulticamDrift(reference, target, sampleRate, options),
+ });
+ } catch (error) {
+ self.postMessage({
+ requestId,
+ type: "error",
+ message: error instanceof Error ? error.message : "Multicam sync failed",
+ });
+ }
+};
+
+export {};
diff --git a/package.json b/package.json
index 3fcab06f..021d6654 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "openreel",
- "version": "0.1.1",
+ "version": "0.1.2",
"private": true,
"description": "Professional video, audio, and photo editing in your browser",
"type": "module",
@@ -14,6 +14,8 @@
"test": "pnpm -r test:run",
"test:watch": "pnpm -r test",
"lint": "pnpm -r lint",
+ "check:mobile-offline": "node scripts/check-mobile-offline.mjs",
+ "check:retired-cloud-gpu": "node scripts/check-retired-cloud-gpu.mjs",
"typecheck": "pnpm -r typecheck",
"clean": "pnpm -r clean",
"claude:help": "cat scripts/claude-review.md",
diff --git a/packages/agent-runner/src/cli.ts b/packages/agent-runner/src/cli.ts
index 4db4fa8a..75623c42 100644
--- a/packages/agent-runner/src/cli.ts
+++ b/packages/agent-runner/src/cli.ts
@@ -57,8 +57,8 @@ function resolveApiKey(provider: LlmProvider): string {
}
const DEFAULT_MODEL: Record<LlmProvider, string> = {
- anthropic: "claude-sonnet-4-20250514",
- openai: "gpt-4o",
+ anthropic: "claude-sonnet-5",
+ openai: "gpt-5.6-sol",
};
const USAGE = `openreel-agent — headless project editing
diff --git a/packages/agent-runner/src/export-queue.ts b/packages/agent-runner/src/export-queue.ts
index ac520e4d..db6f070a 100644
--- a/packages/agent-runner/src/export-queue.ts
+++ b/packages/agent-runner/src/export-queue.ts
@@ -19,7 +19,7 @@ export interface ExportQueueOptions {
}
/**
- * Drives a batch of export/render jobs through a JobRunner (e.g. the GPU worker)
+ * Drives a batch of export/render jobs through a JobRunner
* with a bounded worker pool — the "export these N variants" capability. Results
* are returned in input order; a failing job never aborts the rest.
*/
diff --git a/packages/agent-runner/src/gpu-job-runner.test.ts b/packages/agent-runner/src/gpu-job-runner.test.ts
deleted file mode 100644
index e8065156..00000000
--- a/packages/agent-runner/src/gpu-job-runner.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { createGpuJobRunner, GpuTokenProvider, type GpuRunnerConfig } from "./gpu-job-runner";
-
-function json(status: number, body: unknown): Response {
- return {
- ok: status < 400,
- status,
- headers: { get: () => null },
- json: async () => body,
- text: async () => JSON.stringify(body),
- } as unknown as Response;
-}
-
-const baseConfig: Omit<GpuRunnerConfig, "fetchFn"> = {
- gpuBaseUrl: "https://gpu.test",
- brokerBaseUrl: "https://broker.test",
- bundleId: "com.openreel.video",
- instanceId: "srv-1",
- pollIntervalMs: 1,
- sleep: async () => {},
- now: () => 1000,
-};
-
-describe("GpuTokenProvider", () => {
- it("mints a token via challenge then token, and caches it", async () => {
- const fetchFn = vi
- .fn()
- .mockResolvedValueOnce(json(200, { challengeId: "ch1" }))
- .mockResolvedValueOnce(json(200, { token: "jwt-1", exp: 9999 }));
- const provider = new GpuTokenProvider({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
-
- expect(await provider.getToken()).toBe("jwt-1");
- expect(await provider.getToken()).toBe("jwt-1");
- expect(fetchFn).toHaveBeenCalledTimes(2);
- expect((fetchFn.mock.calls[0][0] as string)).toContain("/auth/challenge");
- expect((fetchFn.mock.calls[1][0] as string)).toContain("/auth/token");
- });
-
- it("throws on a failed challenge", async () => {
- const fetchFn = vi.fn().mockResolvedValue(json(503, {}));
- const provider = new GpuTokenProvider({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
- await expect(provider.getToken()).rejects.toThrow(/challenge failed/);
- });
-});
-
-describe("createGpuJobRunner", () => {
- function routedFetch(jobStatuses: Array<Record<string, unknown>>) {
- let pollIndex = 0;
- return vi.fn(async (url: string, init?: RequestInit) => {
- if (url.includes("/auth/challenge")) return json(200, { challengeId: "ch1" });
- if (url.includes("/auth/token")) return json(200, { token: "jwt", exp: 9999 });
- if (url.endsWith("/jobs") && init?.method === "POST")
- return json(200, { jobID: "job1", status: "queued" });
- if (url.includes("/jobs/job1")) return json(200, jobStatuses[pollIndex++] ?? jobStatuses[jobStatuses.length - 1]);
- return json(404, {});
- });
- }
-
- it("submits a job and polls to success", async () => {
- const fetchFn = routedFetch([
- { jobID: "job1", status: "running", progress: 50 },
- { jobID: "job1", status: "succeeded", manifestURL: "https://gpu.test/m" },
- ]);
- const runner = createGpuJobRunner({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
-
- const result = await runner("upscale", { mediaKey: "k" });
- expect(result.ok).toBe(true);
- expect(result.data).toMatchObject({ jobID: "job1", status: "succeeded", manifestURL: "https://gpu.test/m" });
- });
-
- it("returns an error when the job fails", async () => {
- const fetchFn = routedFetch([{ jobID: "job1", status: "failed", error: "GPU OOM" }]);
- const runner = createGpuJobRunner({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
-
- const result = await runner("exportVideo", {});
- expect(result.ok).toBe(false);
- expect(result.error).toContain("GPU OOM");
- });
-
- it("times out when the job never reaches a terminal state", async () => {
- let t = 0;
- const fetchFn = vi.fn(async (url: string, init?: RequestInit) => {
- if (url.includes("/auth/challenge")) return json(200, { challengeId: "ch1" });
- if (url.includes("/auth/token")) return json(200, { token: "jwt", exp: 9999 });
- if (url.endsWith("/jobs") && init?.method === "POST")
- return json(200, { jobID: "job1", status: "queued" });
- return json(200, { jobID: "job1", status: "running" });
- });
- const runner = createGpuJobRunner({
- ...baseConfig,
- fetchFn: fetchFn as unknown as typeof fetch,
- maxPollMs: 10,
- now: () => (t += 5),
- });
- const result = await runner("exportVideo", {});
- expect(result.ok).toBe(false);
- expect(result.error).toMatch(/timed out/);
- });
-
- it("re-mints the token and retries on a 401 from the job API", async () => {
- let tokenCalls = 0;
- let first = true;
- const fetchFn = vi.fn(async (url: string, init?: RequestInit) => {
- if (url.includes("/auth/challenge")) return json(200, { challengeId: "ch1" });
- if (url.includes("/auth/token")) {
- tokenCalls++;
- return json(200, { token: `jwt-${tokenCalls}`, exp: 9999 });
- }
- if (url.endsWith("/jobs") && init?.method === "POST") {
- if (first) {
- first = false;
- return json(401, { error: "expired" });
- }
- return json(200, { jobID: "job1", status: "succeeded" });
- }
- return json(200, { jobID: "job1", status: "succeeded" });
- });
- const runner = createGpuJobRunner({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
- const result = await runner("upscale", {});
- expect(result.ok).toBe(true);
- expect(tokenCalls).toBeGreaterThanOrEqual(2);
- });
-
- it("returns an error when submit is rejected", async () => {
- const fetchFn = vi.fn(async (url: string) => {
- if (url.includes("/auth/challenge")) return json(200, { challengeId: "ch1" });
- if (url.includes("/auth/token")) return json(200, { token: "jwt", exp: 9999 });
- return json(500, {});
- });
- const runner = createGpuJobRunner({ ...baseConfig, fetchFn: fetchFn as unknown as typeof fetch });
-
- const result = await runner("transcribe", {});
- expect(result.ok).toBe(false);
- expect(result.error).toContain("submit failed");
- });
-});
diff --git a/packages/agent-runner/src/gpu-job-runner.ts b/packages/agent-runner/src/gpu-job-runner.ts
deleted file mode 100644
index 7923f765..00000000
--- a/packages/agent-runner/src/gpu-job-runner.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-import type { JobKind, JobResult, JobRunner } from "@openreel/agent";
-
-export interface GpuRunnerConfig {
- readonly gpuBaseUrl: string;
- readonly brokerBaseUrl: string;
- readonly bundleId: string;
- readonly instanceId: string;
- /** Broker platform leg; "desktop" uses the unattested open path. */
- readonly platform?: string;
- readonly fetchFn?: typeof fetch;
- readonly pollIntervalMs?: number;
- readonly maxPollMs?: number;
- readonly sleep?: (ms: number) => Promise<void>;
- readonly now?: () => number;
-}
-
-const TERMINAL_OK = new Set(["succeeded", "completed", "complete", "done"]);
-const TERMINAL_FAIL = new Set(["failed", "error", "cancelled", "canceled"]);
-
-const realSleep = (ms: number): Promise<void> =>
- new Promise((resolve) => setTimeout(resolve, ms));
-
-interface TokenCache {
- token: string;
- exp: number;
-}
-
-/**
- * Mints short-lived GPU JWTs via the auth broker's open (unattested) leg, so a
- * server-side agent can authorize GPU jobs without a bundled secret. Tokens are
- * cached until shortly before expiry.
- */
-export class GpuTokenProvider {
- private cached: TokenCache | null = null;
-
- constructor(private readonly config: GpuRunnerConfig) {}
-
- invalidate(): void {
- this.cached = null;
- }
-
- private get fetchFn(): typeof fetch {
- return this.config.fetchFn ?? fetch;
- }
-
- private nowSeconds(): number {
- return Math.floor((this.config.now ? this.config.now() : Date.now()) / 1000);
- }
-
- private headers(): Record<string, string> {
- return {
- "Content-Type": "application/json",
- Accept: "application/json",
- "X-Bundle-ID": this.config.bundleId,
- };
- }
-
- async getToken(): Promise<string> {
- if (this.cached && this.cached.exp - this.nowSeconds() > 60) {
- return this.cached.token;
- }
- const platform = this.config.platform ?? "desktop";
- const challengeRes = await this.fetchFn(`${this.config.brokerBaseUrl}/auth/challenge`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform, instanceId: this.config.instanceId }),
- });
- if (!challengeRes.ok) {
- throw new Error(`auth challenge failed: ${challengeRes.status}`);
- }
- const challenge = (await challengeRes.json()) as { challengeId?: string };
- if (!challenge.challengeId) {
- throw new Error("auth challenge missing challengeId");
- }
- const tokenRes = await this.fetchFn(`${this.config.brokerBaseUrl}/auth/token`, {
- method: "POST",
- headers: this.headers(),
- body: JSON.stringify({ platform, challengeId: challenge.challengeId }),
- });
- if (!tokenRes.ok) {
- throw new Error(`auth token mint failed: ${tokenRes.status}`);
- }
- const minted = (await tokenRes.json()) as { token?: string; exp?: number };
- if (!minted.token || typeof minted.exp !== "number") {
- throw new Error("auth token response malformed");
- }
- this.cached = { token: minted.token, exp: minted.exp };
- return minted.token;
- }
-}
-
-interface GpuJobStatus {
- jobID: string;
- status: string;
- progress?: number;
- message?: string;
- manifestURL?: string;
- error?: string;
-}
-
-/**
- * Builds a JobRunner that delegates the agent's runJob calls (export, transcribe,
- * upscale, remove-background, …) to the GPU worker at `ai.openreel.video`,
- * authorized by the broker. Submits the job, polls to a terminal state, and
- * returns the job reference / manifest. Requires live GPU + broker infra.
- */
-export function createGpuJobRunner(config: GpuRunnerConfig): JobRunner {
- const tokens = new GpuTokenProvider(config);
- const fetchFn = config.fetchFn ?? fetch;
- const pollIntervalMs = config.pollIntervalMs ?? 2000;
- const maxPollMs = config.maxPollMs ?? 10 * 60 * 1000;
- const sleep = config.sleep ?? realSleep;
- const now = config.now ?? Date.now;
-
- async function authedFetch(url: string, init: RequestInit): Promise<Response> {
- const withAuth = async (): Promise<Response> => {
- const token = await tokens.getToken();
- return fetchFn(url, {
- ...init,
- headers: {
- ...(init.headers as Record<string, string>),
- Authorization: `Bearer ${token}`,
- "X-Bundle-ID": config.bundleId,
- Accept: "application/json",
- },
- });
- };
- let res = await withAuth();
- if (res.status === 401) {
- tokens.invalidate();
- res = await withAuth();
- }
- return res;
- }
-
- return async (kind: JobKind, params: Record<string, unknown>): Promise<JobResult> => {
- try {
- const submitRes = await authedFetch(`${config.gpuBaseUrl}/jobs`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ kind, params }),
- });
- if (!submitRes.ok) {
- return { ok: false, error: `GPU submit failed: ${submitRes.status}` };
- }
- const created = (await submitRes.json()) as GpuJobStatus;
- const jobID = created.jobID;
- if (!jobID) return { ok: false, error: "GPU submit returned no jobID" };
-
- const deadline = now() + maxPollMs;
- let status = created.status;
- let last: GpuJobStatus = created;
- while (!TERMINAL_OK.has(status.toLowerCase()) && !TERMINAL_FAIL.has(status.toLowerCase())) {
- if (now() >= deadline) {
- return { ok: false, error: `GPU job ${jobID} timed out (last status: ${status})` };
- }
- await sleep(pollIntervalMs);
- const statusRes = await authedFetch(`${config.gpuBaseUrl}/jobs/${jobID}`, {
- method: "GET",
- });
- if (!statusRes.ok) {
- return { ok: false, error: `GPU status failed: ${statusRes.status}` };
- }
- last = (await statusRes.json()) as GpuJobStatus;
- status = last.status;
- }
-
- if (TERMINAL_FAIL.has(status.toLowerCase())) {
- return { ok: false, error: last.error ?? `GPU job ${jobID} ${status}` };
- }
- return {
- ok: true,
- data: { jobID, status, manifestURL: last.manifestURL },
- };
- } catch (error) {
- return {
- ok: false,
- error: error instanceof Error ? error.message : String(error),
- };
- }
- };
-}
diff --git a/packages/agent-runner/src/index.ts b/packages/agent-runner/src/index.ts
index 8aca046a..63465fa6 100644
--- a/packages/agent-runner/src/index.ts
+++ b/packages/agent-runner/src/index.ts
@@ -16,11 +16,6 @@ export {
type NodeLLMOptions,
type LlmProvider,
} from "./node-llm";
-export {
- createGpuJobRunner,
- GpuTokenProvider,
- type GpuRunnerConfig,
-} from "./gpu-job-runner";
export {
runExportQueue,
type ExportJobSpec,
diff --git a/packages/agent-runner/src/run.ts b/packages/agent-runner/src/run.ts
index 5223fd73..37df901c 100644
--- a/packages/agent-runner/src/run.ts
+++ b/packages/agent-runner/src/run.ts
@@ -4,6 +4,7 @@ import {
toAnthropicTools,
toOpenAITools,
buildSystemPrompt,
+ selectToolsForPrompt,
} from "@openreel/agent";
import type { LLMClient, RunTurnResult, JobRunner } from "@openreel/agent";
import type { Project } from "@openreel/core/types/project";
@@ -46,13 +47,17 @@ export async function runHeadlessEdit(
maxTokens: opts.maxTokens,
fetchFn: opts.fetchFn,
});
- const tools = opts.provider === "anthropic" ? toAnthropicTools() : toOpenAITools();
+ const selectedToolNames = selectToolsForPrompt(opts.prompt);
+ const tools =
+ opts.provider === "anthropic"
+ ? toAnthropicTools(selectedToolNames)
+ : toOpenAITools(selectedToolNames);
const result = await runTurn({
host,
llm,
tools,
- system: buildSystemPrompt(host),
+ system: buildSystemPrompt(host, selectedToolNames),
messages: [{ role: "user", content: opts.prompt }],
limits: opts.limits,
dryRun: opts.dryRun,
diff --git a/packages/agent/src/headless-host.test.ts b/packages/agent/src/headless-host.test.ts
index 0e9fb609..866670fd 100644
--- a/packages/agent/src/headless-host.test.ts
+++ b/packages/agent/src/headless-host.test.ts
@@ -60,7 +60,7 @@ describe("HeadlessHost", () => {
it("returns a typed failure from runJob with no job runner", async () => {
const host = new HeadlessHost(makeEmptyProject());
- const res = await host.runJob("transcribe", {});
+ const res = await host.runJob("exportVideo", {});
expect(res.ok).toBe(false);
});
});
diff --git a/packages/agent/src/host.ts b/packages/agent/src/host.ts
index 40a61e18..cf01c9d2 100644
--- a/packages/agent/src/host.ts
+++ b/packages/agent/src/host.ts
@@ -1,14 +1,14 @@
import type { Action, ActionResult } from "@openreel/core/types/actions";
import type { Project } from "@openreel/core/types/project";
import type { CapabilityManifest } from "@openreel/core/capabilities/manifest";
+import type {
+ MulticamActivityMap,
+ MulticamManifest,
+ MulticamShotPolicy,
+ MulticamTranscriptSegment,
+} from "@openreel/core";
export type JobKind =
- | "transcribe"
- | "detectHighlights"
- | "removeBackground"
- | "upscale"
- | "generateMusic"
- | "inpaint"
| "exportVideo"
| "exportAudio"
| "exportFrame";
@@ -161,6 +161,37 @@ export interface HumanoidRigResult {
readonly error?: string;
}
+export interface MulticamHostBridge {
+ getManifest(groupId?: string): Promise<{ groupId: string; manifest: MulticamManifest }>;
+ getActivityMap(
+ groupId?: string,
+ range?: { startMs?: number; endMs?: number },
+ ): Promise<{ groupId: string; activity: MulticamActivityMap; sampled: boolean }>;
+ getTranscript(
+ groupId?: string,
+ range?: { startMs?: number; endMs?: number },
+ ): Promise<{ groupId: string; transcripts: Record<string, MulticamTranscriptSegment[]> }>;
+ setEditPolicy(
+ groupId: string,
+ policy: Partial<MulticamShotPolicy>,
+ ): Promise<Record<string, unknown>>;
+ annotateSegment(input: {
+ groupId: string;
+ startMs: number;
+ endMs: number;
+ note: string;
+ }): Promise<Record<string, unknown>>;
+ getEditSummary(groupId?: string): Promise<Record<string, unknown>>;
+ overrideCut(input: {
+ groupId: string;
+ switchId: string;
+ operation: "accept" | "reject" | "nudge" | "set-camera";
+ deltaMs?: number;
+ cameraId?: string;
+ }): Promise<Record<string, unknown>>;
+ previewFrame(groupId: string, timeMs: number): Promise<JobResult>;
+}
+
export interface CreateProjectOptions {
readonly name?: string;
readonly width?: number;
@@ -207,6 +238,8 @@ export interface EditingHost {
runJob(kind: JobKind, params: Record<string, unknown>): Promise<JobResult>;
/** Machine-readable enums + parameter ranges for the agent. */
capabilities(): CapabilityManifest;
+ /** Narrow multicam planning/review surface shared with local MCP clients. */
+ multicam?: MulticamHostBridge;
/** Throws when no project is open (guard for mutating tools). */
requireOpenProject(): void;
diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts
index 0b0566b9..4c6f43ef 100644
--- a/packages/agent/src/index.ts
+++ b/packages/agent/src/index.ts
@@ -18,6 +18,7 @@ export * from "./llm";
export { runTurn } from "./loop";
export type { RunTurnInput, RunTurnResult, StopReason } from "./loop";
export { buildSystemPrompt } from "./system-prompt";
+export { selectToolsForPrompt, DEFAULT_AGENT_TOOL_LIMIT } from "./tool-router";
export { toLogRecord, createEventLogger, collectEvents } from "./observability";
export type { AgentLogRecord } from "./observability";
export { generateCapabilityMarkdown } from "./gen-docs";
diff --git a/packages/agent/src/llm.test.ts b/packages/agent/src/llm.test.ts
index 44244e40..8efc1b9e 100644
--- a/packages/agent/src/llm.test.ts
+++ b/packages/agent/src/llm.test.ts
@@ -3,6 +3,7 @@ import {
buildAnthropicBody,
parseAnthropicResponse,
buildOpenAIBody,
+ makeClientFromSend,
parseOpenAIResponse,
AnthropicClient,
OpenAIClient,
@@ -59,13 +60,17 @@ describe("Anthropic normalization", () => {
describe("OpenAI normalization", () => {
it("builds messages with tool_calls + tool role", () => {
- const body = buildOpenAIBody({ system: "sys", messages: convo, tools: [] }, "gpt") as {
+ const body = buildOpenAIBody({ system: "sys", messages: convo, tools: [] }, "gpt", 2048) as {
messages: Array<{ role: string; tool_calls?: unknown[]; tool_call_id?: string }>;
+ max_completion_tokens: number;
+ max_tokens?: number;
};
expect(body.messages[0].role).toBe("system");
const assistant = body.messages.find((m) => m.role === "assistant");
expect(assistant?.tool_calls).toBeTruthy();
expect(body.messages.some((m) => m.role === "tool")).toBe(true);
+ expect(body.max_completion_tokens).toBe(2048);
+ expect(body.max_tokens).toBeUndefined();
});
it("parses tool_calls with JSON arguments", () => {
@@ -87,6 +92,94 @@ describe("OpenAI normalization", () => {
expect(parsed.stopReason).toBe("tool_use");
});
+ it("normalizes array content, object arguments, fallback ids, and alternate usage fields", () => {
+ const parsed = parseOpenAIResponse({
+ choices: [
+ {
+ message: {
+ content: [
+ { type: "text", text: "First " },
+ { type: "output_text", text: { value: "second" } },
+ ],
+ tool_calls: [
+ { function: { name: "list_clips", arguments: {} } },
+ ],
+ },
+ finish_reason: "stop",
+ },
+ ],
+ usage: { input_tokens: 12, output_tokens: 7 },
+ });
+
+ expect(parsed.text).toBe("First second");
+ expect(parsed.toolUses).toEqual([
+ { id: "compatible-tool-call-0", name: "list_clips", input: {} },
+ ]);
+ expect(parsed.stopReason).toBe("tool_use");
+ expect(parsed.usage).toEqual({ inputTokens: 12, outputTokens: 7 });
+ });
+
+ it("supports legacy function_call and double-encoded arguments", () => {
+ const parsed = parseOpenAIResponse({
+ choices: [
+ {
+ message: {
+ content: null,
+ function_call: {
+ name: "get_clip",
+ arguments: '"{\\"clipId\\":\\"c1\\"}"',
+ },
+ },
+ finish_reason: "function_call",
+ },
+ ],
+ });
+
+ expect(parsed.toolUses[0]).toEqual({
+ id: "legacy-function-call-0",
+ name: "get_clip",
+ input: { clipId: "c1" },
+ });
+ });
+
+ it("rejects malformed compatible responses with actionable errors", () => {
+ expect(() => parseOpenAIResponse({ choices: [] })).toThrow(/no assistant message/i);
+ expect(() =>
+ parseOpenAIResponse({
+ choices: [
+ {
+ message: {
+ tool_calls: [
+ { id: "bad", function: { name: "get_clip", arguments: "{" } },
+ ],
+ },
+ },
+ ],
+ }),
+ ).toThrow(/invalid JSON arguments.*get_clip/i);
+ expect(() =>
+ parseOpenAIResponse({ error: { message: "Model is unavailable" } }),
+ ).toThrow(/Model is unavailable/);
+ });
+
+ it("can omit OpenAI token-limit fields for compatible endpoints", async () => {
+ let sent: Record<string, unknown> | undefined;
+ const client = makeClientFromSend({
+ provider: "openai",
+ model: "compatible-model",
+ omitMaxTokens: true,
+ send: async (body) => {
+ sent = body as Record<string, unknown>;
+ return { choices: [{ message: { content: "ok" }, finish_reason: "stop" }] };
+ },
+ });
+
+ await client.complete({ messages: [{ role: "user", content: "hi" }], tools: [] });
+
+ expect(sent?.max_completion_tokens).toBeUndefined();
+ expect(sent?.max_tokens).toBeUndefined();
+ });
+
it("OpenAIClient round-trips through an injected transport", async () => {
const client = new OpenAIClient({
model: "gpt",
diff --git a/packages/agent/src/llm.ts b/packages/agent/src/llm.ts
index ab315493..301a1465 100644
--- a/packages/agent/src/llm.ts
+++ b/packages/agent/src/llm.ts
@@ -21,6 +21,42 @@ export interface LLMResponse {
readonly usage?: LLMUsage;
}
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+function responseError(raw: unknown, provider: string): Error | null {
+ if (!isRecord(raw) || !isRecord(raw.error)) return null;
+ const message =
+ typeof raw.error.message === "string"
+ ? raw.error.message
+ : typeof raw.error.type === "string"
+ ? raw.error.type
+ : "The provider returned an error response.";
+ return new Error(`${provider}: ${message}`);
+}
+
+function tokenCount(value: unknown): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
+}
+
+function parseToolInput(value: unknown, toolName: string): Record<string, unknown> {
+ if (value === undefined || value === null || value === "") return {};
+ if (isRecord(value)) return value;
+ if (typeof value !== "string") {
+ throw new Error(`Model returned invalid arguments for tool ${toolName}.`);
+ }
+
+ try {
+ let parsed: unknown = JSON.parse(value);
+ // A few compatible servers double-encode function arguments.
+ if (typeof parsed === "string") parsed = JSON.parse(parsed);
+ if (!isRecord(parsed)) throw new Error("arguments must be an object");
+ return parsed;
+ } catch {
+ throw new Error(`Model returned invalid JSON arguments for tool ${toolName}.`);
+ }
+}
+
export type LoopToolResultBlock =
| { readonly type: "text"; readonly text: string }
| {
@@ -208,20 +244,25 @@ export function buildAnthropicBody(
}
export function parseAnthropicResponse(raw: unknown): LLMResponse {
+ const upstreamError = responseError(raw, "Anthropic");
+ if (upstreamError) throw upstreamError;
const r = raw as {
- content?: Array<{ type: string; text?: string; id?: string; name?: string; input?: unknown }>;
+ content?: string | Array<{ type?: string; text?: string; id?: string; name?: string; input?: unknown }>;
stop_reason?: string;
usage?: { input_tokens?: number; output_tokens?: number };
};
- let text = "";
+ let text = typeof r.content === "string" ? r.content : "";
const toolUses: LLMToolUse[] = [];
- for (const block of r.content ?? []) {
+ for (const block of Array.isArray(r.content) ? r.content : []) {
if (block.type === "text" && block.text) text += block.text;
- else if (block.type === "tool_use" && block.id && block.name) {
+ else if (block.type === "tool_use") {
+ if (!block.id || !block.name) {
+ throw new Error("Anthropic returned a tool call without an id or name.");
+ }
toolUses.push({
id: block.id,
name: block.name,
- input: (block.input as Record<string, unknown>) ?? {},
+ input: parseToolInput(block.input, block.name),
});
}
}
@@ -233,8 +274,8 @@ export function parseAnthropicResponse(raw: unknown): LLMResponse {
: "end_turn";
const usage = r.usage
? {
- inputTokens: r.usage.input_tokens ?? 0,
- outputTokens: r.usage.output_tokens ?? 0,
+ inputTokens: tokenCount(r.usage.input_tokens),
+ outputTokens: tokenCount(r.usage.output_tokens),
}
: undefined;
return { text, toolUses, stopReason, usage };
@@ -297,45 +338,87 @@ export function buildOpenAIBody(
model,
messages,
tools: input.tools,
- ...(maxTokens ? { max_tokens: maxTokens } : {}),
+ ...(maxTokens ? { max_completion_tokens: maxTokens } : {}),
};
}
export function parseOpenAIResponse(raw: unknown): LLMResponse {
+ const upstreamError = responseError(raw, "OpenAI-compatible provider");
+ if (upstreamError) throw upstreamError;
const r = raw as {
choices?: Array<{
message?: {
- content?: string | null;
- tool_calls?: Array<{ id: string; function: { name: string; arguments: string } }>;
+ content?: unknown;
+ tool_calls?: unknown[];
+ function_call?: unknown;
};
finish_reason?: string;
}>;
- usage?: { prompt_tokens?: number; completion_tokens?: number };
+ usage?: {
+ prompt_tokens?: number;
+ completion_tokens?: number;
+ input_tokens?: number;
+ output_tokens?: number;
+ };
};
const choice = r.choices?.[0];
+ if (!choice?.message) {
+ throw new Error("OpenAI-compatible provider returned no assistant message.");
+ }
const msg = choice?.message;
- const toolUses: LLMToolUse[] = (msg?.tool_calls ?? []).map((tc) => {
- let input: Record<string, unknown> = {};
- try {
- input = JSON.parse(tc.function.arguments) as Record<string, unknown>;
- } catch {
- input = {};
+
+ const textFromContent = (content: unknown): string => {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .map((part) => {
+ if (typeof part === "string") return part;
+ if (!isRecord(part)) return "";
+ if (typeof part.text === "string") return part.text;
+ if (isRecord(part.text) && typeof part.text.value === "string") {
+ return part.text.value;
+ }
+ return typeof part.content === "string" ? part.content : "";
+ })
+ .join("");
+ };
+
+ const rawToolCalls = Array.isArray(msg.tool_calls) ? [...msg.tool_calls] : [];
+ if (rawToolCalls.length === 0 && msg.function_call !== undefined) {
+ rawToolCalls.push({ id: "legacy-function-call-0", function: msg.function_call });
+ }
+ const toolUses: LLMToolUse[] = rawToolCalls.map((rawToolCall, index) => {
+ if (!isRecord(rawToolCall)) {
+ throw new Error("OpenAI-compatible provider returned an invalid tool call.");
+ }
+ const fn = isRecord(rawToolCall.function) ? rawToolCall.function : rawToolCall;
+ const name = typeof fn.name === "string" ? fn.name : "";
+ if (!name) {
+ throw new Error("OpenAI-compatible provider returned a tool call without a name.");
}
- return { id: tc.id, name: tc.function.name, input };
+ const id =
+ typeof rawToolCall.id === "string" && rawToolCall.id
+ ? rawToolCall.id
+ : `compatible-tool-call-${index}`;
+ return {
+ id,
+ name,
+ input: parseToolInput(fn.arguments, name),
+ };
});
const stopReason: LLMStopReason =
- choice?.finish_reason === "tool_calls"
+ toolUses.length > 0 || choice.finish_reason === "tool_calls" || choice.finish_reason === "function_call"
? "tool_use"
- : choice?.finish_reason === "length"
+ : choice.finish_reason === "length" || choice.finish_reason === "max_tokens"
? "max_tokens"
: "end_turn";
const usage = r.usage
? {
- inputTokens: r.usage.prompt_tokens ?? 0,
- outputTokens: r.usage.completion_tokens ?? 0,
+ inputTokens: tokenCount(r.usage.prompt_tokens ?? r.usage.input_tokens),
+ outputTokens: tokenCount(r.usage.completion_tokens ?? r.usage.output_tokens),
}
: undefined;
- return { text: msg?.content ?? "", toolUses, stopReason, usage };
+ return { text: textFromContent(msg.content), toolUses, stopReason, usage };
}
export class OpenAIClient implements LLMClient {
@@ -351,15 +434,25 @@ export interface ClientFromSendOptions {
readonly provider: LlmProviderName;
readonly model: string;
readonly maxTokens?: number;
+ /** Omit provider-specific output-token fields for broad compatible-endpoint support. */
+ readonly omitMaxTokens?: boolean;
readonly send: LLMSend;
}
/** Assembles the right provider client from an injected transport (shared by the web + node factories). */
export function makeClientFromSend(opts: ClientFromSendOptions): LLMClient {
- const maxTokens = opts.maxTokens ?? 4096;
+ const maxTokens = opts.omitMaxTokens ? undefined : (opts.maxTokens ?? 4096);
return opts.provider === "anthropic"
- ? new AnthropicClient({ model: opts.model, maxTokens, send: opts.send })
- : new OpenAIClient({ model: opts.model, maxTokens, send: opts.send });
+ ? new AnthropicClient({
+ model: opts.model,
+ maxTokens: maxTokens ?? 4096,
+ send: opts.send,
+ })
+ : new OpenAIClient({
+ model: opts.model,
+ maxTokens,
+ send: opts.send,
+ });
}
// ---- Mock (tests / dry runs) ------------------------------------------------
diff --git a/packages/agent/src/loop.test.ts b/packages/agent/src/loop.test.ts
index 32705c2d..d96f83cf 100644
--- a/packages/agent/src/loop.test.ts
+++ b/packages/agent/src/loop.test.ts
@@ -63,6 +63,22 @@ describe("runTurn", () => {
expect(host.getProject().timeline.tracks[0].clips[0].speed ?? 1).toBe(1);
});
+ it("surfaces a provider output-limit stop as a budget stop", async () => {
+ const host = new HeadlessHost(makeProjectWithClip());
+ const result = await runTurn({
+ host,
+ llm: new MockLLMClient([
+ { text: "A partial response", stopReason: "max_tokens", toolUses: [] },
+ ]),
+ tools,
+ messages: userMsg("describe the project"),
+ });
+
+ expect(result.text).toBe("A partial response");
+ expect(result.stoppedReason).toBe("budget");
+ expect(result.committed).toBe(true);
+ });
+
it("gates destructive tools and honors rejection", async () => {
const host = new HeadlessHost(makeProjectWithClip());
const script: LLMResponse[] = [
diff --git a/packages/agent/src/loop.ts b/packages/agent/src/loop.ts
index 3ae1ec8e..f3802522 100644
--- a/packages/agent/src/loop.ts
+++ b/packages/agent/src/loop.ts
@@ -147,7 +147,7 @@ export async function runTurn(input: RunTurnInput): Promise<RunTurnResult> {
text: response.text,
messages,
toolCalls,
- stoppedReason: "end_turn",
+ stoppedReason: response.stopReason === "max_tokens" ? "budget" : "end_turn",
committed: true,
usage,
};
diff --git a/packages/agent/src/registry.multicam.test.ts b/packages/agent/src/registry.multicam.test.ts
new file mode 100644
index 00000000..f1d890d8
--- /dev/null
+++ b/packages/agent/src/registry.multicam.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it, vi } from "vitest";
+import type { EditingHost, MulticamHostBridge } from "./host";
+import { executeTool } from "./executor";
+import { getTool, toMcpTools } from "./registry";
+import type { MulticamManifest } from "@openreel/core";
+
+function bridge(): MulticamHostBridge {
+ const manifest: MulticamManifest = {
+ spec: "openreel-multicam/v1",
+ fps: 25,
+ sync: { method: "audio-crosscorr", reference: "wide" },
+ participants: [
+ { id: "p1", name: "A", audio: "a", seat: "left" },
+ { id: "p2", name: "B", audio: "b", seat: "right" },
+ ],
+ cameras: [
+ { id: "a", type: "closeup", subject: "p1", file: "a.mp4" },
+ { id: "b", type: "closeup", subject: "p2", file: "b.mp4" },
+ { id: "wide", type: "wide", subject: "all", file: "wide.mp4" },
+ ],
+ constraints: {
+ min_shot_ms: 1_800,
+ max_shot_ms: 25_000,
+ cut_lead_ms: 120,
+ reaction_shot_after_ms: 12_000,
+ forbid_jump_cut_same_subject: true,
+ },
+ };
+ return {
+ getManifest: vi.fn(async () => ({
+ groupId: "g1",
+ manifest,
+ })),
+ getActivityMap: vi.fn(),
+ getTranscript: vi.fn(),
+ setEditPolicy: vi.fn(async (_groupId, policy) => ({ policy })),
+ annotateSegment: vi.fn(),
+ getEditSummary: vi.fn(),
+ overrideCut: vi.fn(async () => ({ cuts: 2 })),
+ previewFrame: vi.fn(async () => ({ ok: true, data: { dataUrl: "data:image/png;base64,AA==" } })),
+ };
+}
+
+describe("multicam agent and MCP tools", () => {
+ it("publishes the narrow issue #92 tool surface", () => {
+ const names = [
+ "get_project_manifest",
+ "get_activity_map",
+ "get_transcript",
+ "set_edit_policy",
+ "annotate_segment",
+ "get_edit_summary",
+ "override_cut",
+ "preview_frame",
+ ];
+ expect(names.every((name) => getTool(name))).toBe(true);
+ expect(names.every((name) => toMcpTools().some((tool) => tool.name === name))).toBe(true);
+ expect(getTool("set_edit_policy")?.destructive).toBe(true);
+ expect(getTool("override_cut")?.destructive).toBe(true);
+ });
+
+ it("routes manifest reads through the host bridge", async () => {
+ const multicam = bridge();
+ const result = await executeTool(
+ "get_project_manifest",
+ { groupId: "g1" },
+ { multicam } as unknown as EditingHost,
+ );
+
+ expect(result.ok).toBe(true);
+ expect(multicam.getManifest).toHaveBeenCalledWith("g1");
+ });
+
+ it("enforces policy and cut bounds before invoking the host", async () => {
+ const multicam = bridge();
+ const host = { multicam } as unknown as EditingHost;
+ const invalidPolicy = await executeTool(
+ "set_edit_policy",
+ { groupId: "g1", commitMs: 9_000 },
+ host,
+ );
+ const invalidNudge = await executeTool(
+ "override_cut",
+ { groupId: "g1", switchId: "s1", operation: "nudge", deltaMs: 3_000 },
+ host,
+ );
+ const valid = await executeTool(
+ "set_edit_policy",
+ { groupId: "g1", strategy: "composite", commitMs: 400 },
+ host,
+ );
+
+ expect(invalidPolicy.ok).toBe(false);
+ expect(invalidNudge.ok).toBe(false);
+ expect(valid.ok).toBe(true);
+ expect(multicam.setEditPolicy).toHaveBeenCalledWith(
+ "g1",
+ expect.objectContaining({ strategy: "composite", commitMs: 400 }),
+ );
+ });
+});
diff --git a/packages/agent/src/registry.ts b/packages/agent/src/registry.ts
index cca7fd45..f35f5636 100644
--- a/packages/agent/src/registry.ts
+++ b/packages/agent/src/registry.ts
@@ -31823,12 +31823,243 @@ const TOOLS: RegisteredTool[] = [
},
},
- // jobs (delegated to host.runJob — GPU/render/AI service; gated as expensive)
+ {
+ name: "get_project_manifest",
+ domain: "multicam",
+ title: "Get multicam project manifest",
+ description:
+ "Return the exact openreel-multicam/v1 manifest for a camera group, including participants, camera subjects, sync reference, and hard constraints.",
+ inputSchema: obj({ groupId: str }),
+ readOnly: true,
+ destructive: false,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ return ok("Loaded multicam manifest", await host.multicam.getManifest(optionalString(args.groupId)));
+ },
+ },
+ {
+ name: "get_activity_map",
+ domain: "multicam",
+ title: "Get multicam activity map",
+ description:
+ "Read the reusable .orma speech activity map for an optional millisecond range. Large maps are deterministically sampled to at most 2,000 points.",
+ inputSchema: obj({ groupId: str, startMs: num, endMs: num }),
+ readOnly: true,
+ destructive: false,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const startMs = optionalNumber(args.startMs);
+ const endMs = optionalNumber(args.endMs);
+ if ((startMs !== undefined && startMs < 0) || (endMs !== undefined && endMs < 0) ||
+ (startMs !== undefined && endMs !== undefined && endMs <= startMs)) {
+ return fail("Activity range must satisfy 0 <= startMs < endMs", "INVALID_PARAMS");
+ }
+ return ok("Loaded multicam activity map", await host.multicam.getActivityMap(
+ optionalString(args.groupId),
+ { startMs, endMs },
+ ));
+ },
+ },
+ {
+ name: "get_transcript",
+ domain: "multicam",
+ title: "Get multicam transcript",
+ description:
+ "Read optional per-participant local Whisper transcript segments from the separate .orma artifact.",
+ inputSchema: obj({ groupId: str, startMs: num, endMs: num }),
+ readOnly: true,
+ destructive: false,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const startMs = optionalNumber(args.startMs);
+ const endMs = optionalNumber(args.endMs);
+ if ((startMs !== undefined && startMs < 0) || (endMs !== undefined && endMs < 0) ||
+ (startMs !== undefined && endMs !== undefined && endMs <= startMs)) {
+ return fail("Transcript range must satisfy 0 <= startMs < endMs", "INVALID_PARAMS");
+ }
+ return ok("Loaded multicam transcript", await host.multicam.getTranscript(
+ optionalString(args.groupId),
+ { startMs, endMs },
+ ));
+ },
+ },
+ {
+ name: "set_edit_policy",
+ domain: "multicam",
+ title: "Set multicam edit policy",
+ description:
+ "Re-plan the automatic multicam edit from cached analysis. All values are schema-validated and manifest shot constraints remain hard bounds.",
+ inputSchema: obj({
+ groupId: str,
+ strategy: { type: "string", enum: ["hold", "winner", "priority", "wide", "composite", "progressive"] },
+ escalateTo: { type: "string", enum: ["winner", "priority", "wide", "composite", "progressive"] },
+ priorityParticipantIds: { type: "array", items: str, maxItems: 16 },
+ commitMs: { type: "number", minimum: 0, maximum: 5_000 },
+ layoutEnterMs: { type: "number", minimum: 0, maximum: 5_000 },
+ layoutExitMs: { type: "number", minimum: 0, maximum: 10_000 },
+ minLayoutLifeMs: { type: "number", minimum: 100, maximum: 30_000 },
+ maxLayoutChangesPerMinute: { type: "number", minimum: 1, maximum: 60 },
+ }, ["groupId"]),
+ readOnly: false,
+ destructive: true,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const groupId = optionalString(args.groupId);
+ if (!groupId) return fail("groupId is required", "INVALID_PARAMS");
+ const strategies = ["hold", "winner", "priority", "wide", "composite", "progressive"] as const;
+ const escalations = ["winner", "priority", "wide", "composite", "progressive"] as const;
+ const strategy = optionalString(args.strategy);
+ const escalateTo = optionalString(args.escalateTo);
+ if (strategy && !(strategies as readonly string[]).includes(strategy)) {
+ return fail("strategy is invalid", "INVALID_PARAMS");
+ }
+ if (escalateTo && !(escalations as readonly string[]).includes(escalateTo)) {
+ return fail("escalateTo is invalid", "INVALID_PARAMS");
+ }
+ const bounded = (
+ key: string,
+ minimum: number,
+ maximum: number,
+ ): number | undefined => {
+ const value = optionalNumber(args[key]);
+ if (value === undefined) return undefined;
+ if (value < minimum || value > maximum) throw new Error(`${key} must be between ${minimum} and ${maximum}`);
+ return value;
+ };
+ try {
+ const updates: Record<string, unknown> = {};
+ if (strategy) updates.strategy = strategy;
+ if (escalateTo) updates.escalateTo = escalateTo;
+ if (Array.isArray(args.priorityParticipantIds)) {
+ if (args.priorityParticipantIds.length > 16 || args.priorityParticipantIds.some((id) => typeof id !== "string")) {
+ return fail("priorityParticipantIds must contain at most 16 strings", "INVALID_PARAMS");
+ }
+ updates.priorityParticipantIds = args.priorityParticipantIds;
+ }
+ for (const [key, minimum, maximum] of [
+ ["commitMs", 0, 5_000],
+ ["layoutEnterMs", 0, 5_000],
+ ["layoutExitMs", 0, 10_000],
+ ["minLayoutLifeMs", 100, 30_000],
+ ["maxLayoutChangesPerMinute", 1, 60],
+ ] as const) {
+ const value = bounded(key, minimum, maximum);
+ if (value !== undefined) updates[key] = value;
+ }
+ return ok("Updated multicam edit policy", await host.multicam.setEditPolicy(groupId, updates));
+ } catch (error) {
+ return fail(error instanceof Error ? error.message : "Invalid edit policy", "INVALID_PARAMS");
+ }
+ },
+ },
+ {
+ name: "annotate_segment",
+ domain: "multicam",
+ title: "Annotate multicam segment",
+ description: "Attach a concise planning note to a bounded multicam time range without modifying cached analysis.",
+ inputSchema: obj({ groupId: str, startMs: num, endMs: num, note: str }, ["groupId", "startMs", "endMs", "note"]),
+ readOnly: false,
+ destructive: false,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const groupId = optionalString(args.groupId);
+ const startMs = optionalNumber(args.startMs);
+ const endMs = optionalNumber(args.endMs);
+ const note = optionalString(args.note);
+ if (!groupId || startMs === undefined || endMs === undefined || startMs < 0 || endMs <= startMs || !note || note.length > 500) {
+ return fail("groupId, a valid millisecond range, and a note of at most 500 characters are required", "INVALID_PARAMS");
+ }
+ return ok("Annotated multicam segment", await host.multicam.annotateSegment({ groupId, startMs, endMs, note }));
+ },
+ },
+ {
+ name: "get_edit_summary",
+ domain: "multicam",
+ title: "Get multicam edit summary",
+ description: "Summarize shots, layouts, pending cut review, annotations, and top deterministic social candidates.",
+ inputSchema: obj({ groupId: str }),
+ readOnly: true,
+ destructive: false,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ return ok("Loaded multicam edit summary", await host.multicam.getEditSummary(optionalString(args.groupId)));
+ },
+ },
+ {
+ name: "override_cut",
+ domain: "multicam",
+ title: "Override multicam cut",
+ description: "Accept, reject, nudge by at most 2 seconds, or assign a valid manifest camera to one generated cut.",
+ inputSchema: obj({
+ groupId: str,
+ switchId: str,
+ operation: { type: "string", enum: ["accept", "reject", "nudge", "set-camera"] },
+ deltaMs: { type: "number", minimum: -2_000, maximum: 2_000 },
+ cameraId: str,
+ }, ["groupId", "switchId", "operation"]),
+ readOnly: false,
+ destructive: true,
+ expensive: false,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const groupId = optionalString(args.groupId);
+ const switchId = optionalString(args.switchId);
+ const operation = optionalString(args.operation);
+ const deltaMs = optionalNumber(args.deltaMs);
+ const cameraId = optionalString(args.cameraId);
+ if (!groupId || !switchId || !operation || !["accept", "reject", "nudge", "set-camera"].includes(operation)) {
+ return fail("groupId, switchId, and a valid operation are required", "INVALID_PARAMS");
+ }
+ if (operation === "nudge" && (deltaMs === undefined || Math.abs(deltaMs) > 2_000)) {
+ return fail("nudge requires deltaMs between -2000 and 2000", "INVALID_PARAMS");
+ }
+ if (operation === "set-camera" && !cameraId) {
+ return fail("set-camera requires cameraId", "INVALID_PARAMS");
+ }
+ return ok("Applied multicam cut override", await host.multicam.overrideCut({
+ groupId,
+ switchId,
+ operation: operation as "accept" | "reject" | "nudge" | "set-camera",
+ deltaMs,
+ cameraId,
+ }));
+ },
+ },
+ {
+ name: "preview_frame",
+ domain: "multicam",
+ title: "Preview multicam frame",
+ description: "Render a frame at a bounded millisecond time for visual inspection of the current multicam edit.",
+ inputSchema: obj({ groupId: str, timeMs: { type: "number", minimum: 0 } }, ["groupId", "timeMs"]),
+ readOnly: true,
+ destructive: false,
+ expensive: true,
+ handler: async (args, host) => {
+ if (!host.multicam) return fail("Multicam tools are unavailable in this host", "UNSUPPORTED");
+ const groupId = optionalString(args.groupId);
+ const timeMs = optionalNumber(args.timeMs);
+ if (!groupId || timeMs === undefined || timeMs < 0) {
+ return fail("groupId and non-negative timeMs are required", "INVALID_PARAMS");
+ }
+ const result = await host.multicam.previewFrame(groupId, timeMs);
+ return result.ok
+ ? ok("Rendered multicam preview frame", result.data)
+ : fail(result.error ?? "Preview frame failed", "PREVIEW_FAILED");
+ },
+ },
+
+ // Local render jobs delegated to the app host and gated as expensive.
jobTool(
"export_video",
"export",
"Export video",
- "Render the whole project to a video file (format: mp4|webm|mov, default mp4), upload it to cloud storage, and return a presigned download URL (data.url, valid ~15 min) plus mediaKey/bytes. Expensive — requires confirmation.",
+ "Render the whole project to a local video file (format: mp4|webm|mov, default mp4) and return its local result metadata. Expensive — requires confirmation.",
"exportVideo",
obj({ format: str }),
),
@@ -31836,18 +32067,10 @@ const TOOLS: RegisteredTool[] = [
"export_audio",
"export",
"Export audio",
- "Render the project audio to a file (format: mp3|wav|aac|flac|ogg, default wav), upload it to cloud storage, and return a presigned download URL (data.url, valid ~15 min). Expensive — requires confirmation.",
+ "Render the project audio to a local file (format: mp3|wav|aac|flac|ogg, default wav) and return its local result metadata. Expensive — requires confirmation.",
"exportAudio",
obj({ format: str }),
),
- jobTool(
- "transcribe_clip",
- "ai",
- "Transcribe clip",
- "Transcribe a clip's audio to text/subtitles via the AI service. Expensive — requires confirmation.",
- "transcribe",
- obj({ clipId: str }, ["clipId"]),
- ),
];
// ---- Registry --------------------------------------------------------------
@@ -31865,6 +32088,12 @@ export function toolDefs(): ToolDef[] {
return listTools().map(({ handler: _handler, ...def }) => def);
}
+function selectedTools(names?: Iterable<string>): RegisteredTool[] {
+ if (!names) return listTools();
+ const selected = new Set(names);
+ return listTools().filter((tool) => selected.has(tool.name));
+}
+
interface NamedToolSchema {
name: string;
description: string;
@@ -31872,8 +32101,8 @@ interface NamedToolSchema {
}
/** Anthropic Messages API tool format. */
-export function toAnthropicTools(): NamedToolSchema[] {
- return listTools().map((t) => ({
+export function toAnthropicTools(names?: Iterable<string>): NamedToolSchema[] {
+ return selectedTools(names).map((t) => ({
name: t.name,
description: t.description,
input_schema: t.inputSchema,
@@ -31881,11 +32110,11 @@ export function toAnthropicTools(): NamedToolSchema[] {
}
/** OpenAI Chat Completions tool format. */
-export function toOpenAITools(): Array<{
+export function toOpenAITools(names?: Iterable<string>): Array<{
type: "function";
function: { name: string; description: string; parameters: JSONSchema };
}> {
- return listTools().map((t) => ({
+ return selectedTools(names).map((t) => ({
type: "function",
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}));
@@ -31905,9 +32134,9 @@ export function toMcpTools(): Array<{
}
/** Human-readable capability reference generated from the registry. */
-export function toCapabilityDoc(): string {
+export function toCapabilityDoc(names?: Iterable<string>): string {
const byDomain = new Map<string, RegisteredTool[]>();
- for (const t of listTools()) {
+ for (const t of selectedTools(names)) {
const arr = byDomain.get(t.domain) ?? [];
arr.push(t);
byDomain.set(t.domain, arr);
diff --git a/packages/agent/src/system-prompt.ts b/packages/agent/src/system-prompt.ts
index 0ffe9ac9..5686882f 100644
--- a/packages/agent/src/system-prompt.ts
+++ b/packages/agent/src/system-prompt.ts
@@ -6,7 +6,10 @@ import { toCapabilityDoc } from "./registry";
* Builds the agent system prompt: tool-usage guidance + the current editor state
* + the capability reference, so the model can plan edits with valid values.
*/
-export function buildSystemPrompt(host: EditingHost): string {
+export function buildSystemPrompt(
+ host: EditingHost,
+ selectedToolNames?: Iterable<string>,
+): string {
let state = "(no project open)";
try {
state = JSON.stringify(serializeEditorState(host.getProject()));
@@ -24,6 +27,8 @@ export function buildSystemPrompt(host: EditingHost): string {
"- Use duplicate_track for timeline-backed video/image/audio tracks. For repeated Motion styling, use transfer_motion_effect_stack or transfer_motion_mask_stack so animated parameters, expressions, ordering, and independent ids are preserved across target layers.",
"- Destructive/expensive tools (delete, remove, export, AI jobs) require user confirmation — explain what you're about to do.",
"- After making the requested edits, stop and summarize what you changed.",
+ "- Write user-facing responses in concise GitHub-flavored Markdown. Prefer short paragraphs and bullets; use tables only when they improve clarity, and fence code or JSON when you need to show it.",
+ "- Do not expose internal chain-of-thought, tool schemas, or raw tool-result JSON. Summarize actions and errors in plain language.",
"",
"Motion Creator (After Effects-style motion graphics):",
"- The motion model is compositions -> layers -> keyframes. A composition has its own size/duration/frameRate, a stack of layers, plus variables, markers, an optional camera, and lights.",
@@ -54,6 +59,6 @@ export function buildSystemPrompt(host: EditingHost): string {
"",
`Current editor state: ${state}`,
"",
- toCapabilityDoc(),
+ toCapabilityDoc(selectedToolNames),
].join("\n");
}
diff --git a/packages/agent/src/tool-router.test.ts b/packages/agent/src/tool-router.test.ts
new file mode 100644
index 00000000..7536290e
--- /dev/null
+++ b/packages/agent/src/tool-router.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from "vitest";
+import { getTool, toOpenAITools } from "./registry";
+import { DEFAULT_AGENT_TOOL_LIMIT, selectToolsForPrompt } from "./tool-router";
+
+describe("agent tool router", () => {
+ it("keeps ordinary timeline editing under provider tool limits", () => {
+ const names = selectToolsForPrompt("Trim the first clip, add captions, and fade the audio");
+ expect(names.length).toBeLessThanOrEqual(DEFAULT_AGENT_TOOL_LIMIT);
+ expect(names).toContain("trim_clip");
+ expect(names).toContain("add_subtitle");
+ expect(names).toContain("set_clip_fade");
+ expect(names).toContain("get_editor_state");
+ expect(names).toContain("execute_action");
+ expect(toOpenAITools(names)).toHaveLength(names.length);
+ });
+
+ it("routes motion requests to motion tools without losing core inspection", () => {
+ const names = selectToolsForPrompt(
+ "Create a motion composition with animated text layers, masks, and keyframes",
+ );
+ expect(names.length).toBeLessThanOrEqual(DEFAULT_AGENT_TOOL_LIMIT);
+ expect(names).toContain("create_motion_composition");
+ expect(names).toContain("add_motion_layer");
+ expect(names).toContain("get_editor_state");
+ expect(names.some((name) => getTool(name)?.domain === "motion")).toBe(true);
+ });
+
+ it("routes 3D product work to semantic creation tools", () => {
+ const names = selectToolsForPrompt(
+ "Build a cinematic 3D product scene with an exploded view and brushed metal materials",
+ );
+ expect(names.length).toBeLessThanOrEqual(DEFAULT_AGENT_TOOL_LIMIT);
+ expect(names).toContain("create_product_cinematic_scene");
+ expect(names).toContain("animate_creation_exploded_view");
+ expect(names).toContain("apply_creation_material_preset");
+ });
+
+ it("retains tools used earlier in a follow-up conversation", () => {
+ const names = selectToolsForPrompt("Make it slower", {
+ maxTools: 20,
+ priorToolNames: ["animate_layer"],
+ });
+ expect(names).toContain("animate_layer");
+ });
+});
diff --git a/packages/agent/src/tool-router.ts b/packages/agent/src/tool-router.ts
new file mode 100644
index 00000000..268bb75a
--- /dev/null
+++ b/packages/agent/src/tool-router.ts
@@ -0,0 +1,99 @@
+import { listTools } from "./registry";
+import type { RegisteredTool } from "./registry";
+
+/** Leave headroom below provider limits for future built-in/meta tools. */
+export const DEFAULT_AGENT_TOOL_LIMIT = 120;
+
+const ALWAYS_AVAILABLE = new Set([
+ "get_editor_state",
+ "list_media",
+ "list_tracks",
+ "list_clips",
+ "get_clip",
+ "get_capabilities",
+ "create_project",
+ "list_projects",
+ "open_project",
+ "save_project",
+ "list_motion_compositions",
+ "get_motion_composition",
+ "create_motion_composition",
+ "add_motion_layer",
+ "add_motion_layers",
+ "set_motion_layer_transform",
+ "animate_layer",
+ "remove_motion_layer",
+ "render_motion_frame",
+ "insert_motion_into_editor",
+ "execute_action",
+ "batch_actions",
+]);
+
+const MOTION_TERMS = /\b(motion|composition|layer|keyframe|animate|animation|after effects|lower third|title card|kinetic|lottie|svg|figma|particle|shader|mask|matte|precomp|camera|render frame)\b/i;
+const CREATION_TERMS = /\b(3d|three[- ]?d|product|character|scene|model|gltf|glb|rig|mesh|material|texture|bevel|displacement|x[- ]?ray|cloth|camera module|exploded|cinematic|decal|cutaway)\b/i;
+
+const words = (value: string): string[] =>
+ value
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, " ")
+ .split(/\s+/)
+ .filter((word) => word.length >= 3);
+
+function relevance(tool: RegisteredTool, promptWords: Set<string>): number {
+ if (ALWAYS_AVAILABLE.has(tool.name)) return 10_000;
+ const name = new Set(words(tool.name));
+ const title = new Set(words(tool.title));
+ const description = new Set(words(tool.description));
+ let score = tool.readOnly ? 12 : 0;
+ for (const word of promptWords) {
+ if (name.has(word)) score += 18;
+ if (title.has(word)) score += 10;
+ if (description.has(word)) score += 2;
+ }
+ return score;
+}
+
+function isCreationTool(tool: RegisteredTool): boolean {
+ const haystack = `${tool.name} ${tool.title} ${tool.description}`;
+ return /creation|3d|scene3d|gltf|glb|rigging|humanoid|product cinematic/i.test(haystack);
+}
+
+/**
+ * Route a user request to a provider-safe subset of the full editor registry.
+ * The registry remains authoritative and executable; routing only limits the
+ * function schemas sent on this turn so large registries stay within provider
+ * limits and do not waste the user's context window.
+ */
+export function selectToolsForPrompt(
+ prompt: string,
+ options: { readonly maxTools?: number; readonly priorToolNames?: readonly string[] } = {},
+): string[] {
+ const maxTools = Math.max(1, options.maxTools ?? DEFAULT_AGENT_TOOL_LIMIT);
+ const wantsMotion = MOTION_TERMS.test(prompt);
+ const wantsCreation = CREATION_TERMS.test(prompt);
+ const prior = new Set(options.priorToolNames ?? []);
+ const promptWords = new Set(words(prompt));
+
+ const candidates = listTools().filter((tool) => {
+ if (ALWAYS_AVAILABLE.has(tool.name) || prior.has(tool.name)) return true;
+ if (!wantsMotion && !wantsCreation) return tool.domain !== "motion";
+ if (wantsCreation && isCreationTool(tool)) return true;
+ if (wantsMotion && tool.domain === "motion" && !isCreationTool(tool)) return true;
+ return tool.domain === "read" || ["project", "media", "export", "raw"].includes(tool.domain);
+ });
+
+ return candidates
+ .map((tool, index) => ({
+ tool,
+ index,
+ score:
+ relevance(tool, promptWords) +
+ (prior.has(tool.name) ? 5_000 : 0) +
+ (wantsCreation && isCreationTool(tool) ? 100 : 0) +
+ (wantsMotion && tool.domain === "motion" ? 50 : 0),
+ }))
+ .sort((a, b) => b.score - a.score || a.index - b.index)
+ .slice(0, maxTools)
+ .sort((a, b) => a.index - b.index)
+ .map(({ tool }) => tool.name);
+}
diff --git a/packages/agent/src/types.ts b/packages/agent/src/types.ts
index 1bb4413a..518f0960 100644
--- a/packages/agent/src/types.ts
+++ b/packages/agent/src/types.ts
@@ -20,6 +20,7 @@ export type ToolDomain =
| "marker"
| "ai"
| "export"
+ | "multicam"
| "raw";
export interface ToolDef {
diff --git a/packages/core/package.json b/packages/core/package.json
index bf942bb7..f1e7048a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -44,8 +44,10 @@
"idb-keyval": "^6.2.2",
"immer": "^11.0.1",
"mediabunny": "^1.25.3",
+ "onnxruntime-web": "1.21.0",
"polygon-clipping": "0.15.7",
"three": "^0.182.0",
- "uuid": "^13.0.0"
+ "uuid": "^13.0.0",
+ "yaml": "^2.4.2"
}
}
diff --git a/packages/core/src/actions/action-executor.test.ts b/packages/core/src/actions/action-executor.test.ts
index 7a8881fc..2c6f2cf0 100644
--- a/packages/core/src/actions/action-executor.test.ts
+++ b/packages/core/src/actions/action-executor.test.ts
@@ -153,7 +153,8 @@ describe("ActionExecutor transform/update", () => {
it("deep-merges a partial axis (does not drop the other) and round-trips", async () => {
const executor = new ActionExecutor();
const project = makeProjectWithClip();
- const before = JSON.stringify(project);
+ const beforeTimeline = JSON.stringify(project.timeline);
+ const beforeModifiedAt = project.modifiedAt;
const result = await executor.execute(
{
@@ -169,9 +170,53 @@ describe("ActionExecutor transform/update", () => {
x: 100,
y: 0,
});
+ expect(project.modifiedAt).toBeGreaterThan(beforeModifiedAt);
await executor.undo(project);
- expect(JSON.stringify(project)).toBe(before);
+ expect(JSON.stringify(project.timeline)).toBe(beforeTimeline);
+ });
+
+ it("keeps one visual clip while moving it and fully removes it", async () => {
+ const executor = new ActionExecutor();
+ const project = makeProjectWithClip();
+ (project.timeline.tracks[0] as { type: string }).type = "image";
+
+ const beforeMove = project.modifiedAt;
+ const move = await executor.execute(
+ {
+ id: "move-image",
+ type: "clip/move",
+ params: { clipId: "c1", startTime: 2 },
+ timestamp: Date.now(),
+ } as Action,
+ project,
+ );
+
+ expect(move.success).toBe(true);
+ expect(
+ project.timeline.tracks.flatMap((track) => track.clips).filter(
+ (clip) => clip.id === "c1",
+ ),
+ ).toHaveLength(1);
+ expect(project.timeline.tracks[0].clips[0].startTime).toBe(2);
+ expect(project.modifiedAt).toBeGreaterThan(beforeMove);
+
+ const remove = await executor.execute(
+ {
+ id: "remove-image",
+ type: "clip/remove",
+ params: { clipId: "c1" },
+ timestamp: Date.now(),
+ } as Action,
+ project,
+ );
+
+ expect(remove.success).toBe(true);
+ expect(
+ project.timeline.tracks.flatMap((track) => track.clips).filter(
+ (clip) => clip.id === "c1",
+ ),
+ ).toHaveLength(0);
});
});
@@ -445,16 +490,27 @@ describe("ActionExecutor track/rename", () => {
describe("ActionExecutor track/duplicate", () => {
it("duplicates clips and remaps transition references with one-step undo", async () => {
const executor = new ActionExecutor();
- const project = makeProjectWithTransitions([
- {
- id: "transition-source",
- clipAId: "c1",
- clipBId: "c2",
- type: "crossfade",
- duration: 1,
- params: {},
- },
- ]);
+ const project = {
+ ...makeProjectWithTransitions([
+ {
+ id: "transition-source",
+ clipAId: "c1",
+ clipBId: "c2",
+ type: "crossfade",
+ duration: 1,
+ params: {},
+ },
+ ]),
+ textClips: [
+ {
+ id: "text-source",
+ trackId: "t1",
+ startTime: 1,
+ duration: 2,
+ text: "Mixed track title",
+ },
+ ],
+ } as unknown as Project;
const result = await executor.execute(
{
@@ -483,13 +539,68 @@ describe("ActionExecutor track/duplicate", () => {
clipBId: duplicate.clips[1].id,
});
expect(duplicate.transitions[0].id).not.toBe("transition-source");
+ expect(project.textClips).toHaveLength(2);
+ const duplicatedText = project.textClips?.find(
+ (item) => item.id !== "text-source",
+ );
+ expect(duplicatedText?.trackId).toBe(duplicate.id);
+ const duplicatedTextId = duplicatedText?.id;
await executor.undo(project);
expect(project.timeline.tracks).toHaveLength(1);
+ expect(project.textClips?.map((item) => item.id)).toEqual(["text-source"]);
await executor.redo(project);
expect(project.timeline.tracks).toHaveLength(2);
expect(project.timeline.tracks[1].name).toBe("V1 Copy");
+ expect(project.textClips?.find((item) => item.trackId === duplicate.id)?.id).toBe(
+ duplicatedTextId,
+ );
+ });
+
+ it("removes and restores project-level items owned by a track", async () => {
+ const executor = new ActionExecutor();
+ const project = {
+ ...makeProjectWithTransitions(),
+ shapeClips: [
+ {
+ id: "shape-source",
+ trackId: "t1",
+ startTime: 1,
+ duration: 2,
+ type: "shape",
+ },
+ ],
+ motionInstances: [
+ {
+ id: "motion-source",
+ compositionId: "composition-1",
+ trackId: "t1",
+ startTime: 3,
+ duration: 2,
+ },
+ ],
+ } as unknown as Project;
+
+ const result = await executor.execute(
+ {
+ id: "remove-mixed-track",
+ type: "track/remove",
+ params: { trackId: "t1" },
+ timestamp: Date.now(),
+ },
+ project,
+ );
+
+ expect(result.success).toBe(true);
+ expect(project.timeline.tracks).toHaveLength(0);
+ expect(project.shapeClips).toEqual([]);
+ expect(project.motionInstances).toEqual([]);
+
+ await executor.undo(project);
+ expect(project.timeline.tracks).toHaveLength(1);
+ expect(project.shapeClips?.[0]?.id).toBe("shape-source");
+ expect(project.motionInstances?.[0]?.id).toBe("motion-source");
});
});
diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.ts
index cd23c65f..f7fbf903 100644
--- a/packages/core/src/actions/action-executor.ts
+++ b/packages/core/src/actions/action-executor.ts
@@ -35,6 +35,10 @@ import type {
} from "../utils/immutable-updates";
import type { BlendMode } from "../video/types";
import type { EmphasisAnimation } from "../graphics/types";
+import type { ShapeClip, StickerClip, SVGClip } from "../graphics/types";
+import type { TextClip } from "../text/types";
+import type { AdjustmentLayer } from "../video/adjustment-layer-engine";
+import type { MotionCompositionInstance } from "../motion/types";
import type { ClipColorGrading } from "../video/color-grading-engine";
import {
registerMotionShader,
@@ -49,6 +53,79 @@ import { getActionHandler } from "./registry";
import "./handlers";
import { calculateProjectDuration } from "../timeline/project-duration";
+interface MutableProjectItems {
+ textClips?: TextClip[];
+ shapeClips?: ShapeClip[];
+ svgClips?: SVGClip[];
+ stickerClips?: StickerClip[];
+ adjustmentLayers?: AdjustmentLayer[];
+ motionInstances?: MotionCompositionInstance[];
+}
+
+interface TrackOwnedItems {
+ textClips: TextClip[];
+ shapeClips: ShapeClip[];
+ svgClips: SVGClip[];
+ stickerClips: StickerClip[];
+ adjustmentLayers: AdjustmentLayer[];
+ motionInstances: MotionCompositionInstance[];
+}
+
+function getTrackOwnedItems(project: Project, trackId: string): TrackOwnedItems {
+ return {
+ textClips: (project.textClips ?? []).filter((item) => item.trackId === trackId),
+ shapeClips: (project.shapeClips ?? []).filter((item) => item.trackId === trackId),
+ svgClips: (project.svgClips ?? []).filter((item) => item.trackId === trackId),
+ stickerClips: (project.stickerClips ?? []).filter(
+ (item) => item.trackId === trackId,
+ ),
+ adjustmentLayers: (project.adjustmentLayers ?? []).filter(
+ (item) => item.trackId === trackId,
+ ),
+ motionInstances: (project.motionInstances ?? []).filter(
+ (item) => item.trackId === trackId,
+ ),
+ };
+}
+
+function removeTrackOwnedItems(project: Project, trackId: string): void {
+ const mutable = project as Project & MutableProjectItems;
+ mutable.textClips = (project.textClips ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+ mutable.shapeClips = (project.shapeClips ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+ mutable.svgClips = (project.svgClips ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+ mutable.stickerClips = (project.stickerClips ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+ mutable.adjustmentLayers = (project.adjustmentLayers ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+ mutable.motionInstances = (project.motionInstances ?? []).filter(
+ (item) => item.trackId !== trackId,
+ );
+}
+
+function restoreTrackOwnedItems(project: Project, items: TrackOwnedItems): void {
+ const mutable = project as Project & MutableProjectItems;
+ mutable.textClips = [...(project.textClips ?? []), ...items.textClips];
+ mutable.shapeClips = [...(project.shapeClips ?? []), ...items.shapeClips];
+ mutable.svgClips = [...(project.svgClips ?? []), ...items.svgClips];
+ mutable.stickerClips = [...(project.stickerClips ?? []), ...items.stickerClips];
+ mutable.adjustmentLayers = [
+ ...(project.adjustmentLayers ?? []),
+ ...items.adjustmentLayers,
+ ];
+ mutable.motionInstances = [
+ ...(project.motionInstances ?? []),
+ ...items.motionInstances,
+ ];
+}
+
export class ActionExecutor {
private validator: ActionValidator;
private history: ActionHistory;
@@ -251,6 +328,7 @@ export class ActionExecutor {
lastAddedIds: this.lastAddedIds,
});
this.recalculateTimelineDuration(project);
+ this.markProjectModified(project);
return;
}
@@ -280,6 +358,7 @@ export class ActionExecutor {
// Recompute timeline duration from clips after any action that may affect it
this.recalculateTimelineDuration(project);
+ this.markProjectModified(project);
}
private recalculateTimelineDuration(project: Project): void {
@@ -287,6 +366,10 @@ export class ActionExecutor {
calculateProjectDuration(project);
}
+ private markProjectModified(project: Project): void {
+ (project as { modifiedAt: number }).modifiedAt = Date.now();
+ }
+
private applyProjectAction(action: ProjectAction, project: Project): void {
switch (action.type) {
case "project/rename":
@@ -422,6 +505,9 @@ export class ActionExecutor {
trackType: string;
position?: number;
trackId?: string;
+ mode?: "standard";
+ role?: Track["role"];
+ name?: string;
};
const trackNames: Record<string, string> = {
video: "Video",
@@ -431,13 +517,23 @@ export class ActionExecutor {
graphics: "Graphics",
};
const trackCount =
- timeline.tracks.filter(
- (t: MutableTrack) => t.type === params.trackType,
+ timeline.tracks.filter((track: MutableTrack) =>
+ params.mode === "standard"
+ ? track.mode === "standard"
+ : track.type === params.trackType,
).length + 1;
const newTrack: MutableTrack = {
id: params.trackId ?? `track-${crypto.randomUUID()}`,
type: params.trackType as Track["type"],
- name: `${trackNames[params.trackType] || params.trackType} ${trackCount}`,
+ mode: params.mode,
+ role: params.role,
+ name:
+ params.name ??
+ `${
+ params.mode === "standard"
+ ? "Track"
+ : trackNames[params.trackType] || params.trackType
+ } ${trackCount}`,
clips: [],
transitions: [],
locked: false,
@@ -465,6 +561,8 @@ export class ActionExecutor {
sourceTrackId: string;
position?: number;
trackId?: string;
+ itemIdMap?: Record<string, string>;
+ transitionIdMap?: Record<string, string>;
};
const sourceIndex = timeline.tracks.findIndex(
(track: MutableTrack) => track.id === params.sourceTrackId,
@@ -472,12 +570,33 @@ export class ActionExecutor {
if (sourceIndex < 0) break;
const source = timeline.tracks[sourceIndex];
const trackId = params.trackId ?? `track-${crypto.randomUUID()}`;
- const clipIdMap = new Map(
- source.clips.map((clip) => [
- clip.id,
- `clip-${crypto.randomUUID()}`,
+ params.trackId = trackId;
+ const ownedItems = getTrackOwnedItems(project, source.id);
+ const sourceItemIds = [
+ ...source.clips.map((clip) => clip.id),
+ ...ownedItems.textClips.map((item) => item.id),
+ ...ownedItems.shapeClips.map((item) => item.id),
+ ...ownedItems.svgClips.map((item) => item.id),
+ ...ownedItems.stickerClips.map((item) => item.id),
+ ...ownedItems.adjustmentLayers.map((item) => item.id),
+ ...ownedItems.motionInstances.map((item) => item.id),
+ ];
+ params.itemIdMap ??= Object.fromEntries(
+ sourceItemIds.map((id) => [id, `item-${crypto.randomUUID()}`]),
+ );
+ params.transitionIdMap ??= Object.fromEntries(
+ source.transitions.map((transition) => [
+ transition.id,
+ `transition-${crypto.randomUUID()}`,
]),
);
+ const duplicateItem = <T extends { id: string; trackId?: string }>(
+ item: T,
+ ): T => ({
+ ...structuredClone(item),
+ id: params.itemIdMap![item.id]!,
+ trackId,
+ });
const names = new Set(timeline.tracks.map((track) => track.name));
const baseName = `${source.name} Copy`;
let name = baseName;
@@ -492,16 +611,16 @@ export class ActionExecutor {
name,
clips: source.clips.map((clip) => ({
...structuredClone(clip),
- id: clipIdMap.get(clip.id)!,
+ id: params.itemIdMap![clip.id]!,
trackId,
})),
transitions: source.transitions.map((transition) => ({
...structuredClone(transition),
- id: `transition-${crypto.randomUUID()}`,
+ id: params.transitionIdMap![transition.id]!,
clipAId:
- clipIdMap.get(transition.clipAId) ?? transition.clipAId,
+ params.itemIdMap![transition.clipAId] ?? transition.clipAId,
clipBId: transition.clipBId
- ? (clipIdMap.get(transition.clipBId) ?? transition.clipBId)
+ ? (params.itemIdMap![transition.clipBId] ?? transition.clipBId)
: undefined,
})),
};
@@ -511,6 +630,22 @@ export class ActionExecutor {
duplicate,
...timeline.tracks.slice(position),
];
+ restoreTrackOwnedItems(project, {
+ textClips: ownedItems.textClips.map(duplicateItem),
+ shapeClips: ownedItems.shapeClips.map(duplicateItem),
+ svgClips: ownedItems.svgClips.map(duplicateItem),
+ stickerClips: ownedItems.stickerClips.map(duplicateItem),
+ adjustmentLayers: ownedItems.adjustmentLayers.map((layer) => ({
+ ...duplicateItem(layer),
+ affectedTracks:
+ layer.affectedTracks === "all"
+ ? "all"
+ : layer.affectedTracks.map((affectedTrackId) =>
+ affectedTrackId === source.id ? trackId : affectedTrackId,
+ ),
+ })),
+ motionInstances: ownedItems.motionInstances.map(duplicateItem),
+ });
this.lastAddedIds.set("track", trackId);
break;
}
@@ -520,16 +655,24 @@ export class ActionExecutor {
timeline.tracks = timeline.tracks.filter(
(t: MutableTrack) => t.id !== params.trackId,
);
+ removeTrackOwnedItems(project, params.trackId);
break;
}
case "track/restore": {
- const params = action.params as { track: Track; position: number };
+ const params = action.params as {
+ track: Track;
+ position: number;
+ items?: TrackOwnedItems;
+ };
timeline.tracks = [
...timeline.tracks.slice(0, params.position),
params.track,
...timeline.tracks.slice(params.position),
];
+ if (params.items) {
+ restoreTrackOwnedItems(project, params.items);
+ }
break;
}
@@ -672,6 +815,7 @@ export class ActionExecutor {
reversed?: boolean;
audioTrackIndex?: number;
sourceClip?: Clip;
+ clipId?: string;
};
const track = timeline.tracks.find(
(t: MutableTrack) => t.id === params.trackId,
@@ -698,12 +842,12 @@ export class ActionExecutor {
const newClip = params.sourceClip
? {
...structuredClone(params.sourceClip),
- id: crypto.randomUUID(),
+ id: params.clipId ?? crypto.randomUUID(),
trackId: params.trackId,
startTime: params.startTime,
}
: {
- id: crypto.randomUUID(),
+ id: params.clipId ?? crypto.randomUUID(),
mediaId: params.mediaId,
trackId: params.trackId,
startTime: params.startTime,
@@ -726,6 +870,7 @@ export class ActionExecutor {
? { audioTrackIndex: params.audioTrackIndex }
: {}),
};
+ params.clipId = newClip.id;
track.clips = [...track.clips, newClip];
this.lastAddedIds.set("clip", newClip.id);
}
diff --git a/packages/core/src/actions/action-history.ts b/packages/core/src/actions/action-history.ts
index 3f20daed..a88fda72 100644
--- a/packages/core/src/actions/action-history.ts
+++ b/packages/core/src/actions/action-history.ts
@@ -139,6 +139,7 @@ export class ActionHistory {
private redoStack: HistoryEntry[] = [];
private maxHistorySize: number;
private currentGroupId: string | null = null;
+ private groupDepth = 0;
private snapshots: HistorySnapshot[] = [];
private listeners: Set<() => void> = new Set();
private lastActionTime: number = 0;
@@ -217,11 +218,21 @@ export class ActionHistory {
}
beginGroup(_description?: string): string {
+ if (this.currentGroupId) {
+ this.groupDepth += 1;
+ return this.currentGroupId;
+ }
this.currentGroupId = `group-${Date.now()}`;
+ this.groupDepth = 1;
return this.currentGroupId;
}
endGroup(): void {
+ if (this.groupDepth > 1) {
+ this.groupDepth -= 1;
+ return;
+ }
+ this.groupDepth = 0;
this.currentGroupId = null;
this.notify();
}
@@ -363,6 +374,7 @@ export class ActionHistory {
this.redoStack = [];
this.snapshots = [];
this.currentGroupId = null;
+ this.groupDepth = 0;
this.notify();
}
diff --git a/packages/core/src/actions/handlers/index.ts b/packages/core/src/actions/handlers/index.ts
index d8c8aecd..82ac368d 100644
--- a/packages/core/src/actions/handlers/index.ts
+++ b/packages/core/src/actions/handlers/index.ts
@@ -3,3 +3,4 @@ import "./bulk-set";
import "./overlay";
import "./motion";
import "./creation";
+import "./multicam";
diff --git a/packages/core/src/actions/handlers/multicam.test.ts b/packages/core/src/actions/handlers/multicam.test.ts
new file mode 100644
index 00000000..f738ecee
--- /dev/null
+++ b/packages/core/src/actions/handlers/multicam.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+import { ActionExecutor } from "../action-executor";
+import type { Action } from "../../types/actions";
+import type { Project } from "../../types/project";
+import type { Track } from "../../types/timeline";
+
+const track = (id: string, updates: Partial<Track> = {}): Track => ({
+ id,
+ type: "video",
+ name: id,
+ clips: [],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ ...updates,
+});
+
+const project = (): Project => ({
+ id: "p",
+ name: "p",
+ createdAt: 0,
+ modifiedAt: 0,
+ settings: { width: 1920, height: 1080, frameRate: 25, sampleRate: 48_000, channels: 2 },
+ mediaLibrary: { items: [] },
+ timeline: { tracks: [track("a"), track("b")], subtitles: [], markers: [], duration: 0 },
+});
+
+describe("multicam/applyEdit", () => {
+ it("atomically replaces output, hides sources, persists metadata, and undoes", async () => {
+ const value = project();
+ const executor = new ActionExecutor();
+ const action: Action = {
+ type: "multicam/applyEdit",
+ id: "apply",
+ timestamp: 1,
+ params: {
+ outputTrack: track("output"),
+ outputTrackPosition: 1,
+ sourceTrackIds: ["a", "b"],
+ groups: [{ id: "group", angles: [] }],
+ },
+ };
+
+ expect((await executor.execute(action, value)).success).toBe(true);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual(["a", "output", "b"]);
+ expect(value.timeline.tracks.filter((entry) => entry.id !== "output").every(
+ (entry) => entry.hidden && entry.muted,
+ )).toBe(true);
+ expect(value.multicamGroups?.[0]?.id).toBe("group");
+
+ expect((await executor.undo(value)).success).toBe(true);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual(["a", "b"]);
+ expect(value.timeline.tracks.every((entry) => !entry.hidden && !entry.muted)).toBe(true);
+ expect(value.multicamGroups).toEqual([]);
+
+ expect((await executor.redo(value)).success).toBe(true);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual(["a", "output", "b"]);
+ });
+
+ it("rejects clips assigned to a different track", async () => {
+ const value = project();
+ const executor = new ActionExecutor();
+ const result = await executor.execute({
+ type: "multicam/applyEdit",
+ id: "invalid",
+ timestamp: 1,
+ params: {
+ outputTrack: track("output", { clips: [{ trackId: "other" }] as Track["clips"] }),
+ sourceTrackIds: ["a", "b"],
+ groups: [],
+ },
+ }, value);
+
+ expect(result.success).toBe(false);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual(["a", "b"]);
+ });
+
+ it("owns every generated panel track in the same undo step", async () => {
+ const value = project();
+ const executor = new ActionExecutor();
+ const result = await executor.execute({
+ type: "multicam/applyEdit",
+ id: "panels",
+ timestamp: 1,
+ params: {
+ outputTracks: [track("panel-1"), track("panel-2")],
+ sourceTrackIds: ["a", "b"],
+ groups: [],
+ },
+ }, value);
+
+ expect(result.success).toBe(true);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual([
+ "panel-1", "panel-2", "a", "b",
+ ]);
+ await executor.undo(value);
+ expect(value.timeline.tracks.map((entry) => entry.id)).toEqual(["a", "b"]);
+ });
+});
diff --git a/packages/core/src/actions/handlers/multicam.ts b/packages/core/src/actions/handlers/multicam.ts
new file mode 100644
index 00000000..384b9509
--- /dev/null
+++ b/packages/core/src/actions/handlers/multicam.ts
@@ -0,0 +1,143 @@
+import type { Action, ValidationResult } from "../../types/actions";
+import type { Project } from "../../types/project";
+import type { Track } from "../../types/timeline";
+import type { MultiCamGroup } from "../../video/multicam-engine";
+import type { ActionHandler } from "../registry";
+import { registerActionHandler } from "../registry";
+
+interface ApplyMulticamEditParams {
+ outputTrack?: Track;
+ outputTracks?: Track[];
+ outputTrackPosition?: number;
+ sourceTrackIds: string[];
+ groups: MultiCamGroup[];
+}
+
+interface RestoreMulticamEditParams {
+ outputTrackIds: string[];
+ priorOutputTracks: Array<{ track: Track; position: number }>;
+ sourceTrackStates: Array<{ trackId: string; hidden: boolean; muted: boolean }>;
+ groups: MultiCamGroup[];
+}
+
+function outputTracks(params: ApplyMulticamEditParams): Track[] {
+ return params.outputTracks ?? (params.outputTrack ? [params.outputTrack] : []);
+}
+
+function invalid(message: string): ValidationResult {
+ return { valid: false, errors: [{ code: "INVALID_PARAMS", message }] };
+}
+
+function applyEdit(
+ project: Project,
+ params: ApplyMulticamEditParams,
+): void {
+ const outputs = outputTracks(params);
+ const outputIds = new Set(outputs.map((track) => track.id));
+ const sourceIds = new Set(params.sourceTrackIds);
+ const withoutOutput = project.timeline.tracks
+ .filter((track) => !outputIds.has(track.id))
+ .map((track) =>
+ sourceIds.has(track.id)
+ ? { ...track, hidden: true, muted: true }
+ : track,
+ );
+ const position = Math.max(
+ 0,
+ Math.min(params.outputTrackPosition ?? 0, withoutOutput.length),
+ );
+ const tracks = [...withoutOutput];
+ tracks.splice(position, 0, ...structuredClone(outputs));
+ Object.assign(project.timeline as unknown as Record<string, unknown>, { tracks });
+ Object.assign(project as unknown as Record<string, unknown>, {
+ multicamGroups: structuredClone(params.groups),
+ });
+}
+
+const applyMulticamEdit: ActionHandler = {
+ type: "multicam/applyEdit",
+ validate(action: Action, project: Project): ValidationResult {
+ const params = action.params as unknown as Partial<ApplyMulticamEditParams>;
+ const outputs = outputTracks(params as ApplyMulticamEditParams);
+ if (!outputs.length || outputs.some((track) => typeof track.id !== "string")) {
+ return invalid("multicam/applyEdit requires at least one output track");
+ }
+ if (outputs.some((track) => track.type !== "video")) {
+ return invalid("multicam outputs must be video tracks");
+ }
+ if (outputs.some((track) => !Array.isArray(track.clips) || track.clips.some(
+ (clip) => clip.trackId !== track.id,
+ ))) {
+ return invalid("every multicam clip must target the output track");
+ }
+ if (!Array.isArray(params.sourceTrackIds) || !Array.isArray(params.groups)) {
+ return invalid("multicam/applyEdit requires source tracks and groups");
+ }
+ const knownTrackIds = new Set(project.timeline.tracks.map((track) => track.id));
+ const unknown = params.sourceTrackIds.find((id) => !knownTrackIds.has(id));
+ return unknown ? invalid(`multicam source track not found: ${unknown}`) : { valid: true, errors: [] };
+ },
+ apply(action: Action, project: Project): void {
+ applyEdit(project, action.params as unknown as ApplyMulticamEditParams);
+ },
+ invert(action: Action, projectBefore: Project): Action | null {
+ const params = action.params as unknown as ApplyMulticamEditParams;
+ const outputIds = outputTracks(params).map((track) => track.id);
+ const priorOutputTracks = projectBefore.timeline.tracks.flatMap((track, position) =>
+ outputIds.includes(track.id) ? [{ track: structuredClone(track), position }] : [],
+ );
+ return {
+ type: "multicam/restoreEdit",
+ id: `inverse-${action.id}`,
+ timestamp: Date.now(),
+ params: {
+ outputTrackIds: outputIds,
+ priorOutputTracks,
+ sourceTrackStates: params.sourceTrackIds.flatMap((trackId) => {
+ const track = projectBefore.timeline.tracks.find((entry) => entry.id === trackId);
+ return track
+ ? [{ trackId, hidden: track.hidden, muted: track.muted }]
+ : [];
+ }),
+ groups: structuredClone(projectBefore.multicamGroups ?? []),
+ },
+ };
+ },
+};
+
+const restoreMulticamEdit: ActionHandler = {
+ type: "multicam/restoreEdit",
+ validate(action: Action): ValidationResult {
+ const params = action.params as unknown as Partial<RestoreMulticamEditParams>;
+ return Array.isArray(params.outputTrackIds) && Array.isArray(params.groups)
+ ? { valid: true, errors: [] }
+ : invalid("multicam/restoreEdit requires a prior edit snapshot");
+ },
+ apply(action: Action, project: Project): void {
+ const params = action.params as unknown as RestoreMulticamEditParams;
+ const states = new Map(params.sourceTrackStates.map((entry) => [entry.trackId, entry]));
+ const tracks = project.timeline.tracks
+ .filter((track) => !params.outputTrackIds.includes(track.id))
+ .map((track) => {
+ const state = states.get(track.id);
+ return state ? { ...track, hidden: state.hidden, muted: state.muted } : track;
+ });
+ for (const entry of [...params.priorOutputTracks].sort((left, right) => left.position - right.position)) {
+ tracks.splice(
+ Math.max(0, Math.min(entry.position, tracks.length)),
+ 0,
+ structuredClone(entry.track),
+ );
+ }
+ Object.assign(project.timeline as unknown as Record<string, unknown>, { tracks });
+ Object.assign(project as unknown as Record<string, unknown>, {
+ multicamGroups: structuredClone(params.groups),
+ });
+ },
+ invert(): Action | null {
+ return null;
+ },
+};
+
+registerActionHandler(applyMulticamEdit);
+registerActionHandler(restoreMulticamEdit);
diff --git a/packages/core/src/actions/inverse-action-generator.ts b/packages/core/src/actions/inverse-action-generator.ts
index bd2d12cb..f9a91d12 100644
--- a/packages/core/src/actions/inverse-action-generator.ts
+++ b/packages/core/src/actions/inverse-action-generator.ts
@@ -15,8 +15,20 @@ import type {
} from "../types/actions";
import type { Project, MediaItem } from "../types/project";
import type { Track, Clip, Transition } from "../types/timeline";
+import type { TextClip } from "../text/types";
+import type { ShapeClip, StickerClip, SVGClip } from "../graphics/types";
+import type { AdjustmentLayer } from "../video/adjustment-layer-engine";
+import type { MotionCompositionInstance } from "../motion/types";
import { getActionHandler } from "./registry";
+type TrackOwnedProjectItem =
+ | TextClip
+ | ShapeClip
+ | SVGClip
+ | StickerClip
+ | AdjustmentLayer
+ | MotionCompositionInstance;
+
export class InverseActionGenerator {
generate(action: Action, projectBefore: Project): Action | null {
const type = (action as TimelineAction).type;
@@ -256,6 +268,26 @@ export class InverseActionGenerator {
return this.createInverseAction(action, "track/restore", {
track: this.cloneTrack(removedTrack),
position,
+ items: {
+ textClips: this.cloneTrackItems(projectBefore.textClips, action.params.trackId),
+ shapeClips: this.cloneTrackItems(
+ projectBefore.shapeClips,
+ action.params.trackId,
+ ),
+ svgClips: this.cloneTrackItems(projectBefore.svgClips, action.params.trackId),
+ stickerClips: this.cloneTrackItems(
+ projectBefore.stickerClips,
+ action.params.trackId,
+ ),
+ adjustmentLayers: this.cloneTrackItems(
+ projectBefore.adjustmentLayers,
+ action.params.trackId,
+ ),
+ motionInstances: this.cloneTrackItems(
+ projectBefore.motionInstances,
+ action.params.trackId,
+ ),
+ },
});
}
@@ -844,17 +876,20 @@ export class InverseActionGenerator {
};
}
+ private cloneTrackItems<T extends TrackOwnedProjectItem>(
+ items: readonly T[] | undefined,
+ trackId: string,
+ ): T[] {
+ return (items ?? [])
+ .filter((item) => item.trackId === trackId)
+ .map((item) => structuredClone(item));
+ }
+
private cloneTrack(track: Track): Record<string, unknown> {
return {
- id: track.id,
- type: track.type,
- name: track.name,
+ ...(track as unknown as Record<string, unknown>),
clips: track.clips.map((c) => this.cloneClip(c)),
transitions: track.transitions?.map((t) => ({ ...t })) ?? [],
- locked: track.locked,
- hidden: track.hidden,
- muted: track.muted,
- solo: track.solo,
};
}
diff --git a/packages/core/src/ai/cloud-job-types.test.ts b/packages/core/src/ai/cloud-job-types.test.ts
deleted file mode 100644
index 48c59ba4..00000000
--- a/packages/core/src/ai/cloud-job-types.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- AI_CLOUD_JOB_KINDS,
- isTerminalStatus,
- MEDIA_OPTIONAL_KINDS,
- artifactIsImage,
- artifactIsVideo,
- artifactIsAudio,
-} from "./cloud-job-types";
-
-describe("cloud-job-types", () => {
- it("uses snake_case wire values for kinds", () => {
- expect(AI_CLOUD_JOB_KINDS.aiHighlight).toBe("ai_highlight");
- expect(AI_CLOUD_JOB_KINDS.backgroundRemoval).toBe("background_removal");
- expect(AI_CLOUD_JOB_KINDS.upscale).toBe("upscale");
- expect(Object.keys(AI_CLOUD_JOB_KINDS).length).toBe(25);
- });
- it("marks completed/failed/cancelled terminal", () => {
- expect(isTerminalStatus("completed")).toBe(true);
- expect(isTerminalStatus("failed")).toBe(true);
- expect(isTerminalStatus("cancelled")).toBe(true);
- expect(isTerminalStatus("processing")).toBe(false);
- expect(isTerminalStatus("queued")).toBe(false);
- expect(isTerminalStatus("uploading")).toBe(false);
- });
- it("knows media-optional kinds", () => {
- expect(MEDIA_OPTIONAL_KINDS.has("music_generation")).toBe(true);
- expect(MEDIA_OPTIONAL_KINDS.has("translation")).toBe(true);
- expect(MEDIA_OPTIONAL_KINDS.has("upscale")).toBe(false);
- });
- it("classifies artifacts by type or extension", () => {
- expect(artifactIsImage({ relativePath: "out.png" })).toBe(true);
- expect(artifactIsVideo({ relativePath: "out.mp4" })).toBe(true);
- expect(artifactIsAudio({ relativePath: "out.wav" })).toBe(true);
- expect(artifactIsImage({ type: "image", relativePath: "x" })).toBe(true);
- expect(artifactIsVideo({ relativePath: "out.png" })).toBe(false);
- });
-});
diff --git a/packages/core/src/ai/cloud-job-types.ts b/packages/core/src/ai/cloud-job-types.ts
deleted file mode 100644
index 45def9d4..00000000
--- a/packages/core/src/ai/cloud-job-types.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-export const AI_CLOUD_JOB_KINDS = {
- transcription: "transcription",
- aiHighlight: "ai_highlight",
- autoCaptions: "auto_captions",
- personMatting: "person_matting",
- objectTracking: "object_tracking",
- faceAnalysis: "face_analysis",
- stabilization: "stabilization",
- autoReframe: "auto_reframe",
- audioSeparation: "audio_separation",
- colorMatch: "color_match",
- colorize: "colorize",
- upscale: "upscale",
- sceneDetection: "scene_detection",
- backgroundRemoval: "background_removal",
- musicGeneration: "music_generation",
- photoEnhance: "photo_enhance",
- portraitBokeh: "portrait_bokeh",
- smartThumbnail: "smart_thumbnail",
- denoise: "denoise",
- silenceRemoval: "silence_removal",
- frameInterpolation: "frame_interpolation",
- faceRestore: "face_restore",
- objectRemoval: "object_removal",
- voiceEnhance: "voice_enhance",
- translation: "translation",
-} as const;
-
-export type AiCloudJobKind = (typeof AI_CLOUD_JOB_KINDS)[keyof typeof AI_CLOUD_JOB_KINDS];
-
-export type AiCloudJobStatus =
- | "queued"
- | "uploading"
- | "processing"
- | "completed"
- | "failed"
- | "cancelled";
-
-const TERMINAL_STATUSES: ReadonlySet<string> = new Set(["completed", "failed", "cancelled"]);
-
-export function isTerminalStatus(status: string): boolean {
- return TERMINAL_STATUSES.has(status);
-}
-
-export const MEDIA_OPTIONAL_KINDS: ReadonlySet<string> = new Set([
- AI_CLOUD_JOB_KINDS.musicGeneration,
- AI_CLOUD_JOB_KINDS.translation,
-]);
-
-export interface AiCloudJobRequest {
- kind: string;
- params: Record<string, unknown>;
-}
-
-export interface AiCloudJobCreated {
- jobID: string;
- status: AiCloudJobStatus;
- manifestURL?: string;
-}
-
-export interface AiCloudJobStatusResponse {
- jobID: string;
- status: AiCloudJobStatus;
- progress?: number;
- message?: string;
- manifestURL?: string;
- error?: string;
- queuePosition?: number;
- pendingAhead?: number;
-}
-
-export interface AiWorkerArtifactReference {
- type?: string;
- stem?: string;
- relativePath: string;
- width?: number;
- height?: number;
- frameIndex?: number;
- sourceTime?: number;
- score?: number;
- fps?: number;
- frameCount?: number;
- sampleRate?: number;
- duration?: number;
- channels?: number;
-}
-
-export interface AiWorkerResultManifest {
- jobID: string;
- kind: string;
- status?: AiCloudJobStatus;
- model?: string;
- artifacts: AiWorkerArtifactReference[];
- metadata?: Record<string, unknown>;
-}
-
-const IMAGE_EXTS: ReadonlySet<string> = new Set(["jpg", "jpeg", "png", "heic", "heif", "webp", "tiff", "tif", "bmp"]);
-const VIDEO_EXTS: ReadonlySet<string> = new Set(["mp4", "mov", "m4v", "webm"]);
-const AUDIO_EXTS: ReadonlySet<string> = new Set(["wav", "m4a", "mp3", "aac", "ogg"]);
-
-function ext(relativePath: string): string {
- return relativePath.split(".").pop()?.toLowerCase() ?? "";
-}
-
-export function artifactIsImage(a: AiWorkerArtifactReference): boolean {
- return a.type === "image" || IMAGE_EXTS.has(ext(a.relativePath));
-}
-
-export function artifactIsVideo(a: AiWorkerArtifactReference): boolean {
- return a.type === "video" || a.type === "mask_video" || VIDEO_EXTS.has(ext(a.relativePath));
-}
-
-export function artifactIsAudio(a: AiWorkerArtifactReference): boolean {
- return a.type === "audio" || AUDIO_EXTS.has(ext(a.relativePath));
-}
-
-export function normalizeResultManifest(raw: Record<string, unknown>): AiWorkerResultManifest {
- const artifactsRaw = Array.isArray(raw.artifacts) ? (raw.artifacts as Record<string, unknown>[]) : [];
- return {
- jobID: String(raw.jobID ?? ""),
- kind: String(raw.kind ?? ""),
- status: raw.status as AiCloudJobStatus | undefined,
- model: typeof raw.model === "string" ? raw.model : undefined,
- artifacts: artifactsRaw
- .filter((a) => typeof a.relativePath === "string")
- .map((a) => ({ ...(a as object), relativePath: String((a as { relativePath: unknown }).relativePath) }) as AiWorkerArtifactReference),
- metadata: (raw.metadata as Record<string, unknown>) ?? {},
- };
-}
-
-export function primaryArtifact(manifest: AiWorkerResultManifest): AiWorkerArtifactReference | null {
- return (
- manifest.artifacts.find(artifactIsVideo) ??
- manifest.artifacts.find(artifactIsImage) ??
- manifest.artifacts.find(artifactIsAudio) ??
- manifest.artifacts[0] ??
- null
- );
-}
diff --git a/packages/core/src/ai/index.ts b/packages/core/src/ai/index.ts
index fc4c8c10..89058a06 100644
--- a/packages/core/src/ai/index.ts
+++ b/packages/core/src/ai/index.ts
@@ -1,4 +1,3 @@
export * from "./background-removal-engine";
export * from "./auto-reframe-engine";
export * from "./person-segmentation-engine";
-export * from "./cloud-job-types";
diff --git a/packages/core/src/animation/animation-exporter.ts b/packages/core/src/animation/animation-exporter.ts
index 327ed5f9..5d37890e 100644
--- a/packages/core/src/animation/animation-exporter.ts
+++ b/packages/core/src/animation/animation-exporter.ts
@@ -23,6 +23,7 @@ import type { Project, MediaItem } from "../types/project";
import type { Clip, Keyframe, EasingType } from "../types/timeline";
import type { TextClip } from "../text/types";
import type { ShapeClip, ShapeType } from "../graphics/types";
+import { getMediaItemCapabilities } from "../timeline/timeline-items";
export interface ExportResult {
success: boolean;
@@ -377,13 +378,11 @@ export class AnimationExporter {
const audioTracks: AudioTrackConfig[] = [];
for (const track of project.timeline.tracks) {
- if (track.type !== "audio") continue;
-
for (const clip of track.clips) {
const mediaItem = project.mediaLibrary.items.find(
(item) => item.id === clip.mediaId,
);
- if (!mediaItem || mediaItem.type !== "audio") continue;
+ if (!mediaItem || !getMediaItemCapabilities(mediaItem).audio) continue;
audioTracks.push({
assetId: clip.mediaId,
diff --git a/packages/core/src/audio/audio-engine.ts b/packages/core/src/audio/audio-engine.ts
index 2180884a..e4aaffd6 100644
--- a/packages/core/src/audio/audio-engine.ts
+++ b/packages/core/src/audio/audio-engine.ts
@@ -23,6 +23,10 @@ import {
import { scheduleVolumeAutomationOnGain } from "./clip-volume-automation";
import { scheduleClipFadeEnvelope } from "./clip-fade-envelope";
import { getTrackTransitionAudioFades } from "./transition-audio-fades";
+import {
+ getMediaItemCapabilities,
+ trackHasAudioItems,
+} from "../timeline/timeline-items";
const SEGMENTED_AUDIO_DECODE_THRESHOLD_SECONDS = 120;
@@ -206,7 +210,7 @@ export class AudioEngine {
): Promise<RenderedAudio> {
this.ensureInitialized();
- const { timeline, mediaLibrary, settings } = project;
+ const { mediaLibrary, settings } = project;
const sampleRate = settings.sampleRate || this.config.sampleRate;
const channels = settings.channels || this.config.channels;
const safeDuration = Math.max(duration, 0.001);
@@ -217,7 +221,7 @@ export class AudioEngine {
sampleRate,
);
const audioTracks = this.getAudioTracksAtTime(
- timeline,
+ project,
startTime,
duration,
);
@@ -289,17 +293,21 @@ export class AudioEngine {
}
private getAudioTracksAtTime(
- timeline: Timeline,
+ project: Project,
startTime: number,
duration: number,
): AudioTrackRenderInfo[] {
const result: AudioTrackRenderInfo[] = [];
const endTime = startTime + duration;
+ const { timeline, mediaLibrary } = project;
timeline.tracks.forEach((track, index) => {
- if (track.type !== "audio" && track.type !== "video") return;
-
- const clips = this.getClipsInRange(track, startTime, endTime);
+ const clips = this.getClipsInRange(track, startTime, endTime).filter(
+ (clip) =>
+ getMediaItemCapabilities(
+ mediaLibrary.items.find((item) => item.id === clip.mediaId),
+ ).audio,
+ );
if (clips.length === 0) return;
result.push({
@@ -765,9 +773,9 @@ export class AudioEngine {
return offlineContext.startRendering();
}
- getChannelStates(timeline: Timeline): AudioChannelState[] {
- return timeline.tracks
- .filter((track) => track.type === "audio" || track.type === "video")
+ getChannelStates(project: Project): AudioChannelState[] {
+ return project.timeline.tracks
+ .filter((track) => trackHasAudioItems(project, track.id))
.map((track) => ({
trackId: track.id,
volume: 1, // Default volume, would be stored in track
diff --git a/packages/core/src/audio/clip-audio-resolution.ts b/packages/core/src/audio/clip-audio-resolution.ts
index 7e07a732..5a786a42 100644
--- a/packages/core/src/audio/clip-audio-resolution.ts
+++ b/packages/core/src/audio/clip-audio-resolution.ts
@@ -13,22 +13,6 @@ const isAlignedLinkedClip = (clip: Clip, candidate: Clip): boolean =>
Math.abs(candidate.startTime - clip.startTime) < LINK_TOLERANCE_SECONDS &&
Math.abs(candidate.inPoint - clip.inPoint) < LINK_TOLERANCE_SECONDS;
-const getTrackTypePriority = (
- currentTrackType: Track["type"] | undefined,
- candidateTrackType: Track["type"],
-): number => {
- if (currentTrackType === "audio") {
- if (candidateTrackType === "video") return 0;
- if (candidateTrackType === "image") return 1;
- }
-
- if (candidateTrackType === "audio") return 0;
- if (candidateTrackType === "video") return 1;
- if (candidateTrackType === "image") return 2;
-
- return 3;
-};
-
export const findClipTrack = (
timeline: TimelineWithTracks,
clipId: string,
@@ -47,7 +31,6 @@ export const getLinkedAudioClips = (
clip: Clip,
timeline: TimelineWithTracks,
): Array<{ clip: Clip; track: Track }> => {
- const currentTrack = timeline.tracks.find((track) => track.id === clip.trackId);
const linkedClips: Array<{ clip: Clip; track: Track }> = [];
for (const track of timeline.tracks) {
@@ -62,11 +45,7 @@ export const getLinkedAudioClips = (
}
}
- return linkedClips.sort(
- (left, right) =>
- getTrackTypePriority(currentTrack?.type, left.track.type) -
- getTrackTypePriority(currentTrack?.type, right.track.type),
- );
+ return linkedClips;
};
export const resolveClipAudioEffects = (
@@ -110,8 +89,8 @@ export const resolveAudibleAudioTarget = (
}
const linkedAudioClip = getLinkedAudioClips(clip, timeline).find(
- (entry) => entry.track.type === "audio" && entry.clip.volume > 0,
+ (entry) => entry.clip.volume > 0,
);
return linkedAudioClip?.clip ?? clip;
-};
\ No newline at end of file
+};
diff --git a/packages/core/src/export/export-engine.test.ts b/packages/core/src/export/export-engine.test.ts
index 2ab9dfbe..a5cf44b3 100644
--- a/packages/core/src/export/export-engine.test.ts
+++ b/packages/core/src/export/export-engine.test.ts
@@ -181,7 +181,29 @@ const createMockProject = (overrides?: Partial<Project>): Project => ({
channels: 2,
},
mediaLibrary: {
- items: [],
+ items: [
+ {
+ id: "media-1",
+ name: "Mock video",
+ type: "video",
+ fileHandle: null,
+ blob: null,
+ metadata: {
+ duration: 40,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48_000,
+ channels: 2,
+ fileSize: 0,
+ hasVideo: true,
+ hasAudio: true,
+ },
+ thumbnailUrl: null,
+ waveformData: null,
+ },
+ ],
},
timeline: {
tracks: [],
diff --git a/packages/core/src/export/export-engine.ts b/packages/core/src/export/export-engine.ts
index 2a0ec69b..2d8ea9ea 100644
--- a/packages/core/src/export/export-engine.ts
+++ b/packages/core/src/export/export-engine.ts
@@ -25,6 +25,11 @@ import { getMediaEngine } from "../media/mediabunny-engine";
import { getWavEncoder } from "../wasm/wav";
import type { EncoderBackend, EncoderBackendFactory } from "./encoder-backend";
import { WebCodecsBackend } from "./webcodecs-backend";
+import { resolveWebCodecsExportLimits } from "./webcodecs-limits";
+import {
+ getMediaItemCapabilities,
+ trackHasAudioItems,
+} from "../timeline/timeline-items";
export class ExportEngine {
private static readonly AUDIO_EXPORT_CHUNK_DURATION_SECONDS = 15;
@@ -161,26 +166,10 @@ export class ExportEngine {
const timelineDuration = this.calculateTimelineDuration(timeline);
if (backend.requiresWebCodecsClamping) {
- const isMemoryIntensiveCodec =
- fullSettings.codec === "vp9" ||
- fullSettings.codec === "av1" ||
- fullSettings.codec === "h265";
- const isLongVideo = timelineDuration > 120;
-
- let maxW = isMemoryIntensiveCodec ? 1920 : 3840;
- let maxH = isMemoryIntensiveCodec ? 1080 : 2160;
- if (isLongVideo) {
- maxW = Math.min(maxW, 1920);
- maxH = Math.min(maxH, 1080);
- }
- if (fullSettings.width > maxW || fullSettings.height > maxH) {
- const scale = Math.min(maxW / fullSettings.width, maxH / fullSettings.height, 1);
- fullSettings.width = Math.round(fullSettings.width * scale / 2) * 2;
- fullSettings.height = Math.round(fullSettings.height * scale / 2) * 2;
- }
- if (isLongVideo && fullSettings.frameRate > 30) {
- fullSettings.frameRate = 30;
- }
+ Object.assign(
+ fullSettings,
+ resolveWebCodecsExportLimits(fullSettings, timelineDuration).settings,
+ );
}
this.abortController = new AbortController();
@@ -237,12 +226,16 @@ export class ExportEngine {
const mediaEngine = getMediaEngine();
const videoMediaIds: string[] = [];
for (const track of project.timeline.tracks) {
- if (track.type !== "video") continue;
for (const clip of track.clips) {
const mediaItem = project.mediaLibrary.items.find(
(m) => m.id === clip.mediaId,
);
- if (mediaItem?.blob && !videoMediaIds.includes(mediaItem.id)) {
+ if (
+ mediaItem?.blob &&
+ getMediaItemCapabilities(mediaItem).visual &&
+ mediaItem.type === "video" &&
+ !videoMediaIds.includes(mediaItem.id)
+ ) {
videoMediaIds.push(mediaItem.id);
try {
await mediaEngine.createExportDecoder(
@@ -906,10 +899,7 @@ export class ExportEngine {
const { timeline } = project;
const hasAudio = timeline.tracks.some(
- (track) =>
- (track.type === "audio" || track.type === "video") &&
- !track.muted &&
- track.clips.length > 0,
+ (track) => !track.muted && trackHasAudioItems(project, track.id),
);
if (!hasAudio) {
diff --git a/packages/core/src/export/webcodecs-limits.test.ts b/packages/core/src/export/webcodecs-limits.test.ts
new file mode 100644
index 00000000..f1758f2f
--- /dev/null
+++ b/packages/core/src/export/webcodecs-limits.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import { DEFAULT_VIDEO_SETTINGS } from "./types";
+import { resolveWebCodecsExportLimits } from "./webcodecs-limits";
+
+describe("resolveWebCodecsExportLimits", () => {
+ it("clamps long portrait exports by long and short edge", () => {
+ const result = resolveWebCodecsExportLimits(
+ {
+ ...DEFAULT_VIDEO_SETTINGS,
+ width: 2160,
+ height: 3840,
+ frameRate: 50,
+ },
+ 221,
+ );
+
+ expect(result.settings).toMatchObject({
+ width: 1080,
+ height: 1920,
+ frameRate: 30,
+ });
+ expect(result).toMatchObject({
+ wasAdjusted: true,
+ resolutionAdjusted: true,
+ frameRateAdjusted: true,
+ });
+ });
+
+ it("preserves a project-sized long portrait export", () => {
+ const result = resolveWebCodecsExportLimits(
+ {
+ ...DEFAULT_VIDEO_SETTINGS,
+ width: 1080,
+ height: 1920,
+ frameRate: 30,
+ },
+ 221,
+ );
+
+ expect(result.settings).toMatchObject({
+ width: 1080,
+ height: 1920,
+ frameRate: 30,
+ });
+ expect(result.wasAdjusted).toBe(false);
+ });
+
+ it("allows 4K portrait H.264 for shorter exports", () => {
+ const result = resolveWebCodecsExportLimits(
+ {
+ ...DEFAULT_VIDEO_SETTINGS,
+ width: 2160,
+ height: 3840,
+ frameRate: 50,
+ },
+ 120,
+ );
+
+ expect(result.settings).toMatchObject({
+ width: 2160,
+ height: 3840,
+ frameRate: 50,
+ });
+ expect(result.wasAdjusted).toBe(false);
+ });
+
+ it("applies the HD edge limit to memory-intensive codecs", () => {
+ const result = resolveWebCodecsExportLimits(
+ {
+ ...DEFAULT_VIDEO_SETTINGS,
+ codec: "h265",
+ width: 3840,
+ height: 2160,
+ },
+ 30,
+ );
+
+ expect(result.settings).toMatchObject({
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ });
+ expect(result.resolutionAdjusted).toBe(true);
+ expect(result.frameRateAdjusted).toBe(false);
+ });
+});
diff --git a/packages/core/src/export/webcodecs-limits.ts b/packages/core/src/export/webcodecs-limits.ts
new file mode 100644
index 00000000..68b4b4ac
--- /dev/null
+++ b/packages/core/src/export/webcodecs-limits.ts
@@ -0,0 +1,54 @@
+import type { VideoExportSettings } from "./types";
+
+export interface WebCodecsExportAdjustment {
+ settings: VideoExportSettings;
+ wasAdjusted: boolean;
+ resolutionAdjusted: boolean;
+ frameRateAdjusted: boolean;
+}
+
+/**
+ * Applies the browser export safety limits without assuming a landscape frame.
+ * The long and short edges are bounded independently so portrait exports retain
+ * the same resolution class as equivalent landscape exports.
+ */
+export function resolveWebCodecsExportLimits(
+ settings: VideoExportSettings,
+ timelineDuration: number,
+): WebCodecsExportAdjustment {
+ const isMemoryIntensiveCodec =
+ settings.codec === "vp9" ||
+ settings.codec === "av1" ||
+ settings.codec === "h265";
+ const isLongVideo = timelineDuration > 120;
+ const usesHdLimit = isMemoryIntensiveCodec || isLongVideo;
+ const maxLongEdge = usesHdLimit ? 1920 : 3840;
+ const maxShortEdge = usesHdLimit ? 1080 : 2160;
+ const requestedLongEdge = Math.max(settings.width, settings.height);
+ const requestedShortEdge = Math.min(settings.width, settings.height);
+ const scale = Math.min(
+ maxLongEdge / requestedLongEdge,
+ maxShortEdge / requestedShortEdge,
+ 1,
+ );
+
+ const width = Math.max(2, Math.round((settings.width * scale) / 2) * 2);
+ const height = Math.max(2, Math.round((settings.height * scale) / 2) * 2);
+ const frameRate =
+ isLongVideo && settings.frameRate > 30 ? 30 : settings.frameRate;
+ const resolutionAdjusted =
+ width !== settings.width || height !== settings.height;
+ const frameRateAdjusted = frameRate !== settings.frameRate;
+
+ return {
+ settings: {
+ ...settings,
+ width,
+ height,
+ frameRate,
+ },
+ wasAdjusted: resolutionAdjusted || frameRateAdjusted,
+ resolutionAdjusted,
+ frameRateAdjusted,
+ };
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 951988e1..171538a4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -18,6 +18,7 @@ export * from "./ai";
export * from "./animation";
export * from "./effects";
export * from "./device";
+export * from "./multicam";
export {
ExportEngine,
getExportEngine,
@@ -37,6 +38,11 @@ export {
type WebCodecsBackendOptions,
} from "./export/webcodecs-backend";
+export {
+ resolveWebCodecsExportLimits,
+ type WebCodecsExportAdjustment,
+} from "./export/webcodecs-limits";
+
export type {
VideoExportSettings,
AudioExportSettings,
diff --git a/packages/core/src/media/native-media-bridge.ts b/packages/core/src/media/native-media-bridge.ts
index 0843b2f1..86828846 100644
--- a/packages/core/src/media/native-media-bridge.ts
+++ b/packages/core/src/media/native-media-bridge.ts
@@ -11,14 +11,6 @@ export interface NativeMediaBridge {
closeWrite(handleId: string): Promise<void>;
readFileBytes(path: string): Promise<ArrayBuffer>;
};
- gpu?: {
- uploadMedia(args: { srcPath: string; filename: string; contentType?: string }): Promise<{ mediaKey: string }>;
- submitJob(args: { kind: string; params: Record<string, unknown>; mediaKey?: string; mediaFilename?: string }): Promise<{ jobID: string; status: string; manifestURL?: string }>;
- jobStatus(jobID: string): Promise<{ jobID: string; status: string; progress?: number; message?: string; manifestURL?: string; error?: string; queuePosition?: number; pendingAhead?: number }>;
- fetchManifest(jobID: string): Promise<Record<string, unknown>>;
- downloadArtifact(jobID: string, relativePath: string): Promise<{ tempPath: string; mime: string }>;
- cancelJob(jobID: string): Promise<{ jobID: string; status: string }>;
- };
media: {
generateProxy(args: { srcPath: string; preset: "low" | "medium" | "high" }): Promise<{ outPath: string }>;
transcode(args: {
diff --git a/packages/core/src/multicam/automatic-edit.test.ts b/packages/core/src/multicam/automatic-edit.test.ts
new file mode 100644
index 00000000..9e1733af
--- /dev/null
+++ b/packages/core/src/multicam/automatic-edit.test.ts
@@ -0,0 +1,223 @@
+import { describe, expect, it } from "vitest";
+import {
+ analyzeMulticamActivity,
+ decideMulticamEdit,
+ DEFAULT_MULTICAM_EDIT_POLICY,
+ type MulticamActivityMap,
+ type MulticamEditPolicy,
+} from "./automatic-edit";
+
+const sampleRate = 1_000;
+
+function signal(ranges: Array<[number, number, number]>, duration = 8): Float32Array {
+ const samples = new Float32Array(duration * sampleRate);
+ for (const [start, end, amplitude] of ranges) {
+ for (let index = start * sampleRate; index < end * sampleRate; index++) {
+ samples[index] = amplitude * Math.sin((2 * Math.PI * 50 * index) / sampleRate);
+ }
+ }
+ return samples;
+}
+
+function activityMap(
+ selections: Array<{ angleIds: string[]; scores: [number, number] }>,
+ windowSeconds = 1,
+): MulticamActivityMap {
+ return {
+ angleIds: ["a", "b"],
+ duration: selections.length * windowSeconds,
+ windowMs: windowSeconds * 1_000,
+ points: selections.map((selection, index) => ({
+ startTime: index * windowSeconds,
+ endTime: (index + 1) * windowSeconds,
+ activeAngleIds: selection.angleIds,
+ scores: { a: selection.scores[0], b: selection.scores[1] },
+ })),
+ };
+}
+
+const policy = (updates: Partial<MulticamEditPolicy> = {}): MulticamEditPolicy => ({
+ ...DEFAULT_MULTICAM_EDIT_POLICY,
+ maxShotMs: 0,
+ minShotMs: 0,
+ cutLeadMs: 0,
+ backchannelMaxMs: 0,
+ ...updates,
+});
+
+describe("analyzeMulticamActivity", () => {
+ it("maps isolated speakers to their camera angles", () => {
+ const activity = analyzeMulticamActivity(
+ [
+ { angleId: "a", samples: signal([[0, 4, 0.8]]), sampleRate },
+ { angleId: "b", samples: signal([[4, 8, 0.8]]), sampleRate },
+ ],
+ { windowMs: 500 },
+ );
+
+ expect(activity.points[2]?.activeAngleIds).toEqual(["a"]);
+ expect(activity.points[10]?.activeAngleIds).toEqual(["b"]);
+ });
+
+ it("suppresses a quieter copy of the dominant microphone as bleed", () => {
+ const activity = analyzeMulticamActivity(
+ [
+ { angleId: "a", samples: signal([[1, 4, 0.8]], 5), sampleRate },
+ { angleId: "b", samples: signal([[1, 4, 0.2]], 5), sampleRate },
+ ],
+ { windowMs: 500, bleedRatio: 0.55 },
+ );
+
+ expect(activity.points[3]?.activeAngleIds).toEqual(["a"]);
+ expect(activity.points[3]?.scores.b).toBeCloseTo(0.25, 1);
+ });
+
+ it("does not classify digital silence as speaker activity", () => {
+ const activity = analyzeMulticamActivity([
+ { angleId: "a", samples: signal([], 2), sampleRate },
+ { angleId: "b", samples: signal([], 2), sampleRate },
+ ]);
+
+ expect(activity.points.every((point) => point.activeAngleIds.length === 0)).toBe(true);
+ });
+
+ it("honors source offsets while constructing the shared activity timeline", () => {
+ const activity = analyzeMulticamActivity(
+ [
+ { angleId: "a", samples: signal([[0, 1, 0.8]], 3), sampleRate },
+ {
+ angleId: "b",
+ samples: signal([[1, 2, 0.8]], 3),
+ sampleRate,
+ offsetSeconds: 1,
+ },
+ ],
+ { windowMs: 500, durationSeconds: 1 },
+ );
+
+ expect(activity.points[0]?.activeAngleIds).toEqual(["a", "b"]);
+ });
+
+ it("uses Silero probabilities to reject non-speech energy", () => {
+ const activity = analyzeMulticamActivity(
+ [
+ {
+ angleId: "a",
+ samples: signal([[0, 2, 0.8]], 2),
+ sampleRate,
+ vad: { windowMs: 500, probabilities: new Float32Array([0.1, 0.1, 0.9, 0.9]) },
+ },
+ { angleId: "b", samples: signal([], 2), sampleRate },
+ ],
+ { windowMs: 500 },
+ );
+
+ expect(activity.points[0]?.activeAngleIds).toEqual([]);
+ expect(activity.points[2]?.activeAngleIds).toEqual(["a"]);
+ });
+});
+
+describe("decideMulticamEdit", () => {
+ it("cuts to the newly active speaker with the configured lead", () => {
+ const activity = activityMap([
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["b"], scores: [0, 1] },
+ { angleIds: ["b"], scores: [0, 1] },
+ ]);
+
+ const edit = decideMulticamEdit(activity, policy({ cutLeadMs: 200 }));
+
+ expect(edit.segments).toHaveLength(2);
+ expect(edit.segments[0]).toMatchObject({ angleId: "a", endTime: 1.8 });
+ expect(edit.segments[1]).toMatchObject({
+ angleId: "b",
+ startTime: 1.8,
+ reason: "speaker",
+ });
+ });
+
+ it("ignores a brief backchannel between longer shots of the same speaker", () => {
+ const activity = activityMap(
+ [
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["b"], scores: [0, 1] },
+ { angleIds: ["a"], scores: [1, 0] },
+ ],
+ 0.5,
+ );
+
+ const edit = decideMulticamEdit(activity, policy({ backchannelMaxMs: 600 }));
+
+ expect(edit.segments).toEqual([
+ expect.objectContaining({ angleId: "a", startTime: 0, endTime: 2 }),
+ ]);
+ });
+
+ it("holds the current angle during overlap or chooses the energy winner", () => {
+ const activity = activityMap([
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["a", "b"], scores: [0.7, 1] },
+ { angleIds: ["b"], scores: [0, 1] },
+ ]);
+
+ const hold = decideMulticamEdit(activity, policy({ overlapStrategy: "hold" }));
+ const winner = decideMulticamEdit(activity, policy({ overlapStrategy: "winner" }));
+
+ expect(hold.segments[0]?.endTime).toBe(2);
+ expect(winner.segments[0]?.endTime).toBe(1);
+ expect(winner.segments[1]).toMatchObject({
+ angleId: "b",
+ reason: "overlap-winner",
+ });
+ });
+
+ it("enforces minimum shot length without losing a persistent speaker change", () => {
+ const activity = activityMap([
+ { angleIds: ["a"], scores: [1, 0] },
+ { angleIds: ["b"], scores: [0, 1] },
+ { angleIds: ["b"], scores: [0, 1] },
+ { angleIds: ["b"], scores: [0, 1] },
+ ]);
+
+ const edit = decideMulticamEdit(activity, policy({ minShotMs: 2_000 }));
+
+ expect(edit.segments[0]?.endTime).toBe(2);
+ expect(edit.segments[1]?.angleId).toBe("b");
+ });
+
+ it("adds deterministic reaction shots when a camera exceeds max shot length", () => {
+ const activity = activityMap(
+ Array.from({ length: 8 }, () => ({
+ angleIds: ["a"],
+ scores: [1, 0.2] as [number, number],
+ })),
+ );
+
+ const edit = decideMulticamEdit(
+ activity,
+ policy({ maxShotMs: 3_000, reactionShotMs: 1_000, minShotMs: 1_000 }),
+ );
+
+ expect(edit.segments).toEqual([
+ expect.objectContaining({ angleId: "a", startTime: 0, endTime: 3 }),
+ expect.objectContaining({ angleId: "b", startTime: 3, endTime: 4, reason: "max-shot" }),
+ expect.objectContaining({ angleId: "a", startTime: 4, endTime: 7 }),
+ expect.objectContaining({ angleId: "b", startTime: 7, endTime: 8, reason: "max-shot" }),
+ ]);
+ });
+
+ it("is deterministic for the same activity and policy", () => {
+ const activity = activityMap([
+ { angleIds: ["a"], scores: [1, 0.2] },
+ { angleIds: ["a", "b"], scores: [0.8, 1] },
+ { angleIds: ["b"], scores: [0.1, 1] },
+ ]);
+ const editPolicy = policy({ overlapStrategy: "winner", cutLeadMs: 100 });
+
+ expect(decideMulticamEdit(activity, editPolicy)).toEqual(
+ decideMulticamEdit(activity, editPolicy),
+ );
+ });
+});
diff --git a/packages/core/src/multicam/automatic-edit.ts b/packages/core/src/multicam/automatic-edit.ts
new file mode 100644
index 00000000..d1223d75
--- /dev/null
+++ b/packages/core/src/multicam/automatic-edit.ts
@@ -0,0 +1,554 @@
+import {
+ correctMulticamBleedEnergies,
+ type MulticamBleedCalibration,
+} from "./bleed-calibration";
+
+export type MulticamOverlapStrategy = "hold" | "winner";
+
+export interface MulticamVadTrack {
+ windowMs: number;
+ probabilities: Float32Array;
+}
+
+export interface MulticamAudioSource {
+ angleId: string;
+ samples: Float32Array;
+ sampleRate: number;
+ /** Seconds to advance into this source to align it with the group timeline. */
+ offsetSeconds?: number;
+ vad?: MulticamVadTrack;
+}
+
+export interface MulticamActivityPoint {
+ startTime: number;
+ endTime: number;
+ activeAngleIds: string[];
+ /** Relative energy scores. The strongest source in a window has a score of 1. */
+ scores: Record<string, number>;
+ speechProbabilities?: Record<string, number>;
+}
+
+export interface MulticamActivityMap {
+ angleIds: string[];
+ duration: number;
+ windowMs: number;
+ points: MulticamActivityPoint[];
+}
+
+export interface MulticamActivityOptions {
+ windowMs?: number;
+ durationSeconds?: number;
+ noiseFloorPercentile?: number;
+ activityThresholdDb?: number;
+ bleedRatio?: number;
+ analysisSampleRate?: number;
+ vadThreshold?: number;
+ bleedCalibration?: MulticamBleedCalibration;
+}
+
+export interface MulticamEditPolicy {
+ overlapStrategy: MulticamOverlapStrategy;
+ minShotMs: number;
+ maxShotMs: number;
+ reactionShotMs: number;
+ cutLeadMs: number;
+ backchannelMaxMs: number;
+ /** Begin reaction-shot consideration after this much uninterrupted screen time. */
+ reactionShotAfterMs: number;
+ /** Avoid consecutive angles that frame the same participant. */
+ forbidJumpCutSameSubject: boolean;
+ initialAngleId?: string;
+}
+
+export type MulticamEditReason =
+ | "speaker"
+ | "overlap-hold"
+ | "overlap-winner"
+ | "silence-hold"
+ | "max-shot"
+ | "backchannel-hold"
+ | "turn-collision-winner"
+ | "successful-interruption"
+ | "sustained-overlap"
+ | "group-reaction"
+ | "reaction-shot"
+ | "layout-budget"
+ | "directive";
+
+export interface MulticamEditDecision {
+ angleId: string;
+ startTime: number;
+ endTime: number;
+ reason: MulticamEditReason;
+ confidence: number;
+}
+
+export interface MulticamEditDecisionList {
+ duration: number;
+ segments: MulticamEditDecision[];
+}
+
+export const DEFAULT_MULTICAM_ACTIVITY_OPTIONS: Required<
+ Omit<MulticamActivityOptions, "durationSeconds" | "bleedCalibration">
+> = {
+ windowMs: 50,
+ noiseFloorPercentile: 0.2,
+ activityThresholdDb: 8,
+ bleedRatio: 0.55,
+ analysisSampleRate: 2_000,
+ vadThreshold: 0.5,
+};
+
+export const DEFAULT_MULTICAM_EDIT_POLICY: MulticamEditPolicy = {
+ overlapStrategy: "hold",
+ minShotMs: 1_800,
+ maxShotMs: 30_000,
+ reactionShotMs: 2_000,
+ cutLeadMs: 120,
+ backchannelMaxMs: 700,
+ reactionShotAfterMs: 12_000,
+ forbidJumpCutSameSubject: true,
+};
+
+const clamp = (value: number, min: number, max: number): number =>
+ Math.min(max, Math.max(min, value));
+
+const finiteNonNegative = (value: number | undefined, fallback: number): number =>
+ typeof value === "number" && Number.isFinite(value) && value >= 0
+ ? value
+ : fallback;
+
+const finiteNumber = (value: number | undefined, fallback: number): number =>
+ typeof value === "number" && Number.isFinite(value) ? value : fallback;
+
+function percentile(values: readonly number[], position: number): number {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ const index = Math.floor(clamp(position, 0, 1) * (sorted.length - 1));
+ return sorted[index] ?? 0;
+}
+
+function windowRms(
+ source: MulticamAudioSource,
+ startTime: number,
+ endTime: number,
+ analysisSampleRate: number,
+): number {
+ const offset = finiteNumber(source.offsetSeconds, 0);
+ const sourceStart = startTime + offset;
+ const startSample = Math.max(0, Math.floor(sourceStart * source.sampleRate));
+ const endSample = Math.min(
+ source.samples.length,
+ Math.ceil((endTime + offset) * source.sampleRate),
+ );
+ if (endSample <= startSample) return 0;
+
+ const stride = Math.max(1, Math.floor(source.sampleRate / analysisSampleRate));
+ let sumSquares = 0;
+ let count = 0;
+ for (let index = startSample; index < endSample; index += stride) {
+ const sample = source.samples[index] ?? 0;
+ sumSquares += sample * sample;
+ count++;
+ }
+ return count > 0 ? Math.sqrt(sumSquares / count) : 0;
+}
+
+/**
+ * Builds a deterministic, compact speech-activity artifact from isolated camera
+ * or microphone recordings. Activity is relative to every source in a window,
+ * which rejects quieter copies of the same voice caused by microphone bleed.
+ */
+export function analyzeMulticamActivity(
+ sources: readonly MulticamAudioSource[],
+ options: MulticamActivityOptions = {},
+): MulticamActivityMap {
+ const validSources = sources.filter(
+ (source) =>
+ source.angleId.length > 0 &&
+ source.sampleRate > 0 &&
+ Number.isFinite(source.sampleRate),
+ );
+ const windowMs = Math.max(
+ 10,
+ finiteNonNegative(options.windowMs, DEFAULT_MULTICAM_ACTIVITY_OPTIONS.windowMs),
+ );
+ const windowSeconds = windowMs / 1_000;
+ const availableDuration = validSources.reduce((longest, source) => {
+ const offset = finiteNumber(source.offsetSeconds, 0);
+ return Math.max(longest, source.samples.length / source.sampleRate - offset);
+ }, 0);
+ const duration = Math.max(
+ 0,
+ Math.min(
+ availableDuration,
+ finiteNonNegative(options.durationSeconds, availableDuration),
+ ),
+ );
+ const windowCount = Math.ceil(duration / windowSeconds);
+ const analysisSampleRate = Math.max(
+ 100,
+ finiteNonNegative(
+ options.analysisSampleRate,
+ DEFAULT_MULTICAM_ACTIVITY_OPTIONS.analysisSampleRate,
+ ),
+ );
+ const energies = new Map<string, number[]>();
+
+ for (const source of validSources) {
+ const sourceEnergies: number[] = [];
+ for (let index = 0; index < windowCount; index++) {
+ const startTime = index * windowSeconds;
+ sourceEnergies.push(
+ windowRms(
+ source,
+ startTime,
+ Math.min(duration, startTime + windowSeconds),
+ analysisSampleRate,
+ ),
+ );
+ }
+ energies.set(source.angleId, sourceEnergies);
+ }
+
+ const floorPosition = clamp(
+ options.noiseFloorPercentile ??
+ DEFAULT_MULTICAM_ACTIVITY_OPTIONS.noiseFloorPercentile,
+ 0,
+ 1,
+ );
+ const thresholdMultiplier = Math.pow(
+ 10,
+ finiteNonNegative(
+ options.activityThresholdDb,
+ DEFAULT_MULTICAM_ACTIVITY_OPTIONS.activityThresholdDb,
+ ) / 20,
+ );
+ const correctedEnergies = new Map<string, number[]>(
+ validSources.map((source) => [source.angleId, []]),
+ );
+ for (let index = 0; index < windowCount; index++) {
+ const raw: Record<string, number> = {};
+ for (const source of validSources) {
+ raw[source.angleId] = energies.get(source.angleId)?.[index] ?? 0;
+ }
+ const corrected = correctMulticamBleedEnergies(raw, options.bleedCalibration);
+ for (const source of validSources) {
+ correctedEnergies.get(source.angleId)?.push(corrected[source.angleId] ?? 0);
+ }
+ }
+
+ const thresholds = new Map<string, number>();
+ for (const source of validSources) {
+ const sourceEnergies = correctedEnergies.get(source.angleId) ?? [];
+ const floor = percentile(sourceEnergies, floorPosition);
+ const peak = sourceEnergies.reduce(
+ (strongest, energy) => Math.max(strongest, energy),
+ 0,
+ );
+ // Continuously active microphones have no silent calibration window. Cap
+ // the adaptive threshold below their peak so relative-energy comparison can
+ // still identify them, while the absolute floor rejects digital silence.
+ thresholds.set(
+ source.angleId,
+ Math.max(0.001, Math.min(floor * thresholdMultiplier, peak * 0.5)),
+ );
+ }
+
+ const bleedRatio = clamp(
+ options.bleedRatio ?? DEFAULT_MULTICAM_ACTIVITY_OPTIONS.bleedRatio,
+ 0,
+ 1,
+ );
+ const vadThreshold = clamp(
+ options.vadThreshold ?? DEFAULT_MULTICAM_ACTIVITY_OPTIONS.vadThreshold,
+ 0,
+ 1,
+ );
+ const points: MulticamActivityPoint[] = [];
+ for (let index = 0; index < windowCount; index++) {
+ let strongest = 0;
+ for (const source of validSources) {
+ strongest = Math.max(
+ strongest,
+ correctedEnergies.get(source.angleId)?.[index] ?? 0,
+ );
+ }
+
+ const scores: Record<string, number> = {};
+ const speechProbabilities: Record<string, number> = {};
+ const activeAngleIds: string[] = [];
+ for (const source of validSources) {
+ const energy = correctedEnergies.get(source.angleId)?.[index] ?? 0;
+ const sourceWindowMiddle =
+ (index + 0.5) * windowMs + finiteNumber(source.offsetSeconds, 0) * 1_000;
+ const vadIndex = source.vad
+ ? Math.floor(sourceWindowMiddle / source.vad.windowMs)
+ : -1;
+ const speechProbability = source.vad
+ ? (source.vad.probabilities[vadIndex] ?? 0)
+ : 1;
+ speechProbabilities[source.angleId] = speechProbability;
+ scores[source.angleId] = strongest > 0 ? energy / strongest : 0;
+ if (
+ speechProbability >= vadThreshold &&
+ energy >= (thresholds.get(source.angleId) ?? Number.POSITIVE_INFINITY) &&
+ energy >= strongest * bleedRatio
+ ) {
+ activeAngleIds.push(source.angleId);
+ }
+ }
+
+ points.push({
+ startTime: index * windowSeconds,
+ endTime: Math.min(duration, (index + 1) * windowSeconds),
+ activeAngleIds,
+ scores,
+ speechProbabilities,
+ });
+ }
+
+ return {
+ angleIds: validSources.map((source) => source.angleId),
+ duration,
+ windowMs,
+ points,
+ };
+}
+
+interface CandidateRun {
+ angleId: string;
+ startTime: number;
+ endTime: number;
+ reason: Exclude<MulticamEditReason, "max-shot">;
+ confidence: number;
+ pointCount: number;
+}
+
+function strongestAngle(
+ point: MulticamActivityPoint,
+ angleIds: readonly string[],
+): string | undefined {
+ return angleIds.reduce<string | undefined>((winner, angleId) => {
+ if (!winner) return angleId;
+ return (point.scores[angleId] ?? 0) > (point.scores[winner] ?? 0)
+ ? angleId
+ : winner;
+ }, undefined);
+}
+
+function candidateRuns(
+ activity: MulticamActivityMap,
+ policy: MulticamEditPolicy,
+): CandidateRun[] {
+ const firstActive = activity.points.find((point) => point.activeAngleIds.length > 0);
+ let current =
+ (policy.initialAngleId && activity.angleIds.includes(policy.initialAngleId)
+ ? policy.initialAngleId
+ : undefined) ??
+ (firstActive ? strongestAngle(firstActive, firstActive.activeAngleIds) : undefined) ??
+ activity.angleIds[0];
+ if (!current) return [];
+
+ const runs: CandidateRun[] = [];
+ for (const point of activity.points) {
+ let candidate = current;
+ let reason: CandidateRun["reason"] = "silence-hold";
+ if (point.activeAngleIds.length === 1) {
+ candidate = point.activeAngleIds[0] ?? current;
+ reason = "speaker";
+ } else if (point.activeAngleIds.length > 1) {
+ if (policy.overlapStrategy === "hold" && point.activeAngleIds.includes(current)) {
+ candidate = current;
+ reason = "overlap-hold";
+ } else {
+ candidate = strongestAngle(point, point.activeAngleIds) ?? current;
+ reason = policy.overlapStrategy === "winner" ? "overlap-winner" : "overlap-hold";
+ }
+ }
+
+ const confidence = clamp(point.scores[candidate] ?? 0, 0, 1);
+ const previous = runs[runs.length - 1];
+ if (previous && previous.angleId === candidate && previous.reason === reason) {
+ previous.endTime = point.endTime;
+ previous.confidence =
+ (previous.confidence * previous.pointCount + confidence) /
+ (previous.pointCount + 1);
+ previous.pointCount++;
+ } else {
+ runs.push({
+ angleId: candidate,
+ startTime: point.startTime,
+ endTime: point.endTime,
+ reason,
+ confidence,
+ pointCount: 1,
+ });
+ }
+ current = candidate;
+ }
+ return runs;
+}
+
+function mergeAdjacentRuns(runs: readonly CandidateRun[]): CandidateRun[] {
+ const merged: CandidateRun[] = [];
+ for (const run of runs) {
+ const previous = merged[merged.length - 1];
+ if (previous && previous.angleId === run.angleId) {
+ const previousDuration = previous.endTime - previous.startTime;
+ const runDuration = run.endTime - run.startTime;
+ const total = previousDuration + runDuration;
+ previous.endTime = run.endTime;
+ previous.confidence =
+ total > 0
+ ? (previous.confidence * previousDuration + run.confidence * runDuration) /
+ total
+ : previous.confidence;
+ if (previous.reason === "silence-hold" && run.reason !== "silence-hold") {
+ previous.reason = run.reason;
+ }
+ } else {
+ merged.push({ ...run });
+ }
+ }
+ return merged;
+}
+
+function suppressBackchannels(
+ runs: readonly CandidateRun[],
+ backchannelMaxSeconds: number,
+): CandidateRun[] {
+ let result = runs.map((run) => ({ ...run }));
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (let index = 1; index < result.length; index++) {
+ const run = result[index];
+ const previous = result[index - 1];
+ const next = result[index + 1];
+ if (!run || !previous) continue;
+ const isBrief = run.endTime - run.startTime <= backchannelMaxSeconds;
+ const returnsToPrevious = !next || next.angleId === previous.angleId;
+ if (isBrief && run.angleId !== previous.angleId && returnsToPrevious) {
+ run.angleId = previous.angleId;
+ run.reason = previous.reason;
+ changed = true;
+ }
+ }
+ result = mergeAdjacentRuns(result);
+ }
+ return result;
+}
+
+function buildSpeakerSegments(
+ runs: readonly CandidateRun[],
+ duration: number,
+ policy: MulticamEditPolicy,
+): MulticamEditDecision[] {
+ const first = runs[0];
+ if (!first || duration <= 0) return [];
+ const minShot = finiteNonNegative(policy.minShotMs, 0) / 1_000;
+ const cutLead = finiteNonNegative(policy.cutLeadMs, 0) / 1_000;
+ const segments: MulticamEditDecision[] = [
+ {
+ angleId: first.angleId,
+ startTime: 0,
+ endTime: duration,
+ reason: first.reason,
+ confidence: first.confidence,
+ },
+ ];
+
+ for (const run of runs.slice(1)) {
+ const current = segments[segments.length - 1];
+ if (!current || current.angleId === run.angleId) continue;
+ const cutTime = Math.max(current.startTime + minShot, run.startTime - cutLead);
+ if (cutTime >= run.endTime || cutTime >= duration) continue;
+ current.endTime = cutTime;
+ segments.push({
+ angleId: run.angleId,
+ startTime: cutTime,
+ endTime: duration,
+ reason: run.reason,
+ confidence: run.confidence,
+ });
+ }
+ return segments;
+}
+
+function scoreAngleInRange(
+ activity: MulticamActivityMap,
+ angleId: string,
+ startTime: number,
+ endTime: number,
+): number {
+ let total = 0;
+ let count = 0;
+ for (const point of activity.points) {
+ if (point.endTime <= startTime || point.startTime >= endTime) continue;
+ total += point.scores[angleId] ?? 0;
+ count++;
+ }
+ return count > 0 ? total / count : 0;
+}
+
+function addReactionShots(
+ segments: readonly MulticamEditDecision[],
+ activity: MulticamActivityMap,
+ policy: MulticamEditPolicy,
+): MulticamEditDecision[] {
+ const maxShot = finiteNonNegative(policy.maxShotMs, 0) / 1_000;
+ const reactionDuration = Math.max(
+ finiteNonNegative(policy.minShotMs, 0),
+ finiteNonNegative(policy.reactionShotMs, 0),
+ ) / 1_000;
+ if (maxShot <= 0 || reactionDuration <= 0 || activity.angleIds.length < 2) {
+ return [...segments];
+ }
+
+ const output: MulticamEditDecision[] = [];
+ for (const segment of segments) {
+ let cursor = segment.startTime;
+ while (segment.endTime - cursor >= maxShot + reactionDuration) {
+ const reactionStart = cursor + maxShot;
+ const reactionEnd = Math.min(segment.endTime, reactionStart + reactionDuration);
+ const alternate = activity.angleIds
+ .filter((angleId) => angleId !== segment.angleId)
+ .map((angleId) => ({
+ angleId,
+ score: scoreAngleInRange(activity, angleId, reactionStart, reactionEnd),
+ }))
+ .sort((a, b) => b.score - a.score || a.angleId.localeCompare(b.angleId))[0];
+ if (!alternate) break;
+ output.push({ ...segment, startTime: cursor, endTime: reactionStart });
+ output.push({
+ angleId: alternate.angleId,
+ startTime: reactionStart,
+ endTime: reactionEnd,
+ reason: "max-shot",
+ confidence: clamp(alternate.score, 0, 1),
+ });
+ cursor = reactionEnd;
+ }
+ if (cursor < segment.endTime) {
+ output.push({ ...segment, startTime: cursor });
+ }
+ }
+ return output;
+}
+
+/** Pure decision layer: identical activity and policy inputs always produce the same EDL. */
+export function decideMulticamEdit(
+ activity: MulticamActivityMap,
+ policy: MulticamEditPolicy = DEFAULT_MULTICAM_EDIT_POLICY,
+): MulticamEditDecisionList {
+ const runs = suppressBackchannels(
+ candidateRuns(activity, policy),
+ finiteNonNegative(policy.backchannelMaxMs, 0) / 1_000,
+ );
+ const speakerSegments = buildSpeakerSegments(runs, activity.duration, policy);
+ return {
+ duration: activity.duration,
+ segments: addReactionShots(speakerSegments, activity, policy),
+ };
+}
diff --git a/packages/core/src/multicam/bleed-calibration.test.ts b/packages/core/src/multicam/bleed-calibration.test.ts
new file mode 100644
index 00000000..7494c3df
--- /dev/null
+++ b/packages/core/src/multicam/bleed-calibration.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import {
+ calibrateMulticamBleed,
+ correctMulticamBleedEnergies,
+} from "./bleed-calibration";
+
+const samples = (amplitude: number): Float32Array =>
+ Float32Array.from({ length: 1_000 }, (_, index) =>
+ amplitude * Math.sin((index / 1_000) * Math.PI * 40),
+ );
+
+describe("multicam bleed calibration", () => {
+ it("learns directional bleed ratios from isolated speech", () => {
+ const calibration = calibrateMulticamBleed(
+ [
+ { angleId: "a", samples: samples(1), sampleRate: 1_000 },
+ { angleId: "b", samples: samples(0.2), sampleRate: 1_000 },
+ ],
+ [{ speakerAngleId: "a", startTime: 0, endTime: 1 }],
+ );
+
+ expect(calibration.ratios.a?.b).toBeCloseTo(0.2, 2);
+ expect(calibration.ratios.a?.a).toBe(1);
+ });
+
+ it("subtracts predicted bleed while preserving independent speech", () => {
+ const calibration = {
+ spec: "openreel-bleed-calibration/v1" as const,
+ angleIds: ["a", "b"],
+ ratios: { a: { a: 1, b: 0.2 }, b: { a: 0.1, b: 1 } },
+ noiseFloor: { a: 0, b: 0 },
+ };
+
+ expect(correctMulticamBleedEnergies({ a: 1, b: 0.2 }, calibration)).toEqual({
+ a: 0.98,
+ b: 0,
+ });
+ expect(correctMulticamBleedEnergies({ a: 1, b: 0.8 }, calibration).b).toBeCloseTo(
+ 0.6,
+ );
+ });
+});
diff --git a/packages/core/src/multicam/bleed-calibration.ts b/packages/core/src/multicam/bleed-calibration.ts
new file mode 100644
index 00000000..5f527eaa
--- /dev/null
+++ b/packages/core/src/multicam/bleed-calibration.ts
@@ -0,0 +1,132 @@
+export const MULTICAM_BLEED_CALIBRATION_SPEC =
+ "openreel-bleed-calibration/v1" as const;
+
+export interface MulticamCalibrationSource {
+ angleId: string;
+ samples: Float32Array;
+ sampleRate: number;
+}
+
+export interface MulticamCalibrationRange {
+ /** The participant/microphone intentionally speaking alone. */
+ speakerAngleId: string;
+ startTime: number;
+ endTime: number;
+}
+
+export interface MulticamBleedCalibration {
+ spec: typeof MULTICAM_BLEED_CALIBRATION_SPEC;
+ angleIds: string[];
+ /** ratios[speaker][receiver] is expected bleed energy at receiver. */
+ ratios: Record<string, Record<string, number>>;
+ noiseFloor: Record<string, number>;
+}
+
+function rmsRange(
+ source: MulticamCalibrationSource,
+ startTime: number,
+ endTime: number,
+): number {
+ const start = Math.max(0, Math.floor(startTime * source.sampleRate));
+ const end = Math.min(source.samples.length, Math.ceil(endTime * source.sampleRate));
+ if (end <= start) return 0;
+ const stride = Math.max(1, Math.floor(source.sampleRate / 2_000));
+ let sum = 0;
+ let count = 0;
+ for (let index = start; index < end; index += stride) {
+ const sample = source.samples[index] ?? 0;
+ sum += sample * sample;
+ count++;
+ }
+ return count ? Math.sqrt(sum / count) : 0;
+}
+
+function median(values: readonly number[]): number {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ const middle = Math.floor(sorted.length / 2);
+ return sorted.length % 2
+ ? (sorted[middle] ?? 0)
+ : ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
+}
+
+/** Learns cross-channel bleed ratios from isolated speaking calibration ranges. */
+export function calibrateMulticamBleed(
+ sources: readonly MulticamCalibrationSource[],
+ ranges: readonly MulticamCalibrationRange[],
+ silenceRange?: { startTime: number; endTime: number },
+): MulticamBleedCalibration {
+ const angleIds = sources.map((source) => source.angleId);
+ const ratios: Record<string, Record<string, number>> = {};
+ const noiseFloor: Record<string, number> = {};
+ for (const source of sources) {
+ noiseFloor[source.angleId] = silenceRange
+ ? rmsRange(source, silenceRange.startTime, silenceRange.endTime)
+ : 0;
+ }
+
+ for (const speakerAngleId of angleIds) {
+ ratios[speakerAngleId] = {};
+ const speakerRanges = ranges.filter(
+ (range) =>
+ range.speakerAngleId === speakerAngleId && range.endTime > range.startTime,
+ );
+ const speaker = sources.find((source) => source.angleId === speakerAngleId);
+ for (const receiver of sources) {
+ if (receiver.angleId === speakerAngleId) {
+ ratios[speakerAngleId][receiver.angleId] = 1;
+ continue;
+ }
+ const measurements = speakerRanges.flatMap((range) => {
+ if (!speaker) return [];
+ const speakerEnergy = Math.max(
+ 0,
+ rmsRange(speaker, range.startTime, range.endTime) -
+ (noiseFloor[speakerAngleId] ?? 0),
+ );
+ const receiverEnergy = Math.max(
+ 0,
+ rmsRange(receiver, range.startTime, range.endTime) -
+ (noiseFloor[receiver.angleId] ?? 0),
+ );
+ return speakerEnergy > 0 ? [receiverEnergy / speakerEnergy] : [];
+ });
+ ratios[speakerAngleId][receiver.angleId] = Math.max(
+ 0,
+ Math.min(1, median(measurements)),
+ );
+ }
+ }
+ return {
+ spec: MULTICAM_BLEED_CALIBRATION_SPEC,
+ angleIds,
+ ratios,
+ noiseFloor,
+ };
+}
+
+/** Removes energy predicted by the learned cross-channel bleed matrix. */
+export function correctMulticamBleedEnergies(
+ energies: Readonly<Record<string, number>>,
+ calibration?: MulticamBleedCalibration,
+): Record<string, number> {
+ if (!calibration) return { ...energies };
+ const corrected: Record<string, number> = {};
+ for (const receiver of calibration.angleIds) {
+ const measured = Math.max(
+ 0,
+ (energies[receiver] ?? 0) - (calibration.noiseFloor[receiver] ?? 0),
+ );
+ let predictedBleed = 0;
+ for (const speaker of calibration.angleIds) {
+ if (speaker === receiver) continue;
+ predictedBleed = Math.max(
+ predictedBleed,
+ Math.max(0, energies[speaker] ?? 0) *
+ (calibration.ratios[speaker]?.[receiver] ?? 0),
+ );
+ }
+ corrected[receiver] = Math.max(0, measured - predictedBleed);
+ }
+ return corrected;
+}
diff --git a/packages/core/src/multicam/cut-review.test.ts b/packages/core/src/multicam/cut-review.test.ts
new file mode 100644
index 00000000..ad7f2c59
--- /dev/null
+++ b/packages/core/src/multicam/cut-review.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import {
+ acceptMulticamCut,
+ createMulticamCutReview,
+ nudgeMulticamCut,
+ rejectMulticamCut,
+ reviewedMulticamEdit,
+} from "./cut-review";
+
+const edit = {
+ duration: 6,
+ segments: [
+ { angleId: "a", startTime: 0, endTime: 2, reason: "speaker" as const, confidence: 1 },
+ { angleId: "b", startTime: 2, endTime: 4, reason: "speaker" as const, confidence: 1 },
+ { angleId: "a", startTime: 4, endTime: 6, reason: "speaker" as const, confidence: 1 },
+ ],
+};
+
+describe("multicam cut review", () => {
+ it("accepts, rejects, and nudges generated cuts", () => {
+ const review = createMulticamCutReview(edit);
+ const secondId = review.segments[1]!.reviewId;
+ expect(acceptMulticamCut(review, secondId).segments[1]?.status).toBe("accepted");
+ const nudged = nudgeMulticamCut(review, secondId, 250);
+ expect(nudged.segments[0]?.endTime).toBe(2.25);
+ expect(nudged.segments[1]?.startTime).toBe(2.25);
+ const rejected = rejectMulticamCut(review, secondId);
+ expect(reviewedMulticamEdit(rejected).segments).toHaveLength(1);
+ expect(reviewedMulticamEdit(rejected).segments[0]).toMatchObject({
+ angleId: "a",
+ startTime: 0,
+ endTime: 6,
+ });
+ });
+});
diff --git a/packages/core/src/multicam/cut-review.ts b/packages/core/src/multicam/cut-review.ts
new file mode 100644
index 00000000..8674b09b
--- /dev/null
+++ b/packages/core/src/multicam/cut-review.ts
@@ -0,0 +1,102 @@
+import type {
+ MulticamEditDecision,
+ MulticamEditDecisionList,
+} from "./automatic-edit";
+
+export type MulticamCutReviewStatus = "pending" | "accepted";
+
+export interface MulticamReviewedDecision extends MulticamEditDecision {
+ reviewId: string;
+ status: MulticamCutReviewStatus;
+}
+
+export interface MulticamCutReview {
+ duration: number;
+ segments: MulticamReviewedDecision[];
+}
+
+function normalize(segments: readonly MulticamReviewedDecision[]): MulticamReviewedDecision[] {
+ const output: MulticamReviewedDecision[] = [];
+ for (const segment of segments) {
+ const previous = output[output.length - 1];
+ if (previous && previous.angleId === segment.angleId) {
+ previous.endTime = segment.endTime;
+ previous.confidence = Math.max(previous.confidence, segment.confidence);
+ } else {
+ output.push({ ...segment });
+ }
+ }
+ return output;
+}
+
+export function createMulticamCutReview(
+ edit: MulticamEditDecisionList,
+): MulticamCutReview {
+ return {
+ duration: edit.duration,
+ segments: edit.segments.map((segment, index) => ({
+ ...segment,
+ reviewId: `cut-${Math.round(segment.startTime * 1_000)}-${index}`,
+ status: index === 0 ? "accepted" : "pending",
+ })),
+ };
+}
+
+export function acceptMulticamCut(
+ review: MulticamCutReview,
+ reviewId: string,
+): MulticamCutReview {
+ return {
+ ...review,
+ segments: review.segments.map((segment) =>
+ segment.reviewId === reviewId ? { ...segment, status: "accepted" } : segment,
+ ),
+ };
+}
+
+/** Rejecting a cut holds the previous angle through the rejected segment. */
+export function rejectMulticamCut(
+ review: MulticamCutReview,
+ reviewId: string,
+): MulticamCutReview {
+ const index = review.segments.findIndex((segment) => segment.reviewId === reviewId);
+ if (index <= 0) return review;
+ const segments = review.segments.map((segment) => ({ ...segment }));
+ const previous = segments[index - 1]!;
+ const rejected = segments[index]!;
+ previous.endTime = rejected.endTime;
+ segments.splice(index, 1);
+ return { ...review, segments: normalize(segments) };
+}
+
+/** Nudges a cut while preserving a minimum handle on both adjacent shots. */
+export function nudgeMulticamCut(
+ review: MulticamCutReview,
+ reviewId: string,
+ deltaMs: number,
+ minimumShotMs = 100,
+): MulticamCutReview {
+ const index = review.segments.findIndex((segment) => segment.reviewId === reviewId);
+ if (index <= 0 || !Number.isFinite(deltaMs)) return review;
+ const segments = review.segments.map((segment) => ({ ...segment }));
+ const previous = segments[index - 1]!;
+ const current = segments[index]!;
+ const minimum = Math.max(0, minimumShotMs) / 1_000;
+ const boundary = Math.min(
+ current.endTime - minimum,
+ Math.max(previous.startTime + minimum, current.startTime + deltaMs / 1_000),
+ );
+ previous.endTime = boundary;
+ current.startTime = boundary;
+ current.status = "pending";
+ return { ...review, segments };
+}
+
+export function reviewedMulticamEdit(
+ review: MulticamCutReview,
+): MulticamEditDecisionList {
+ return {
+ duration: review.duration,
+ segments: review.segments.map(({ reviewId: _reviewId, status: _status, ...segment }) => segment),
+ };
+}
diff --git a/packages/core/src/multicam/drift.test.ts b/packages/core/src/multicam/drift.test.ts
new file mode 100644
index 00000000..c3167e3e
--- /dev/null
+++ b/packages/core/src/multicam/drift.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import {
+ analyzeMulticamDrift,
+ fitMulticamDriftModel,
+ multicamOffsetAt,
+ multicamSourceTime,
+} from "./drift";
+
+describe("multicam drift", () => {
+ it("fits a weighted linear clock model", () => {
+ const model = fitMulticamDriftModel([
+ { timeSeconds: 0, offsetSeconds: 0.1, confidence: 1 },
+ { timeSeconds: 1_800, offsetSeconds: 0.19, confidence: 0.9 },
+ { timeSeconds: 3_600, offsetSeconds: 0.28, confidence: 1 },
+ ]);
+
+ expect(model.interceptSeconds).toBeCloseTo(0.1, 5);
+ expect(model.partsPerMillion).toBeCloseTo(50, 2);
+ expect(multicamOffsetAt(model, 3_600)).toBeCloseTo(0.28, 5);
+ expect(multicamSourceTime(model, 100)).toBeCloseTo(100.105, 4);
+ });
+
+ it("measures a fixed offset with FFT block correlation", () => {
+ const sampleRate = 1_000;
+ const duration = 12;
+ const reference = new Float32Array(sampleRate * duration);
+ for (let index = 0; index < reference.length; index++) {
+ reference[index] =
+ Math.sin(index * 0.071) * 0.6 + Math.sin(index * 0.019) * 0.3;
+ }
+ const target = new Float32Array(reference.length);
+ const delay = 0.2 * sampleRate;
+ for (let index = delay; index < target.length; index++) {
+ target[index] = reference[index - delay] ?? 0;
+ }
+
+ const model = analyzeMulticamDrift(reference, target, sampleRate, {
+ blockSeconds: 2,
+ intervalSeconds: 3,
+ maxOffsetSeconds: 0.5,
+ analysisSampleRate: 250,
+ });
+
+ expect(model.interceptSeconds).toBeCloseTo(0.2, 2);
+ expect(model.confidence).toBeGreaterThan(0.8);
+ });
+});
diff --git a/packages/core/src/multicam/drift.ts b/packages/core/src/multicam/drift.ts
new file mode 100644
index 00000000..bf78a530
--- /dev/null
+++ b/packages/core/src/multicam/drift.ts
@@ -0,0 +1,231 @@
+import { FFT } from "../audio/fft";
+
+export interface MulticamDriftObservation {
+ timeSeconds: number;
+ offsetSeconds: number;
+ confidence: number;
+}
+
+export interface MulticamDriftModel {
+ /** Offset at timeline time zero. */
+ interceptSeconds: number;
+ /** Additional source seconds accumulated per timeline second. */
+ secondsPerSecond: number;
+ partsPerMillion: number;
+ confidence: number;
+ observations: MulticamDriftObservation[];
+}
+
+export interface MulticamDriftAnalysisOptions {
+ blockSeconds?: number;
+ intervalSeconds?: number;
+ maxOffsetSeconds?: number;
+ analysisSampleRate?: number;
+}
+
+const nextPowerOfTwo = (value: number): number => {
+ let result = 1;
+ while (result < value) result *= 2;
+ return result;
+};
+
+function resampleAt(
+ samples: Float32Array,
+ sampleRate: number,
+ startTime: number,
+ duration: number,
+ targetRate: number,
+): Float32Array {
+ const length = Math.max(0, Math.floor(duration * targetRate));
+ const result = new Float32Array(length);
+ for (let index = 0; index < length; index++) {
+ const position = (startTime + index / targetRate) * sampleRate;
+ const left = Math.floor(position);
+ const right = Math.min(samples.length - 1, left + 1);
+ if (left < 0 || left >= samples.length) continue;
+ const fraction = position - left;
+ result[index] =
+ (samples[left] ?? 0) * (1 - fraction) + (samples[right] ?? 0) * fraction;
+ }
+ return result;
+}
+
+function removeMean(samples: Float32Array): Float32Array {
+ if (samples.length === 0) return samples;
+ let mean = 0;
+ for (const sample of samples) mean += sample;
+ mean /= samples.length;
+ return Float32Array.from(samples, (sample) => sample - mean);
+}
+
+function fftBlockOffset(
+ reference: Float32Array,
+ target: Float32Array,
+ maxOffsetSamples: number,
+ sampleRate: number,
+): { offsetSeconds: number; confidence: number } {
+ if (reference.length === 0 || target.length < reference.length) {
+ return { offsetSeconds: 0, confidence: 0 };
+ }
+ const centeredReference = removeMean(reference);
+ const centeredTarget = removeMean(target);
+ const fftSize = nextPowerOfTwo(centeredReference.length + centeredTarget.length - 1);
+ const reversedReference = new Float32Array(fftSize);
+ for (let index = 0; index < centeredReference.length; index++) {
+ reversedReference[index] = centeredReference[centeredReference.length - 1 - index] ?? 0;
+ }
+ const paddedTarget = new Float32Array(fftSize);
+ paddedTarget.set(centeredTarget);
+
+ const fft = new FFT(fftSize);
+ const referenceSpectrum = fft.forward(reversedReference);
+ const targetSpectrum = fft.forward(paddedTarget);
+ const real = new Float32Array(fftSize);
+ const imag = new Float32Array(fftSize);
+ for (let index = 0; index < fftSize; index++) {
+ real[index] =
+ targetSpectrum.real[index] * referenceSpectrum.real[index] -
+ targetSpectrum.imag[index] * referenceSpectrum.imag[index];
+ imag[index] =
+ targetSpectrum.real[index] * referenceSpectrum.imag[index] +
+ targetSpectrum.imag[index] * referenceSpectrum.real[index];
+ }
+ const correlation = fft.inverse(real, imag);
+
+ let referenceEnergy = 0;
+ for (const sample of centeredReference) referenceEnergy += sample * sample;
+ const energyPrefix = new Float64Array(centeredTarget.length + 1);
+ for (let index = 0; index < centeredTarget.length; index++) {
+ const sample = centeredTarget[index] ?? 0;
+ energyPrefix[index + 1] = (energyPrefix[index] ?? 0) + sample * sample;
+ }
+
+ let bestLag = 0;
+ let bestScore = -1;
+ for (let lag = -maxOffsetSamples; lag <= maxOffsetSamples; lag++) {
+ const targetStart = maxOffsetSamples + lag;
+ const targetEnd = targetStart + centeredReference.length;
+ if (targetStart < 0 || targetEnd > centeredTarget.length) continue;
+ const targetEnergy =
+ (energyPrefix[targetEnd] ?? 0) - (energyPrefix[targetStart] ?? 0);
+ const denominator = Math.sqrt(referenceEnergy * targetEnergy);
+ const convolutionIndex = targetStart + centeredReference.length - 1;
+ const score = denominator > 0 ? (correlation[convolutionIndex] ?? 0) / denominator : 0;
+ if (score > bestScore) {
+ bestScore = score;
+ bestLag = lag;
+ }
+ }
+ return {
+ offsetSeconds: bestLag / sampleRate,
+ confidence: Math.max(0, Math.min(1, bestScore)),
+ };
+}
+
+export function fitMulticamDriftModel(
+ observations: readonly MulticamDriftObservation[],
+): MulticamDriftModel {
+ const valid = observations.filter(
+ (entry) =>
+ Number.isFinite(entry.timeSeconds) &&
+ Number.isFinite(entry.offsetSeconds) &&
+ Number.isFinite(entry.confidence) &&
+ entry.confidence > 0,
+ );
+ if (valid.length === 0) {
+ return {
+ interceptSeconds: 0,
+ secondsPerSecond: 0,
+ partsPerMillion: 0,
+ confidence: 0,
+ observations: [],
+ };
+ }
+ let weight = 0;
+ let weightedX = 0;
+ let weightedY = 0;
+ for (const entry of valid) {
+ weight += entry.confidence;
+ weightedX += entry.timeSeconds * entry.confidence;
+ weightedY += entry.offsetSeconds * entry.confidence;
+ }
+ const meanX = weightedX / weight;
+ const meanY = weightedY / weight;
+ let covariance = 0;
+ let variance = 0;
+ for (const entry of valid) {
+ const x = entry.timeSeconds - meanX;
+ covariance += entry.confidence * x * (entry.offsetSeconds - meanY);
+ variance += entry.confidence * x * x;
+ }
+ const secondsPerSecond = variance > 0 ? covariance / variance : 0;
+ const interceptSeconds = meanY - secondsPerSecond * meanX;
+ const confidence = weight / valid.length;
+ return {
+ interceptSeconds,
+ secondsPerSecond,
+ partsPerMillion: secondsPerSecond * 1_000_000,
+ confidence: Math.max(0, Math.min(1, confidence)),
+ observations: valid.map((entry) => ({ ...entry })),
+ };
+}
+
+export function multicamOffsetAt(
+ model: Pick<MulticamDriftModel, "interceptSeconds" | "secondsPerSecond">,
+ timelineTime: number,
+): number {
+ return model.interceptSeconds + model.secondsPerSecond * timelineTime;
+}
+
+export function multicamSourceTime(
+ model: Pick<MulticamDriftModel, "interceptSeconds" | "secondsPerSecond">,
+ timelineTime: number,
+): number {
+ return timelineTime + multicamOffsetAt(model, timelineTime);
+}
+
+/** Measures block offsets with FFT cross-correlation, then fits linear clock drift. */
+export function analyzeMulticamDrift(
+ reference: Float32Array,
+ target: Float32Array,
+ sampleRate: number,
+ options: MulticamDriftAnalysisOptions = {},
+): MulticamDriftModel {
+ const blockSeconds = Math.max(1, options.blockSeconds ?? 5);
+ const intervalSeconds = Math.max(blockSeconds, options.intervalSeconds ?? 300);
+ const maxOffsetSeconds = Math.max(0.05, options.maxOffsetSeconds ?? 2);
+ const analysisSampleRate = Math.max(100, options.analysisSampleRate ?? 400);
+ const duration = Math.min(reference.length, target.length) / sampleRate;
+ const observations: MulticamDriftObservation[] = [];
+ for (
+ let startTime = maxOffsetSeconds;
+ startTime + blockSeconds + maxOffsetSeconds <= duration;
+ startTime += intervalSeconds
+ ) {
+ const refBlock = resampleAt(
+ reference,
+ sampleRate,
+ startTime,
+ blockSeconds,
+ analysisSampleRate,
+ );
+ const targetBlock = resampleAt(
+ target,
+ sampleRate,
+ startTime - maxOffsetSeconds,
+ blockSeconds + maxOffsetSeconds * 2,
+ analysisSampleRate,
+ );
+ const measured = fftBlockOffset(
+ refBlock,
+ targetBlock,
+ Math.round(maxOffsetSeconds * analysisSampleRate),
+ analysisSampleRate,
+ );
+ observations.push({
+ timeSeconds: startTime + blockSeconds / 2,
+ ...measured,
+ });
+ }
+ return fitMulticamDriftModel(observations);
+}
diff --git a/packages/core/src/multicam/index.ts b/packages/core/src/multicam/index.ts
new file mode 100644
index 00000000..ba215902
--- /dev/null
+++ b/packages/core/src/multicam/index.ts
@@ -0,0 +1,11 @@
+export * from "./automatic-edit";
+export * from "./manifest";
+export * from "./drift";
+export * from "./bleed-calibration";
+export * from "./orma";
+export * from "./silero-vad";
+export * from "./shot-planner";
+export * from "./cut-review";
+export * from "./otio";
+export * from "./reaction-analysis";
+export * from "./social-clips";
diff --git a/packages/core/src/multicam/manifest.test.ts b/packages/core/src/multicam/manifest.test.ts
new file mode 100644
index 00000000..e3b18b4e
--- /dev/null
+++ b/packages/core/src/multicam/manifest.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import {
+ DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+ manifestConstraintsToPolicy,
+ parseMulticamManifest,
+ serializeMulticamManifest,
+ validateMulticamManifest,
+ type MulticamManifest,
+} from "./manifest";
+
+const manifest = (): MulticamManifest => ({
+ spec: "openreel-multicam/v1",
+ fps: 25,
+ sync: { method: "audio-crosscorr", reference: "wide" },
+ participants: [
+ { id: "p1", name: "Alex", audio: "track-1", seat: "left" },
+ { id: "p2", name: "Jamie", audio: "track-2", seat: "right" },
+ ],
+ cameras: [
+ { id: "a", type: "closeup", subject: "p1", file: "A001.mp4" },
+ { id: "b", type: "closeup", subject: "p2", file: "B001.mp4" },
+ { id: "wide", type: "wide", subject: "all", file: "C001.mp4" },
+ ],
+ constraints: { ...DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS },
+});
+
+describe("validateMulticamManifest", () => {
+ it("accepts the openreel-multicam/v1 shoot specification", () => {
+ expect(validateMulticamManifest(manifest())).toEqual({ valid: true, errors: [] });
+ });
+
+ it("requires isolated mics, valid subjects, a wide shot, and a sync reference", () => {
+ const invalid = manifest();
+ invalid.participants = invalid.participants.slice(0, 1);
+ invalid.cameras = [
+ { id: "a", type: "closeup", subject: "missing", file: "A001.mp4" },
+ { id: "a", type: "closeup", subject: "p1", file: "B001.mp4" },
+ ];
+ invalid.sync.reference = "missing";
+
+ const result = validateMulticamManifest(invalid);
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toEqual(
+ expect.arrayContaining([
+ "participants must contain at least two isolated microphones",
+ "cameras[0].subject references unknown participant missing",
+ "camera id a is duplicated",
+ "cameras must include at least one locked-off wide shot",
+ "sync.reference missing is not a camera",
+ ]),
+ );
+ });
+
+ it("maps manifest constraints into engine policy fields", () => {
+ expect(manifestConstraintsToPolicy(DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS)).toMatchObject({
+ minShotMs: 1_800,
+ maxShotMs: 25_000,
+ cutLeadMs: 120,
+ reactionShotAfterMs: 12_000,
+ forbidJumpCutSameSubject: true,
+ });
+ });
+
+ it("parses equivalent JSON and YAML shoot manifests", () => {
+ const value = manifest();
+ const json = parseMulticamManifest(JSON.stringify(value));
+ const yaml = parseMulticamManifest(serializeMulticamManifest(value, "yaml"));
+
+ expect(json).toEqual(value);
+ expect(yaml).toEqual(value);
+ });
+});
diff --git a/packages/core/src/multicam/manifest.ts b/packages/core/src/multicam/manifest.ts
new file mode 100644
index 00000000..435c70fd
--- /dev/null
+++ b/packages/core/src/multicam/manifest.ts
@@ -0,0 +1,258 @@
+import type { MulticamEditPolicy } from "./automatic-edit";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+
+export const MULTICAM_MANIFEST_SPEC = "openreel-multicam/v1" as const;
+
+export type MulticamCameraType =
+ | "closeup"
+ | "wide"
+ | "two-shot"
+ | "reaction";
+export type MulticamSeat = "left" | "center" | "right" | number;
+
+export interface MulticamManifestParticipant {
+ id: string;
+ name: string;
+ /** Audio media/track identifier mapped to this isolated microphone. */
+ audio: string;
+ seat: MulticamSeat;
+}
+
+export interface MulticamManifestCamera {
+ id: string;
+ type: MulticamCameraType;
+ /** Participant id, a '+'-joined participant list, or 'all'. */
+ subject: string;
+ /** Original file hint used to resolve/relink the camera source. */
+ file: string;
+ /** Optional resolved OpenReel timeline clip id. */
+ clipId?: string;
+ /** Runtime angle mapping; camera id/file remain the shoot-authored identity. */
+ angleId?: string;
+}
+
+export interface MulticamManifestSync {
+ method: "audio-crosscorr" | "timecode" | "manual";
+ reference: string;
+ block_seconds?: number;
+ max_offset_seconds?: number;
+}
+
+export interface MulticamManifestConstraints {
+ min_shot_ms: number;
+ max_shot_ms: number;
+ cut_lead_ms: number;
+ reaction_shot_after_ms: number;
+ forbid_jump_cut_same_subject: boolean;
+}
+
+export interface MulticamManifest {
+ spec: typeof MULTICAM_MANIFEST_SPEC;
+ fps: number;
+ sync: MulticamManifestSync;
+ participants: MulticamManifestParticipant[];
+ cameras: MulticamManifestCamera[];
+ constraints: MulticamManifestConstraints;
+}
+
+export interface MulticamManifestValidation {
+ valid: boolean;
+ errors: string[];
+}
+
+export const DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS: MulticamManifestConstraints = {
+ min_shot_ms: 1_800,
+ max_shot_ms: 25_000,
+ cut_lead_ms: 120,
+ reaction_shot_after_ms: 12_000,
+ forbid_jump_cut_same_subject: true,
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function requiredString(
+ value: unknown,
+ path: string,
+ errors: string[],
+): value is string {
+ if (typeof value === "string" && value.trim().length > 0) return true;
+ errors.push(`${path} is required`);
+ return false;
+}
+
+function positiveNumber(value: unknown, path: string, errors: string[]): void {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ errors.push(`${path} must be a positive number`);
+ }
+}
+
+/** Validates parsed multicam.json or multicam.yaml content against v1. */
+export function validateMulticamManifest(
+ value: unknown,
+): MulticamManifestValidation {
+ const errors: string[] = [];
+ if (!isRecord(value)) {
+ return { valid: false, errors: ["Manifest must be an object"] };
+ }
+ if (value.spec !== MULTICAM_MANIFEST_SPEC) {
+ errors.push(`spec must be ${MULTICAM_MANIFEST_SPEC}`);
+ }
+ positiveNumber(value.fps, "fps", errors);
+
+ const participants = Array.isArray(value.participants) ? value.participants : [];
+ if (participants.length < 2) {
+ errors.push("participants must contain at least two isolated microphones");
+ }
+ const participantIds = new Set<string>();
+ participants.forEach((entry, index) => {
+ const path = `participants[${index}]`;
+ if (!isRecord(entry)) {
+ errors.push(`${path} must be an object`);
+ return;
+ }
+ if (requiredString(entry.id, `${path}.id`, errors)) {
+ if (participantIds.has(entry.id)) errors.push(`participant id ${entry.id} is duplicated`);
+ participantIds.add(entry.id);
+ }
+ requiredString(entry.name, `${path}.name`, errors);
+ requiredString(entry.audio, `${path}.audio`, errors);
+ if (
+ entry.seat !== "left" &&
+ entry.seat !== "center" &&
+ entry.seat !== "right" &&
+ (typeof entry.seat !== "number" || !Number.isFinite(entry.seat))
+ ) {
+ errors.push(`${path}.seat must be left, center, right, or a numeric order`);
+ }
+ });
+
+ const cameras = Array.isArray(value.cameras) ? value.cameras : [];
+ if (cameras.length < 2) errors.push("cameras must contain at least two angles");
+ const cameraIds = new Set<string>();
+ let hasWide = false;
+ cameras.forEach((entry, index) => {
+ const path = `cameras[${index}]`;
+ if (!isRecord(entry)) {
+ errors.push(`${path} must be an object`);
+ return;
+ }
+ if (requiredString(entry.id, `${path}.id`, errors)) {
+ if (cameraIds.has(entry.id)) errors.push(`camera id ${entry.id} is duplicated`);
+ cameraIds.add(entry.id);
+ }
+ if (
+ !(["closeup", "wide", "two-shot", "reaction"] as const).includes(
+ entry.type as MulticamCameraType,
+ )
+ ) {
+ errors.push(`${path}.type is invalid`);
+ }
+ if (entry.type === "wide") hasWide = true;
+ if (requiredString(entry.subject, `${path}.subject`, errors)) {
+ const subjects = entry.subject === "all" ? [] : entry.subject.split("+");
+ for (const subject of subjects) {
+ if (!participantIds.has(subject)) {
+ errors.push(`${path}.subject references unknown participant ${subject}`);
+ }
+ }
+ }
+ requiredString(entry.file, `${path}.file`, errors);
+ });
+ if (!hasWide) errors.push("cameras must include at least one locked-off wide shot");
+
+ if (!isRecord(value.sync)) {
+ errors.push("sync is required");
+ } else {
+ if (
+ !(["audio-crosscorr", "timecode", "manual"] as const).includes(
+ value.sync.method as MulticamManifestSync["method"],
+ )
+ ) {
+ errors.push("sync.method is invalid");
+ }
+ if (
+ requiredString(value.sync.reference, "sync.reference", errors) &&
+ !cameraIds.has(value.sync.reference)
+ ) {
+ errors.push(`sync.reference ${value.sync.reference} is not a camera`);
+ }
+ }
+
+ if (!isRecord(value.constraints)) {
+ errors.push("constraints are required");
+ } else {
+ for (const key of [
+ "min_shot_ms",
+ "max_shot_ms",
+ "reaction_shot_after_ms",
+ ] as const) {
+ positiveNumber(value.constraints[key], `constraints.${key}`, errors);
+ }
+ if (
+ typeof value.constraints.cut_lead_ms !== "number" ||
+ !Number.isFinite(value.constraints.cut_lead_ms) ||
+ value.constraints.cut_lead_ms < 0
+ ) {
+ errors.push("constraints.cut_lead_ms must be a non-negative number");
+ }
+ if (typeof value.constraints.forbid_jump_cut_same_subject !== "boolean") {
+ errors.push("constraints.forbid_jump_cut_same_subject must be boolean");
+ }
+ if (
+ typeof value.constraints.min_shot_ms === "number" &&
+ typeof value.constraints.max_shot_ms === "number" &&
+ value.constraints.max_shot_ms < value.constraints.min_shot_ms
+ ) {
+ errors.push("constraints.max_shot_ms must be >= min_shot_ms");
+ }
+ }
+
+ return { valid: errors.length === 0, errors };
+}
+
+export function manifestConstraintsToPolicy(
+ constraints: MulticamManifestConstraints,
+ overrides: Partial<MulticamEditPolicy> = {},
+): Partial<MulticamEditPolicy> {
+ return {
+ minShotMs: constraints.min_shot_ms,
+ maxShotMs: constraints.max_shot_ms,
+ cutLeadMs: constraints.cut_lead_ms,
+ reactionShotAfterMs: constraints.reaction_shot_after_ms,
+ forbidJumpCutSameSubject: constraints.forbid_jump_cut_same_subject,
+ ...overrides,
+ };
+}
+
+export function parseMulticamManifest(
+ contents: string,
+ format: "json" | "yaml" | "auto" = "auto",
+): MulticamManifest {
+ let parsed: unknown;
+ try {
+ const trimmed = contents.trim();
+ parsed = format === "json" || (format === "auto" && (trimmed.startsWith("{") || trimmed.startsWith("[")))
+ ? JSON.parse(trimmed)
+ : parseYaml(trimmed);
+ } catch (error) {
+ throw new Error(
+ `Could not parse multicam manifest: ${error instanceof Error ? error.message : "invalid syntax"}`,
+ );
+ }
+ const validation = validateMulticamManifest(parsed);
+ if (!validation.valid) {
+ throw new Error(`Invalid multicam manifest: ${validation.errors.join("; ")}`);
+ }
+ return parsed as MulticamManifest;
+}
+
+export function serializeMulticamManifest(
+ manifest: MulticamManifest,
+ format: "json" | "yaml" = "json",
+): string {
+ return format === "json"
+ ? JSON.stringify(manifest, null, 2)
+ : stringifyYaml(manifest);
+}
diff --git a/packages/core/src/multicam/orma.test.ts b/packages/core/src/multicam/orma.test.ts
new file mode 100644
index 00000000..1c03842f
--- /dev/null
+++ b/packages/core/src/multicam/orma.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS } from "./manifest";
+import {
+ createOrmaArtifact,
+ deserializeOrma,
+ isOrmaCompatible,
+ serializeOrma,
+} from "./orma";
+
+const manifest = {
+ spec: "openreel-multicam/v1" as const,
+ fps: 25,
+ sync: { method: "audio-crosscorr" as const, reference: "wide" },
+ participants: [
+ { id: "p1", name: "Alex", audio: "a", seat: "left" as const },
+ { id: "p2", name: "Jamie", audio: "b", seat: "right" as const },
+ ],
+ cameras: [
+ { id: "a", type: "closeup" as const, subject: "p1", file: "a.mp4" },
+ { id: "b", type: "closeup" as const, subject: "p2", file: "b.mp4" },
+ { id: "wide", type: "wide" as const, subject: "all", file: "wide.mp4" },
+ ],
+ constraints: DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+};
+
+const media = [
+ { id: "a", name: "a.mp4", size: 100, lastModified: 10 },
+ { id: "b", name: "b.mp4", size: 200, lastModified: 20 },
+];
+
+describe(".orma activity artifacts", () => {
+ it("round-trips reusable analysis separately from the edit policy", () => {
+ const artifact = createOrmaArtifact({
+ manifest,
+ media,
+ createdAt: 123,
+ activity: {
+ angleIds: ["a", "b"],
+ duration: 1,
+ windowMs: 50,
+ points: [
+ {
+ startTime: 0,
+ endTime: 1,
+ activeAngleIds: ["a"],
+ scores: { a: 1, b: 0.1 },
+ },
+ ],
+ },
+ });
+
+ expect(deserializeOrma(serializeOrma(artifact))).toEqual(artifact);
+ expect(isOrmaCompatible(artifact, manifest, [...media].reverse())).toBe(true);
+ });
+
+ it("invalidates the cache when source media changes", () => {
+ const artifact = createOrmaArtifact({
+ manifest,
+ media,
+ activity: { angleIds: [], duration: 0, windowMs: 50, points: [] },
+ });
+
+ expect(
+ isOrmaCompatible(artifact, manifest, [
+ { ...media[0]!, size: 101 },
+ media[1]!,
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/packages/core/src/multicam/orma.ts b/packages/core/src/multicam/orma.ts
new file mode 100644
index 00000000..735c735e
--- /dev/null
+++ b/packages/core/src/multicam/orma.ts
@@ -0,0 +1,126 @@
+import type { MulticamActivityMap } from "./automatic-edit";
+import type { MulticamBleedCalibration } from "./bleed-calibration";
+import type { MulticamDriftModel } from "./drift";
+import type { MulticamManifest } from "./manifest";
+import type { MulticamReactionCue } from "./reaction-analysis";
+
+export const ORMA_SPEC = "openreel-activity/v1" as const;
+
+export interface MulticamTranscriptSegment {
+ startMs: number;
+ endMs: number;
+ text: string;
+ confidence?: number;
+}
+
+export interface OrmaMediaFingerprint {
+ id: string;
+ name: string;
+ size: number;
+ lastModified: number;
+}
+
+export interface OrmaArtifact {
+ spec: typeof ORMA_SPEC;
+ manifestFingerprint: string;
+ mediaFingerprint: string;
+ createdAt: number;
+ durationMs: number;
+ activity: MulticamActivityMap;
+ drift: Record<string, MulticamDriftModel>;
+ calibration?: MulticamBleedCalibration;
+ transcripts?: Record<string, MulticamTranscriptSegment[]>;
+ reactions?: MulticamReactionCue[];
+}
+
+function stableValue(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(stableValue);
+ if (!value || typeof value !== "object") return value;
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, entry]) => [key, stableValue(entry)]),
+ );
+}
+
+function fnv1a(value: string): string {
+ let hash = 0x811c9dc5;
+ for (let index = 0; index < value.length; index++) {
+ hash ^= value.charCodeAt(index);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return (hash >>> 0).toString(16).padStart(8, "0");
+}
+
+export function fingerprintMulticamManifest(manifest: MulticamManifest): string {
+ return `manifest-${fnv1a(JSON.stringify(stableValue(manifest)))}`;
+}
+
+export function fingerprintMulticamMedia(
+ media: readonly OrmaMediaFingerprint[],
+): string {
+ const normalized = [...media].sort((left, right) => left.id.localeCompare(right.id));
+ return `media-${fnv1a(JSON.stringify(stableValue(normalized)))}`;
+}
+
+export function createOrmaArtifact(input: {
+ manifest: MulticamManifest;
+ media: readonly OrmaMediaFingerprint[];
+ activity: MulticamActivityMap;
+ drift?: Record<string, MulticamDriftModel>;
+ calibration?: MulticamBleedCalibration;
+ transcripts?: Record<string, MulticamTranscriptSegment[]>;
+ reactions?: MulticamReactionCue[];
+ createdAt?: number;
+}): OrmaArtifact {
+ return {
+ spec: ORMA_SPEC,
+ manifestFingerprint: fingerprintMulticamManifest(input.manifest),
+ mediaFingerprint: fingerprintMulticamMedia(input.media),
+ createdAt: input.createdAt ?? Date.now(),
+ durationMs: Math.round(input.activity.duration * 1_000),
+ activity: structuredClone(input.activity),
+ drift: structuredClone(input.drift ?? {}),
+ calibration: input.calibration
+ ? structuredClone(input.calibration)
+ : undefined,
+ transcripts: input.transcripts
+ ? structuredClone(input.transcripts)
+ : undefined,
+ reactions: input.reactions ? structuredClone(input.reactions) : undefined,
+ };
+}
+
+export function serializeOrma(artifact: OrmaArtifact): string {
+ return JSON.stringify(artifact);
+}
+
+export function deserializeOrma(serialized: string): OrmaArtifact {
+ const value = JSON.parse(serialized) as Partial<OrmaArtifact>;
+ if (
+ value.spec !== ORMA_SPEC ||
+ typeof value.manifestFingerprint !== "string" ||
+ typeof value.mediaFingerprint !== "string" ||
+ typeof value.createdAt !== "number" ||
+ typeof value.durationMs !== "number" ||
+ !value.activity ||
+ !Array.isArray(value.activity.points) ||
+ !value.drift ||
+ typeof value.drift !== "object"
+ ) {
+ throw new Error("Invalid OpenReel multicam activity artifact");
+ }
+ return value as OrmaArtifact;
+}
+
+export function isOrmaCompatible(
+ artifact: OrmaArtifact,
+ manifest: MulticamManifest,
+ media: readonly OrmaMediaFingerprint[],
+): boolean {
+ return (
+ artifact.spec === ORMA_SPEC &&
+ artifact.manifestFingerprint === fingerprintMulticamManifest(manifest) &&
+ artifact.mediaFingerprint === fingerprintMulticamMedia(media)
+ );
+}
diff --git a/packages/core/src/multicam/otio.test.ts b/packages/core/src/multicam/otio.test.ts
new file mode 100644
index 00000000..fb7e0d34
--- /dev/null
+++ b/packages/core/src/multicam/otio.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import { DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS } from "./manifest";
+import { multicamPlanToOtio } from "./otio";
+
+describe("multicam OTIO export", () => {
+ it("emits one OTIO track for each simultaneous panel", () => {
+ const manifest = {
+ spec: "openreel-multicam/v1" as const,
+ fps: 25,
+ sync: { method: "audio-crosscorr" as const, reference: "wide" },
+ participants: [
+ { id: "p1", name: "A", audio: "a", seat: "left" as const },
+ { id: "p2", name: "B", audio: "b", seat: "right" as const },
+ ],
+ cameras: [
+ { id: "a", type: "closeup" as const, subject: "p1", file: "a.mp4" },
+ { id: "b", type: "closeup" as const, subject: "p2", file: "b.mp4" },
+ { id: "wide", type: "wide" as const, subject: "all", file: "wide.mp4" },
+ ],
+ constraints: DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+ };
+ const otio = multicamPlanToOtio({
+ spec: "openreel-multicam-edit/v1",
+ durationMs: 2_000,
+ shots: [{
+ startMs: 0,
+ endMs: 2_000,
+ reason: "sustained-overlap",
+ confidence: 0.9,
+ transitionIn: { type: "layout-morph", durationMs: 200 },
+ layout: {
+ template: "split2",
+ panels: [
+ { cameraId: "a", subject: "p1", rect: { x: 0, y: 0, width: 0.5, height: 1 } },
+ { cameraId: "b", subject: "p2", rect: { x: 0.5, y: 0, width: 0.5, height: 1 } },
+ ],
+ },
+ }],
+ }, manifest) as unknown as { tracks: { children: Array<{ children: unknown[] }> } };
+
+ expect(otio.tracks.children).toHaveLength(2);
+ expect(otio.tracks.children.every((track) => track.children.length === 1)).toBe(true);
+ });
+});
diff --git a/packages/core/src/multicam/otio.ts b/packages/core/src/multicam/otio.ts
new file mode 100644
index 00000000..11b3b78e
--- /dev/null
+++ b/packages/core/src/multicam/otio.ts
@@ -0,0 +1,101 @@
+import type { MulticamManifest } from "./manifest";
+import type { MulticamShotPlan } from "./shot-planner";
+
+export interface OtioSerializable {
+ OTIO_SCHEMA: string;
+ [key: string]: unknown;
+}
+
+const rationalTime = (value: number, rate: number): OtioSerializable => ({
+ OTIO_SCHEMA: "RationalTime.1",
+ value,
+ rate,
+});
+
+const timeRange = (start: number, duration: number, rate: number): OtioSerializable => ({
+ OTIO_SCHEMA: "TimeRange.1",
+ start_time: rationalTime(start, rate),
+ duration: rationalTime(duration, rate),
+});
+
+/** Exports every planned panel as a standards-shaped OpenTimelineIO video track. */
+export function multicamPlanToOtio(
+ plan: MulticamShotPlan,
+ manifest: MulticamManifest,
+ name = "OpenReel Automatic Multicam Edit",
+): OtioSerializable {
+ const maximumPanels = plan.shots.reduce(
+ (maximum, shot) => Math.max(maximum, shot.layout.panels.length),
+ 1,
+ );
+ const tracks = Array.from({ length: maximumPanels }, (_, panelIndex) => {
+ const children = plan.shots.flatMap((shot) => {
+ const panel = shot.layout.panels[panelIndex];
+ if (!panel) return [];
+ const camera = manifest.cameras.find((entry) => entry.id === panel.cameraId);
+ const startFrames = Math.round((shot.startMs / 1_000) * manifest.fps);
+ const durationFrames = Math.round(
+ ((shot.endMs - shot.startMs) / 1_000) * manifest.fps,
+ );
+ return [{
+ OTIO_SCHEMA: "Clip.2",
+ name: `${camera?.id ?? panel.cameraId} · ${shot.reason}`,
+ source_range: timeRange(startFrames, durationFrames, manifest.fps),
+ media_reference: {
+ OTIO_SCHEMA: "ExternalReference.1",
+ target_url: camera?.file ?? "",
+ available_range: null,
+ metadata: { openreel_camera_id: panel.cameraId },
+ },
+ metadata: {
+ openreel: {
+ subject: panel.subject,
+ layout: shot.layout.template,
+ panel_rect: panel.rect,
+ confidence: shot.confidence,
+ reason: shot.reason,
+ },
+ },
+ }];
+ });
+ return {
+ OTIO_SCHEMA: "Track.1",
+ name: `Multicam panel ${panelIndex + 1}`,
+ kind: "Video",
+ children,
+ source_range: null,
+ effects: [],
+ markers: [],
+ metadata: {},
+ };
+ });
+ return {
+ OTIO_SCHEMA: "Timeline.1",
+ name,
+ global_start_time: rationalTime(0, manifest.fps),
+ tracks: {
+ OTIO_SCHEMA: "Stack.1",
+ name: "tracks",
+ children: tracks,
+ source_range: null,
+ effects: [],
+ markers: [],
+ metadata: {},
+ },
+ metadata: {
+ openreel: {
+ spec: plan.spec,
+ duration_ms: plan.durationMs,
+ manifest_spec: manifest.spec,
+ },
+ },
+ };
+}
+
+export function serializeMulticamOtio(
+ plan: MulticamShotPlan,
+ manifest: MulticamManifest,
+ name?: string,
+): string {
+ return JSON.stringify(multicamPlanToOtio(plan, manifest, name), null, 2);
+}
diff --git a/packages/core/src/multicam/reaction-analysis.test.ts b/packages/core/src/multicam/reaction-analysis.test.ts
new file mode 100644
index 00000000..2636d71a
--- /dev/null
+++ b/packages/core/src/multicam/reaction-analysis.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+import { DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS } from "./manifest";
+import {
+ detectMulticamReactionCues,
+ incorporateMulticamReactionCues,
+} from "./reaction-analysis";
+
+describe("multicam reaction analysis", () => {
+ it("merges adjacent face signals and inserts listener shots", () => {
+ const cues = detectMulticamReactionCues([
+ { participantId: "p2", timeMs: 1_000, smile: 0.8, surprise: 0.1, headMotion: 0.1 },
+ { participantId: "p2", timeMs: 1_500, smile: 0.9, surprise: 0.1, headMotion: 0.1 },
+ ]);
+ expect(cues).toHaveLength(1);
+ const manifest = {
+ spec: "openreel-multicam/v1" as const,
+ fps: 25,
+ sync: { method: "audio-crosscorr" as const, reference: "a" },
+ participants: [
+ { id: "p1", name: "A", audio: "a", seat: "left" as const },
+ { id: "p2", name: "B", audio: "b", seat: "right" as const },
+ ],
+ cameras: [
+ { id: "a", type: "closeup" as const, subject: "p1", file: "a.mp4" },
+ { id: "b", type: "closeup" as const, subject: "p2", file: "b.mp4" },
+ ],
+ constraints: DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+ };
+ const result = incorporateMulticamReactionCues({
+ spec: "openreel-multicam-edit/v1",
+ durationMs: 4_000,
+ shots: [{
+ startMs: 0,
+ endMs: 4_000,
+ layout: { template: "solo", panels: [{ cameraId: "a", subject: "p1", rect: { x: 0, y: 0, width: 1, height: 1 } }] },
+ transitionIn: { type: "cut", durationMs: 0 },
+ reason: "speaker",
+ confidence: 1,
+ }],
+ }, manifest, cues);
+
+ expect(result.shots.some((shot) =>
+ shot.reason === "reaction-shot" && shot.layout.panels[0]?.cameraId === "b",
+ )).toBe(true);
+ });
+});
diff --git a/packages/core/src/multicam/reaction-analysis.ts b/packages/core/src/multicam/reaction-analysis.ts
new file mode 100644
index 00000000..4a2fb275
--- /dev/null
+++ b/packages/core/src/multicam/reaction-analysis.ts
@@ -0,0 +1,124 @@
+import type { MulticamManifest } from "./manifest";
+import type { MulticamShot, MulticamShotPlan } from "./shot-planner";
+
+export interface MulticamFaceSignal {
+ participantId: string;
+ timeMs: number;
+ smile: number;
+ surprise: number;
+ headMotion: number;
+}
+
+export interface MulticamReactionCue {
+ participantId: string;
+ startMs: number;
+ endMs: number;
+ confidence: number;
+ kind: "smile" | "surprise" | "movement";
+}
+
+export function detectMulticamReactionCues(
+ signals: readonly MulticamFaceSignal[],
+ options: { threshold?: number; mergeGapMs?: number; minimumMs?: number } = {},
+): MulticamReactionCue[] {
+ const threshold = options.threshold ?? 0.55;
+ const mergeGapMs = options.mergeGapMs ?? 750;
+ const minimumMs = options.minimumMs ?? 300;
+ const candidates = [...signals]
+ .filter((signal) =>
+ Math.max(signal.smile, signal.surprise, signal.headMotion) >= threshold,
+ )
+ .sort((left, right) =>
+ left.participantId.localeCompare(right.participantId) || left.timeMs - right.timeMs,
+ )
+ .map((signal) => {
+ const ranked = [
+ { kind: "smile" as const, value: signal.smile },
+ { kind: "surprise" as const, value: signal.surprise },
+ { kind: "movement" as const, value: signal.headMotion },
+ ].sort((left, right) => right.value - left.value)[0]!;
+ return {
+ participantId: signal.participantId,
+ startMs: signal.timeMs,
+ endMs: signal.timeMs + minimumMs,
+ confidence: ranked.value,
+ kind: ranked.kind,
+ };
+ });
+ const output: MulticamReactionCue[] = [];
+ for (const cue of candidates) {
+ const previous = output[output.length - 1];
+ if (
+ previous &&
+ previous.participantId === cue.participantId &&
+ previous.kind === cue.kind &&
+ cue.startMs - previous.endMs <= mergeGapMs
+ ) {
+ previous.endMs = cue.endMs;
+ previous.confidence = Math.max(previous.confidence, cue.confidence);
+ } else {
+ output.push({ ...cue });
+ }
+ }
+ return output;
+}
+
+function reactionShot(
+ source: MulticamShot,
+ cue: MulticamReactionCue,
+ manifest: MulticamManifest,
+ startMs: number,
+ endMs: number,
+): MulticamShot | undefined {
+ const camera = manifest.cameras.find(
+ (entry) => entry.subject === cue.participantId && entry.type === "closeup",
+ );
+ if (!camera) return undefined;
+ return {
+ ...structuredClone(source),
+ startMs,
+ endMs,
+ layout: {
+ template: "solo",
+ panels: [{
+ cameraId: camera.id,
+ subject: cue.participantId,
+ rect: { x: 0, y: 0, width: 1, height: 1 },
+ }],
+ },
+ transitionIn: { type: "cut", durationMs: 0 },
+ reason: "reaction-shot",
+ confidence: cue.confidence,
+ };
+}
+
+/** Inserts high-confidence listener reactions without changing the activity artifact. */
+export function incorporateMulticamReactionCues(
+ plan: MulticamShotPlan,
+ manifest: MulticamManifest,
+ cues: readonly MulticamReactionCue[],
+): MulticamShotPlan {
+ let shots = plan.shots.map((shot) => structuredClone(shot));
+ for (const cue of [...cues].sort((left, right) => left.startMs - right.startMs)) {
+ if (cue.confidence < 0.65) continue;
+ const index = shots.findIndex(
+ (shot) =>
+ shot.startMs <= cue.startMs &&
+ shot.endMs >= cue.endMs &&
+ shot.layout.panels.every((panel) => panel.subject !== cue.participantId),
+ );
+ if (index < 0) continue;
+ const source = shots[index]!;
+ const duration = Math.min(1_800, Math.max(600, cue.endMs - cue.startMs));
+ const startMs = Math.max(source.startMs, cue.startMs);
+ const endMs = Math.min(source.endMs, startMs + duration);
+ const inserted = reactionShot(source, cue, manifest, startMs, endMs);
+ if (!inserted || endMs <= startMs) continue;
+ const replacement: MulticamShot[] = [];
+ if (source.startMs < startMs) replacement.push({ ...source, endMs: startMs });
+ replacement.push(inserted);
+ if (endMs < source.endMs) replacement.push({ ...source, startMs: endMs });
+ shots.splice(index, 1, ...replacement);
+ }
+ return { ...plan, shots };
+}
diff --git a/packages/core/src/multicam/shot-planner.test.ts b/packages/core/src/multicam/shot-planner.test.ts
new file mode 100644
index 00000000..1d9e02eb
--- /dev/null
+++ b/packages/core/src/multicam/shot-planner.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from "vitest";
+import type { MulticamActivityMap } from "./automatic-edit";
+import { DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS } from "./manifest";
+import {
+ applyMulticamDirectives,
+ planMulticamShots,
+} from "./shot-planner";
+
+const manifest = {
+ spec: "openreel-multicam/v1" as const,
+ fps: 25,
+ sync: { method: "audio-crosscorr" as const, reference: "wide" },
+ participants: [
+ { id: "p1", name: "Alex", audio: "mic1", seat: "left" as const },
+ { id: "p2", name: "Jamie", audio: "mic2", seat: "right" as const },
+ ],
+ cameras: [
+ { id: "cam1", type: "closeup" as const, subject: "p1", file: "a.mp4" },
+ { id: "cam2", type: "closeup" as const, subject: "p2", file: "b.mp4" },
+ { id: "wide", type: "wide" as const, subject: "all", file: "wide.mp4" },
+ ],
+ constraints: {
+ ...DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+ reaction_shot_after_ms: 99_000,
+ },
+};
+
+function activity(entries: Array<{ ids: string[]; scores?: [number, number]; speech?: [number, number] }>): MulticamActivityMap {
+ return {
+ angleIds: ["mic1", "mic2"],
+ duration: entries.length,
+ windowMs: 1_000,
+ points: entries.map((entry, index) => ({
+ startTime: index,
+ endTime: index + 1,
+ activeAngleIds: entry.ids,
+ scores: { mic1: entry.scores?.[0] ?? 1, mic2: entry.scores?.[1] ?? 1 },
+ speechProbabilities: {
+ mic1: entry.speech?.[0] ?? (entry.ids.includes("mic1") ? 1 : 0),
+ mic2: entry.speech?.[1] ?? (entry.ids.includes("mic2") ? 1 : 0),
+ },
+ })),
+ };
+}
+
+describe("multicam shot planner", () => {
+ it("uses seat-ordered split layouts for sustained overlap", () => {
+ const plan = planMulticamShots(
+ activity([
+ { ids: ["mic1"] },
+ { ids: ["mic1", "mic2"] },
+ { ids: ["mic1", "mic2"] },
+ { ids: ["mic1", "mic2"] },
+ ]),
+ manifest,
+ { strategy: "winner", escalateTo: "composite", minLayoutLifeMs: 0 },
+ );
+
+ expect(plan.shots[1]).toMatchObject({
+ reason: "sustained-overlap",
+ layout: {
+ template: "split2",
+ panels: [{ subject: "p1" }, { subject: "p2" }],
+ },
+ });
+ });
+
+ it("applies cut lead and breaks overlong shots with a reaction", () => {
+ const constrained = {
+ ...manifest,
+ constraints: {
+ ...manifest.constraints,
+ min_shot_ms: 1_000,
+ max_shot_ms: 3_000,
+ reaction_shot_after_ms: 10_000,
+ cut_lead_ms: 100,
+ },
+ };
+ const plan = planMulticamShots(
+ activity([
+ { ids: ["mic1"] },
+ { ids: ["mic1"] },
+ { ids: ["mic1"] },
+ { ids: ["mic1"] },
+ { ids: ["mic1"] },
+ ]),
+ constrained,
+ );
+
+ expect(plan.shots[0]?.endMs).toBe(3_000);
+ expect(plan.shots[1]).toMatchObject({
+ startMs: 3_000,
+ endMs: 4_200,
+ reason: "max-shot",
+ layout: { panels: [{ cameraId: "cam2" }] },
+ });
+ });
+
+ it("recognizes a yielding interruption and picks its energy winner", () => {
+ const plan = planMulticamShots(
+ activity([
+ { ids: ["mic1"], scores: [1, 0] },
+ { ids: ["mic1", "mic2"], scores: [0.4, 1] },
+ { ids: ["mic2"], scores: [0, 1] },
+ ]),
+ manifest,
+ { strategy: "winner", minLayoutLifeMs: 0, layoutEnterMs: 0 },
+ );
+
+ expect(plan.shots.some((shot) => shot.reason === "successful-interruption")).toBe(true);
+ expect(plan.shots.at(-1)?.layout.panels[0]?.cameraId).toBe("cam2");
+ });
+
+ it("leads persistent speaker cuts without violating the minimum shot", () => {
+ const plan = planMulticamShots(
+ activity([
+ { ids: ["mic1"] },
+ { ids: ["mic1"] },
+ { ids: ["mic2"] },
+ { ids: ["mic2"] },
+ ]),
+ manifest,
+ );
+
+ expect(plan.shots[0]?.endMs).toBe(1_880);
+ expect(plan.shots[1]?.startMs).toBe(1_880);
+ });
+
+ it("routes non-speech group reactions to the wide camera", () => {
+ const plan = planMulticamShots(
+ activity([{ ids: [], scores: [0.8, 0.7], speech: [0.1, 0.1] }]),
+ manifest,
+ );
+
+ expect(plan.shots[0]).toMatchObject({
+ reason: "group-reaction",
+ layout: { template: "wide", panels: [{ cameraId: "wide" }] },
+ });
+ });
+
+ it("applies bounded camera directives without mutating analysis", () => {
+ const plan = planMulticamShots(activity([{ ids: ["mic1"] }, { ids: ["mic1"] }]), manifest);
+ const changed = applyMulticamDirectives(plan, manifest, [
+ { id: "d1", startMs: 500, endMs: 1_500, cameraId: "cam2" },
+ ]);
+
+ expect(changed.shots.some((shot) => shot.reason === "directive")).toBe(true);
+ expect(changed.shots.find((shot) => shot.reason === "directive")?.layout.panels[0]?.cameraId).toBe("cam2");
+ expect(plan.shots.every((shot) => shot.reason !== "directive")).toBe(true);
+ });
+});
diff --git a/packages/core/src/multicam/shot-planner.ts b/packages/core/src/multicam/shot-planner.ts
new file mode 100644
index 00000000..3a700fc2
--- /dev/null
+++ b/packages/core/src/multicam/shot-planner.ts
@@ -0,0 +1,614 @@
+import type {
+ MulticamActivityMap,
+ MulticamActivityPoint,
+} from "./automatic-edit";
+import type {
+ MulticamManifest,
+ MulticamManifestCamera,
+ MulticamManifestParticipant,
+} from "./manifest";
+
+export type MulticamDecisionStrategy =
+ | "hold"
+ | "winner"
+ | "priority"
+ | "wide"
+ | "composite"
+ | "progressive";
+
+export type MulticamLayoutTemplate =
+ | "solo"
+ | "split2"
+ | "split3"
+ | "pip"
+ | "wide";
+
+export interface MulticamPanelRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface MulticamPanel {
+ cameraId: string;
+ subject: string;
+ rect: MulticamPanelRect;
+ crop?: MulticamPanelRect;
+}
+
+export interface MulticamShotLayout {
+ template: MulticamLayoutTemplate;
+ panels: MulticamPanel[];
+}
+
+export interface MulticamShotTransition {
+ type: "cut" | "dissolve" | "layout-morph";
+ durationMs: number;
+}
+
+export type MulticamShotReason =
+ | "speaker"
+ | "backchannel-hold"
+ | "turn-collision-winner"
+ | "successful-interruption"
+ | "sustained-overlap"
+ | "group-reaction"
+ | "silence-hold"
+ | "reaction-shot"
+ | "max-shot"
+ | "layout-budget"
+ | "directive";
+
+export interface MulticamShot {
+ startMs: number;
+ endMs: number;
+ layout: MulticamShotLayout;
+ transitionIn: MulticamShotTransition;
+ reason: MulticamShotReason;
+ confidence: number;
+}
+
+export interface MulticamShotPlan {
+ spec: "openreel-multicam-edit/v1";
+ durationMs: number;
+ shots: MulticamShot[];
+}
+
+export interface MulticamShotPolicy {
+ strategy: MulticamDecisionStrategy;
+ escalateTo: Exclude<MulticamDecisionStrategy, "hold">;
+ priorityParticipantIds: string[];
+ commitMs: number;
+ layoutEnterMs: number;
+ layoutExitMs: number;
+ minLayoutLifeMs: number;
+ maxLayoutChangesPerMinute: number;
+}
+
+export const DEFAULT_MULTICAM_SHOT_POLICY: MulticamShotPolicy = {
+ strategy: "hold",
+ escalateTo: "wide",
+ priorityParticipantIds: [],
+ commitMs: 300,
+ layoutEnterMs: 350,
+ layoutExitMs: 1_400,
+ minLayoutLifeMs: 1_200,
+ maxLayoutChangesPerMinute: 6,
+};
+
+interface ClassifiedSpan {
+ startMs: number;
+ endMs: number;
+ participantIds: string[];
+ scores: Record<string, number>;
+ speech: Record<string, number>;
+ kind:
+ | "speaker"
+ | "backchannel"
+ | "turn-collision"
+ | "interruption"
+ | "sustained-overlap"
+ | "group-reaction"
+ | "silence";
+}
+
+const clamp = (value: number, min: number, max: number): number =>
+ Math.min(max, Math.max(min, value));
+
+function seatOrder(participant: MulticamManifestParticipant): number {
+ if (typeof participant.seat === "number") return participant.seat;
+ return { left: 0, center: 1, right: 2 }[participant.seat];
+}
+
+function participantForActivityId(
+ manifest: MulticamManifest,
+ activityId: string,
+): string | undefined {
+ const participant = manifest.participants.find(
+ (entry) => entry.id === activityId || entry.audio === activityId,
+ );
+ if (participant) return participant.id;
+ const camera = manifest.cameras.find(
+ (entry) => entry.id === activityId || entry.angleId === activityId,
+ );
+ return camera && camera.subject !== "all" && !camera.subject.includes("+")
+ ? camera.subject
+ : undefined;
+}
+
+function averageRecord(
+ points: readonly MulticamActivityPoint[],
+ key: "scores" | "speechProbabilities",
+ manifest: MulticamManifest,
+): Record<string, number> {
+ const totals: Record<string, number> = {};
+ const counts: Record<string, number> = {};
+ for (const point of points) {
+ const record = point[key] ?? {};
+ for (const [activityId, value] of Object.entries(record)) {
+ const participantId = participantForActivityId(manifest, activityId);
+ if (!participantId) continue;
+ totals[participantId] = (totals[participantId] ?? 0) + value;
+ counts[participantId] = (counts[participantId] ?? 0) + 1;
+ }
+ }
+ return Object.fromEntries(
+ Object.entries(totals).map(([id, value]) => [id, value / (counts[id] ?? 1)]),
+ );
+}
+
+function classifyActivity(
+ activity: MulticamActivityMap,
+ manifest: MulticamManifest,
+): ClassifiedSpan[] {
+ const raw: Array<Omit<ClassifiedSpan, "kind"> & { points: MulticamActivityPoint[] }> = [];
+ for (const point of activity.points) {
+ const participantIds = [...new Set(
+ point.activeAngleIds
+ .map((id) => participantForActivityId(manifest, id))
+ .filter((id): id is string => Boolean(id)),
+ )].sort();
+ const previous = raw[raw.length - 1];
+ if (
+ previous &&
+ previous.participantIds.join("|") === participantIds.join("|") &&
+ Math.abs(previous.endMs - point.startTime * 1_000) < 1
+ ) {
+ previous.endMs = point.endTime * 1_000;
+ previous.points.push(point);
+ } else {
+ raw.push({
+ startMs: point.startTime * 1_000,
+ endMs: point.endTime * 1_000,
+ participantIds,
+ scores: {},
+ speech: {},
+ points: [point],
+ });
+ }
+ }
+
+ return raw.map((entry, index) => {
+ const scores = averageRecord(entry.points, "scores", manifest);
+ const speech = averageRecord(entry.points, "speechProbabilities", manifest);
+ const duration = entry.endMs - entry.startMs;
+ const previous = raw[index - 1];
+ const next = raw[index + 1];
+ let kind: ClassifiedSpan["kind"] = "speaker";
+ if (entry.participantIds.length === 0) {
+ const nonSpeechEnergy = Object.values(scores).some((value) => value >= 0.5);
+ const lowSpeech = Object.values(speech).every((value) => value < 0.5);
+ kind = nonSpeechEnergy && lowSpeech ? "group-reaction" : "silence";
+ } else if (entry.participantIds.length > 1) {
+ const orderedScores = entry.participantIds
+ .map((id) => scores[id] ?? 0)
+ .sort((left, right) => right - left);
+ if (duration < 700 && (orderedScores[1] ?? 0) < (orderedScores[0] ?? 0) * 0.65) {
+ kind = "backchannel";
+ } else if (duration >= 2_000) {
+ kind = "sustained-overlap";
+ } else {
+ const previousSolo = previous?.participantIds.length === 1
+ ? previous.participantIds[0]
+ : undefined;
+ const nextSolo = next?.participantIds.length === 1
+ ? next.participantIds[0]
+ : undefined;
+ kind = previousSolo && nextSolo && previousSolo !== nextSolo
+ ? "interruption"
+ : "turn-collision";
+ }
+ }
+ return {
+ startMs: entry.startMs,
+ endMs: entry.endMs,
+ participantIds: entry.participantIds,
+ scores,
+ speech,
+ kind,
+ };
+ });
+}
+
+function cameraForSubject(
+ manifest: MulticamManifest,
+ subject: string,
+): MulticamManifestCamera | undefined {
+ return (
+ manifest.cameras.find(
+ (camera) => camera.subject === subject && camera.type === "closeup",
+ ) ?? manifest.cameras.find((camera) => camera.subject === subject)
+ );
+}
+
+function wideCamera(manifest: MulticamManifest): MulticamManifestCamera {
+ return (
+ manifest.cameras.find((camera) => camera.type === "wide") ??
+ manifest.cameras[0]!
+ );
+}
+
+function panelRects(count: number): MulticamPanelRect[] {
+ if (count <= 1) return [{ x: 0, y: 0, width: 1, height: 1 }];
+ return Array.from({ length: count }, (_, index) => ({
+ x: index / count,
+ y: 0,
+ width: 1 / count,
+ height: 1,
+ }));
+}
+
+function layoutForParticipants(
+ manifest: MulticamManifest,
+ participantIds: readonly string[],
+ strategy: MulticamDecisionStrategy,
+): MulticamShotLayout {
+ if (strategy === "wide" || participantIds.length === 0) {
+ const camera = wideCamera(manifest);
+ return {
+ template: "wide",
+ panels: [{ cameraId: camera.id, subject: camera.subject, rect: panelRects(1)[0]! }],
+ };
+ }
+ const ordered = participantIds
+ .map((id) => manifest.participants.find((participant) => participant.id === id))
+ .filter((participant): participant is MulticamManifestParticipant => Boolean(participant))
+ .sort((left, right) => seatOrder(left) - seatOrder(right));
+ if (strategy === "progressive" && ordered.length > 1) {
+ const base = cameraForSubject(manifest, ordered[0]!.id) ?? wideCamera(manifest);
+ const pip = cameraForSubject(manifest, ordered[1]!.id) ?? wideCamera(manifest);
+ return {
+ template: "pip",
+ panels: [
+ { cameraId: base.id, subject: base.subject, rect: panelRects(1)[0]! },
+ { cameraId: pip.id, subject: pip.subject, rect: { x: 0.68, y: 0.62, width: 0.28, height: 0.32 } },
+ ],
+ };
+ }
+ const selected = strategy === "composite" ? ordered.slice(0, 3) : ordered.slice(0, 1);
+ const rects = panelRects(selected.length);
+ return {
+ template:
+ selected.length === 1 ? "solo" : selected.length === 2 ? "split2" : "split3",
+ panels: selected.map((participant, index) => {
+ const camera = cameraForSubject(manifest, participant.id) ?? wideCamera(manifest);
+ return {
+ cameraId: camera.id,
+ subject: participant.id,
+ rect: rects[index]!,
+ };
+ }),
+ };
+}
+
+function layoutKey(layout: MulticamShotLayout): string {
+ return `${layout.template}:${layout.panels.map((panel) => panel.cameraId).join("+")}`;
+}
+
+function winner(
+ span: ClassifiedSpan,
+ policy: MulticamShotPolicy,
+): string | undefined {
+ if (policy.strategy === "priority") {
+ const priority = policy.priorityParticipantIds.find((id) =>
+ span.participantIds.includes(id),
+ );
+ if (priority) return priority;
+ }
+ return [...span.participantIds].sort(
+ (left, right) =>
+ (span.scores[right] ?? 0) - (span.scores[left] ?? 0) ||
+ left.localeCompare(right),
+ )[0];
+}
+
+function desiredShot(
+ span: ClassifiedSpan,
+ manifest: MulticamManifest,
+ policy: MulticamShotPolicy,
+ current?: MulticamShot,
+): MulticamShot {
+ let strategy = policy.strategy;
+ let participantIds = span.participantIds;
+ let reason: MulticamShotReason = "speaker";
+ if (span.kind === "silence") {
+ reason = "silence-hold";
+ if (current) return { ...current, startMs: span.startMs, endMs: span.endMs, reason };
+ strategy = "wide";
+ } else if (span.kind === "group-reaction") {
+ reason = "group-reaction";
+ strategy = "wide";
+ } else if (span.kind === "backchannel") {
+ reason = "backchannel-hold";
+ if (current) return { ...current, startMs: span.startMs, endMs: span.endMs, reason };
+ participantIds = [winner(span, policy)!].filter(Boolean);
+ } else if (span.kind === "sustained-overlap") {
+ reason = "sustained-overlap";
+ strategy = policy.escalateTo;
+ } else if (span.kind === "interruption") {
+ reason = "successful-interruption";
+ participantIds = [winner(span, policy)!].filter(Boolean);
+ strategy = strategy === "composite" || strategy === "progressive" ? strategy : "winner";
+ } else if (span.kind === "turn-collision") {
+ reason = "turn-collision-winner";
+ if (strategy === "hold" && current) {
+ return { ...current, startMs: span.startMs, endMs: span.endMs, reason };
+ }
+ if (strategy === "winner" || strategy === "priority" || strategy === "hold") {
+ participantIds = [winner(span, policy)!].filter(Boolean);
+ }
+ } else {
+ participantIds = [winner(span, policy)!].filter(Boolean);
+ strategy = "winner";
+ }
+ const confidence = participantIds.length
+ ? participantIds.reduce((sum, id) => sum + (span.scores[id] ?? 0), 0) /
+ participantIds.length
+ : 0.5;
+ return {
+ startMs: span.startMs,
+ endMs: span.endMs,
+ layout: layoutForParticipants(manifest, participantIds, strategy),
+ transitionIn: { type: "cut", durationMs: 0 },
+ reason,
+ confidence: clamp(confidence, 0, 1),
+ };
+}
+
+function mergeShots(shots: readonly MulticamShot[]): MulticamShot[] {
+ const output: MulticamShot[] = [];
+ for (const shot of shots) {
+ const previous = output[output.length - 1];
+ if (previous && layoutKey(previous.layout) === layoutKey(shot.layout)) {
+ previous.endMs = shot.endMs;
+ previous.confidence = Math.max(previous.confidence, shot.confidence);
+ if (previous.reason === "silence-hold") previous.reason = shot.reason;
+ } else {
+ output.push(structuredClone(shot));
+ }
+ }
+ return output;
+}
+
+function applyHysteresis(
+ desired: readonly MulticamShot[],
+ manifest: MulticamManifest,
+ policy: MulticamShotPolicy,
+): MulticamShot[] {
+ const output: MulticamShot[] = [];
+ for (const shot of desired) {
+ const previous = output[output.length - 1];
+ const duration = shot.endMs - shot.startMs;
+ const leavingLayout = previous && previous.layout.template !== "solo";
+ const required = leavingLayout ? policy.layoutExitMs : policy.layoutEnterMs;
+ if (
+ previous &&
+ layoutKey(previous.layout) !== layoutKey(shot.layout) &&
+ duration < Math.max(policy.commitMs, required)
+ ) {
+ previous.endMs = shot.endMs;
+ continue;
+ }
+ const recentChanges = output.filter(
+ (entry) => entry.startMs >= shot.startMs - 60_000,
+ ).length - 1;
+ let next = structuredClone(shot);
+ if (
+ previous &&
+ layoutKey(previous.layout) !== layoutKey(next.layout) &&
+ recentChanges >= policy.maxLayoutChangesPerMinute
+ ) {
+ next = {
+ ...next,
+ layout: layoutForParticipants(manifest, [], "wide"),
+ reason: "layout-budget",
+ };
+ }
+ if (previous && next.startMs - previous.startMs < policy.minLayoutLifeMs) {
+ const boundary = previous.startMs + policy.minLayoutLifeMs;
+ if (boundary >= next.endMs) {
+ previous.endMs = next.endMs;
+ continue;
+ }
+ previous.endMs = boundary;
+ next.startMs = boundary;
+ }
+ if (previous && previous.layout.template !== next.layout.template) {
+ next.transitionIn = { type: "layout-morph", durationMs: 200 };
+ }
+ output.push(next);
+ }
+ return mergeShots(output);
+}
+
+function addReactionShots(
+ shots: readonly MulticamShot[],
+ manifest: MulticamManifest,
+): MulticamShot[] {
+ const output: MulticamShot[] = [];
+ const constraints = manifest.constraints;
+ const reactionLength = Math.max(constraints.min_shot_ms, 1_200);
+ for (const shot of shots) {
+ const triggerAfter = Math.min(
+ constraints.reaction_shot_after_ms,
+ constraints.max_shot_ms,
+ );
+ let cursor = shot.startMs;
+ while (shot.endMs - cursor > triggerAfter + reactionLength) {
+ const reactionStart = cursor + triggerAfter;
+ const reactionEnd = Math.min(shot.endMs, reactionStart + reactionLength);
+ output.push({ ...structuredClone(shot), startMs: cursor, endMs: reactionStart });
+ const subject = shot.layout.panels[0]?.subject;
+ const alternate = manifest.participants.find(
+ (participant) => participant.id !== subject,
+ );
+ const layout = shot.layout.template === "solo" && alternate
+ ? layoutForParticipants(manifest, [alternate.id], "winner")
+ : shot.layout.template === "wide" && manifest.participants[0]
+ ? layoutForParticipants(manifest, [manifest.participants[0].id], "winner")
+ : layoutForParticipants(manifest, [], "wide");
+ output.push({
+ ...structuredClone(shot),
+ startMs: reactionStart,
+ endMs: reactionEnd,
+ layout,
+ transitionIn: { type: "cut", durationMs: 0 },
+ reason: constraints.max_shot_ms <= constraints.reaction_shot_after_ms
+ ? "max-shot"
+ : "reaction-shot",
+ confidence: 0.5,
+ });
+ cursor = reactionEnd;
+ }
+ if (cursor < shot.endMs) output.push({ ...structuredClone(shot), startMs: cursor });
+ }
+ return output;
+}
+
+function applyCutLead(
+ shots: readonly MulticamShot[],
+ cutLeadMs: number,
+ minimumShotMs: number,
+): MulticamShot[] {
+ const output = shots.map((shot) => structuredClone(shot));
+ for (let index = 1; index < output.length; index++) {
+ const previous = output[index - 1]!;
+ const current = output[index]!;
+ const boundary = Math.max(
+ previous.startMs + minimumShotMs,
+ current.startMs - Math.max(0, cutLeadMs),
+ );
+ if (boundary < current.endMs) {
+ previous.endMs = boundary;
+ current.startMs = boundary;
+ }
+ }
+ return output;
+}
+
+/** Two-pass offline planner: first classifies overlap spans, then plans stable layouts. */
+export function planMulticamShots(
+ activity: MulticamActivityMap,
+ manifest: MulticamManifest,
+ overrides: Partial<MulticamShotPolicy> = {},
+): MulticamShotPlan {
+ const policy = {
+ ...DEFAULT_MULTICAM_SHOT_POLICY,
+ ...overrides,
+ minLayoutLifeMs: Math.max(
+ overrides.minLayoutLifeMs ?? DEFAULT_MULTICAM_SHOT_POLICY.minLayoutLifeMs,
+ manifest.constraints.min_shot_ms,
+ ),
+ };
+ const classified = classifyActivity(activity, manifest);
+ const desired: MulticamShot[] = [];
+ for (const span of classified) {
+ desired.push(desiredShot(span, manifest, policy, desired[desired.length - 1]));
+ }
+ const stable = applyCutLead(
+ applyHysteresis(mergeShots(desired), manifest, policy),
+ manifest.constraints.cut_lead_ms,
+ manifest.constraints.min_shot_ms,
+ );
+ return {
+ spec: "openreel-multicam-edit/v1",
+ durationMs: Math.round(activity.duration * 1_000),
+ shots: addReactionShots(stable, manifest),
+ };
+}
+
+export interface MulticamEditDirective {
+ id: string;
+ startMs: number;
+ endMs: number;
+ cameraId?: string;
+ layout?: MulticamLayoutTemplate;
+ note?: string;
+}
+
+/** Applies validated human/agent directives without changing the cached activity map. */
+export function applyMulticamDirectives(
+ plan: MulticamShotPlan,
+ manifest: MulticamManifest,
+ directives: readonly MulticamEditDirective[],
+): MulticamShotPlan {
+ let shots = plan.shots.map((shot) => structuredClone(shot));
+ for (const directive of directives) {
+ if (
+ !Number.isFinite(directive.startMs) ||
+ !Number.isFinite(directive.endMs) ||
+ directive.startMs < 0 ||
+ directive.endMs <= directive.startMs ||
+ directive.endMs > plan.durationMs
+ ) {
+ throw new Error(`Directive ${directive.id} has an invalid time range`);
+ }
+ const camera = directive.cameraId
+ ? manifest.cameras.find((entry) => entry.id === directive.cameraId)
+ : undefined;
+ if (directive.cameraId && !camera) {
+ throw new Error(`Directive ${directive.id} references an unknown camera`);
+ }
+ shots = shots.flatMap((shot) => {
+ if (shot.endMs <= directive.startMs || shot.startMs >= directive.endMs) return [shot];
+ const result: MulticamShot[] = [];
+ if (shot.startMs < directive.startMs) result.push({ ...shot, endMs: directive.startMs });
+ const startMs = Math.max(shot.startMs, directive.startMs);
+ const endMs = Math.min(shot.endMs, directive.endMs);
+ const layout = camera
+ ? {
+ template: camera.type === "wide" ? "wide" as const : "solo" as const,
+ panels: [{ cameraId: camera.id, subject: camera.subject, rect: panelRects(1)[0]! }],
+ }
+ : directive.layout === "wide"
+ ? layoutForParticipants(manifest, [], "wide")
+ : shot.layout;
+ result.push({ ...shot, startMs, endMs, layout, reason: "directive" });
+ if (shot.endMs > directive.endMs) result.push({ ...shot, startMs: directive.endMs });
+ return result;
+ });
+ }
+ return { ...plan, shots: mergeShots(shots) };
+}
+
+export const MULTICAM_POLICY_PRESETS = {
+ conversation: {
+ ...DEFAULT_MULTICAM_SHOT_POLICY,
+ strategy: "hold",
+ escalateTo: "wide",
+ },
+ energetic: {
+ ...DEFAULT_MULTICAM_SHOT_POLICY,
+ strategy: "winner",
+ escalateTo: "progressive",
+ layoutEnterMs: 250,
+ maxLayoutChangesPerMinute: 10,
+ },
+ panel: {
+ ...DEFAULT_MULTICAM_SHOT_POLICY,
+ strategy: "composite",
+ escalateTo: "composite",
+ maxLayoutChangesPerMinute: 4,
+ },
+} satisfies Record<string, MulticamShotPolicy>;
diff --git a/packages/core/src/multicam/silero-vad.test.ts b/packages/core/src/multicam/silero-vad.test.ts
new file mode 100644
index 00000000..f8e766f8
--- /dev/null
+++ b/packages/core/src/multicam/silero-vad.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ analyzeSileroVad,
+ SILERO_VAD_CHUNK_SAMPLES,
+ SILERO_VAD_CONTEXT_SAMPLES,
+} from "./silero-vad";
+
+class TestTensor {
+ constructor(
+ public type: string,
+ public data: Float32Array | BigInt64Array,
+ public dimensions: readonly number[],
+ ) {}
+}
+
+describe("Silero VAD", () => {
+ it("feeds context, recurrent state, and 16 kHz chunks to ONNX", async () => {
+ let callCount = 0;
+ const run = vi.fn(async (_feeds: Record<string, TestTensor>) => {
+ callCount++;
+ return {
+ output: { data: new Float32Array([callCount / 10]) },
+ stateN: { data: new Float32Array(256).fill(callCount) },
+ };
+ });
+ const runtime = {
+ Tensor: TestTensor,
+ InferenceSession: { create: vi.fn() },
+ };
+ const progress = vi.fn();
+ const result = await analyzeSileroVad(
+ new Float32Array(SILERO_VAD_CHUNK_SAMPLES * 2).fill(0.25),
+ 16_000,
+ { runtime, session: { run }, onProgress: progress },
+ );
+
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(run.mock.calls[0]?.[0].input.dimensions).toEqual([
+ 1,
+ SILERO_VAD_CHUNK_SAMPLES + SILERO_VAD_CONTEXT_SAMPLES,
+ ]);
+ expect(run.mock.calls[1]?.[0].state.data[0]).toBe(1);
+ expect(result.windowMs).toBe(32);
+ expect(result.probabilities[0]).toBeCloseTo(0.1);
+ expect(result.probabilities[1]).toBeCloseTo(0.2);
+ expect(progress).toHaveBeenLastCalledWith(2, 2);
+ });
+
+ it("resamples input audio to the model sample rate", async () => {
+ const run = vi.fn(async () => ({
+ output: { data: new Float32Array([0.75]) },
+ stateN: { data: new Float32Array(256) },
+ }));
+ const result = await analyzeSileroVad(new Float32Array(8_000), 8_000, {
+ runtime: {
+ Tensor: TestTensor,
+ InferenceSession: { create: vi.fn() },
+ },
+ session: { run },
+ });
+
+ expect(run).toHaveBeenCalledTimes(Math.ceil(16_000 / 512));
+ expect(result.probabilities[0]).toBeCloseTo(0.75);
+ });
+});
diff --git a/packages/core/src/multicam/silero-vad.ts b/packages/core/src/multicam/silero-vad.ts
new file mode 100644
index 00000000..17b6a099
--- /dev/null
+++ b/packages/core/src/multicam/silero-vad.ts
@@ -0,0 +1,149 @@
+import type { MulticamVadTrack } from "./automatic-edit";
+
+export const SILERO_VAD_SAMPLE_RATE = 16_000;
+export const SILERO_VAD_CHUNK_SAMPLES = 512;
+export const SILERO_VAD_CONTEXT_SAMPLES = 64;
+export const DEFAULT_SILERO_VAD_MODEL_URL =
+ "https://cdn.jsdelivr.net/gh/snakers4/[email protected]/src/silero_vad/data/silero_vad.onnx";
+
+interface VadTensorLike {
+ data: ArrayLike<number | bigint>;
+}
+
+interface VadSessionLike {
+ run(feeds: Record<string, unknown>): Promise<Record<string, VadTensorLike>>;
+}
+
+interface VadRuntimeLike {
+ Tensor: new (
+ type: "float32" | "int64",
+ data: Float32Array | BigInt64Array,
+ dimensions: readonly number[],
+ ) => unknown;
+ InferenceSession: {
+ create(
+ model: string | ArrayBuffer | Uint8Array,
+ options?: Record<string, unknown>,
+ ): Promise<VadSessionLike>;
+ };
+}
+
+export interface SileroVadOptions {
+ model?: string | ArrayBuffer | Uint8Array;
+ runtime?: VadRuntimeLike;
+ session?: VadSessionLike;
+ onProgress?: (completed: number, total: number) => void;
+}
+
+let defaultSessionPromise: Promise<{
+ runtime: VadRuntimeLike;
+ session: VadSessionLike;
+}> | undefined;
+
+async function loadDefaultSession(
+ model: string | ArrayBuffer | Uint8Array,
+): Promise<{ runtime: VadRuntimeLike; session: VadSessionLike }> {
+ if (!defaultSessionPromise) {
+ defaultSessionPromise = (async () => {
+ // @ts-expect-error onnxruntime-web 1.21 ships types but omits them from its
+ // package exports map; Vite still resolves and bundles the ESM entry.
+ const runtime = (await import("onnxruntime-web")) as unknown as VadRuntimeLike;
+ const session = await runtime.InferenceSession.create(model, {
+ executionProviders: ["wasm"],
+ });
+ return { runtime, session };
+ })();
+ defaultSessionPromise.catch(() => {
+ defaultSessionPromise = undefined;
+ });
+ }
+ return defaultSessionPromise;
+}
+
+function resampleMono(
+ samples: Float32Array,
+ sourceSampleRate: number,
+ targetSampleRate: number,
+): Float32Array {
+ if (sourceSampleRate === targetSampleRate) return samples;
+ const targetLength = Math.max(
+ 0,
+ Math.round((samples.length * targetSampleRate) / sourceSampleRate),
+ );
+ const output = new Float32Array(targetLength);
+ for (let index = 0; index < targetLength; index++) {
+ const position = (index * sourceSampleRate) / targetSampleRate;
+ const left = Math.floor(position);
+ const right = Math.min(samples.length - 1, left + 1);
+ const fraction = position - left;
+ output[index] =
+ (samples[left] ?? 0) * (1 - fraction) +
+ (samples[right] ?? 0) * fraction;
+ }
+ return output;
+}
+
+/**
+ * Runs the pinned Silero VAD ONNX model in 32 ms frames. The runtime is loaded
+ * lazily so projects that do not use multicam do not download ONNX/WASM code.
+ */
+export async function analyzeSileroVad(
+ samples: Float32Array,
+ sampleRate: number,
+ options: SileroVadOptions = {},
+): Promise<MulticamVadTrack> {
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
+ throw new Error("Silero VAD requires a positive audio sample rate");
+ }
+ const loaded = options.runtime
+ ? { runtime: options.runtime, session: options.session }
+ : await loadDefaultSession(options.model ?? DEFAULT_SILERO_VAD_MODEL_URL);
+ const runtime = loaded.runtime;
+ const session = options.session ?? loaded.session;
+ if (!session) throw new Error("Silero VAD session is unavailable");
+ const audio = resampleMono(samples, sampleRate, SILERO_VAD_SAMPLE_RATE);
+ const frameCount = Math.ceil(audio.length / SILERO_VAD_CHUNK_SAMPLES);
+ const probabilities = new Float32Array(frameCount);
+ let context = new Float32Array(SILERO_VAD_CONTEXT_SAMPLES);
+ let state = new Float32Array(2 * 1 * 128);
+
+ for (let frameIndex = 0; frameIndex < frameCount; frameIndex++) {
+ const chunk = new Float32Array(SILERO_VAD_CHUNK_SAMPLES);
+ chunk.set(
+ audio.subarray(
+ frameIndex * SILERO_VAD_CHUNK_SAMPLES,
+ (frameIndex + 1) * SILERO_VAD_CHUNK_SAMPLES,
+ ),
+ );
+ const input = new Float32Array(
+ SILERO_VAD_CONTEXT_SAMPLES + SILERO_VAD_CHUNK_SAMPLES,
+ );
+ input.set(context);
+ input.set(chunk, SILERO_VAD_CONTEXT_SAMPLES);
+ const result = await session.run({
+ input: new runtime.Tensor("float32", input, [1, input.length]),
+ state: new runtime.Tensor("float32", state, [2, 1, 128]),
+ sr: new runtime.Tensor(
+ "int64",
+ BigInt64Array.from([BigInt(SILERO_VAD_SAMPLE_RATE)]),
+ [1],
+ ),
+ });
+ const output = result.output ?? Object.values(result)[0];
+ const nextState = result.stateN ?? result.state;
+ probabilities[frameIndex] = Math.max(
+ 0,
+ Math.min(1, Number(output?.data[0] ?? 0)),
+ );
+ if (nextState?.data) {
+ state = Float32Array.from(nextState.data, Number);
+ }
+ context = chunk.slice(-SILERO_VAD_CONTEXT_SAMPLES);
+ options.onProgress?.(frameIndex + 1, frameCount);
+ }
+
+ return {
+ windowMs: (SILERO_VAD_CHUNK_SAMPLES / SILERO_VAD_SAMPLE_RATE) * 1_000,
+ probabilities,
+ };
+}
diff --git a/packages/core/src/multicam/social-clips.test.ts b/packages/core/src/multicam/social-clips.test.ts
new file mode 100644
index 00000000..14e20b5b
--- /dev/null
+++ b/packages/core/src/multicam/social-clips.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { extractMulticamSocialClips } from "./social-clips";
+
+describe("multicam social clip extraction", () => {
+ it("ranks active, reactive, transcript-rich windows deterministically", () => {
+ const points = Array.from({ length: 120 }, (_, index) => ({
+ startTime: index,
+ endTime: index + 1,
+ activeAngleIds: index >= 40 && index < 80 ? [index % 2 ? "a" : "b"] : [],
+ scores: { a: index % 2, b: (index + 1) % 2 },
+ }));
+ const result = extractMulticamSocialClips({
+ spec: "openreel-activity/v1",
+ manifestFingerprint: "m",
+ mediaFingerprint: "f",
+ createdAt: 1,
+ durationMs: 120_000,
+ activity: { angleIds: ["a", "b"], duration: 120, windowMs: 1_000, points },
+ drift: {},
+ reactions: [{ participantId: "p2", startMs: 50_000, endMs: 51_000, confidence: 0.9, kind: "smile" }],
+ transcripts: { a: [{ startMs: 45_000, endMs: 55_000, text: "A concise memorable podcast moment with a strong reaction" }] },
+ }, { count: 1, durationMs: 30_000, stepMs: 10_000 });
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.startMs).toBeGreaterThanOrEqual(20_000);
+ expect(result[0]?.startMs).toBeLessThanOrEqual(50_000);
+ });
+});
diff --git a/packages/core/src/multicam/social-clips.ts b/packages/core/src/multicam/social-clips.ts
new file mode 100644
index 00000000..3b0e3d92
--- /dev/null
+++ b/packages/core/src/multicam/social-clips.ts
@@ -0,0 +1,77 @@
+import type { OrmaArtifact } from "./orma";
+import type { MulticamReactionCue } from "./reaction-analysis";
+
+export interface MulticamSocialClipCandidate {
+ startMs: number;
+ endMs: number;
+ score: number;
+ reason: string;
+ title?: string;
+}
+
+export function extractMulticamSocialClips(
+ artifact: OrmaArtifact,
+ options: {
+ reactions?: readonly MulticamReactionCue[];
+ count?: number;
+ durationMs?: number;
+ stepMs?: number;
+ } = {},
+): MulticamSocialClipCandidate[] {
+ const durationMs = Math.max(10_000, options.durationMs ?? 45_000);
+ const stepMs = Math.max(1_000, options.stepMs ?? 5_000);
+ const projectDuration = artifact.durationMs;
+ const candidates: MulticamSocialClipCandidate[] = [];
+ for (let startMs = 0; startMs < projectDuration; startMs += stepMs) {
+ const endMs = Math.min(projectDuration, startMs + durationMs);
+ if (endMs - startMs < Math.min(10_000, projectDuration)) continue;
+ const points = artifact.activity.points.filter(
+ (point) => point.endTime * 1_000 > startMs && point.startTime * 1_000 < endMs,
+ );
+ const speaking = points.filter((point) => point.activeAngleIds.length > 0).length;
+ const overlaps = points.filter((point) => point.activeAngleIds.length > 1).length;
+ let switches = 0;
+ let previous = "";
+ for (const point of points) {
+ const next = point.activeAngleIds.join("+");
+ if (previous && next && next !== previous) switches++;
+ if (next) previous = next;
+ }
+ const reactions = (options.reactions ?? artifact.reactions ?? []).filter(
+ (cue) => cue.endMs > startMs && cue.startMs < endMs,
+ );
+ const transcriptSegments = Object.values(artifact.transcripts ?? {}).flat().filter(
+ (segment) => segment.endMs > startMs && segment.startMs < endMs,
+ );
+ const words = transcriptSegments.reduce(
+ (count, segment) => count + segment.text.trim().split(/\s+/).filter(Boolean).length,
+ 0,
+ );
+ const activityRatio = points.length ? speaking / points.length : 0;
+ const score =
+ activityRatio * 0.45 +
+ Math.min(1, switches / 8) * 0.2 +
+ Math.min(1, overlaps / Math.max(1, points.length) * 5) * 0.1 +
+ Math.min(1, reactions.length / 3) * 0.2 +
+ Math.min(1, words / 120) * 0.05;
+ const title = transcriptSegments[0]?.text.trim().slice(0, 80);
+ candidates.push({
+ startMs,
+ endMs,
+ score: Math.round(score * 1_000) / 1_000,
+ reason: `${switches} turns · ${reactions.length} reactions · ${words} words`,
+ title: title || undefined,
+ });
+ }
+ const selected: MulticamSocialClipCandidate[] = [];
+ for (const candidate of candidates.sort(
+ (left, right) => right.score - left.score || left.startMs - right.startMs,
+ )) {
+ if (selected.some((entry) =>
+ candidate.startMs < entry.endMs && candidate.endMs > entry.startMs,
+ )) continue;
+ selected.push(candidate);
+ if (selected.length >= (options.count ?? 3)) break;
+ }
+ return selected.sort((left, right) => left.startMs - right.startMs);
+}
diff --git a/packages/core/src/playback/playback-controller.ts b/packages/core/src/playback/playback-controller.ts
index b32c2bf1..871e0bb7 100644
--- a/packages/core/src/playback/playback-controller.ts
+++ b/packages/core/src/playback/playback-controller.ts
@@ -26,6 +26,10 @@ import {
getPanFromAudioEffects,
getPreviewAudioEffects,
} from "../audio/audio-effect-routing";
+import {
+ getMediaItemCapabilities,
+ trackHasAudioItems,
+} from "../timeline/timeline-items";
export class PlaybackController {
private videoEngine: VideoEngine | null = null;
@@ -570,11 +574,12 @@ export class PlaybackController {
private setupTracksInAudioGraph(): void {
if (!this.project) return;
- const hasSoloTracks = this.project.timeline.tracks.some((t) => t.solo);
-
- for (const track of this.project.timeline.tracks) {
- if (track.type !== "audio" && track.type !== "video") continue;
+ const audioTracks = this.project.timeline.tracks.filter((track) =>
+ trackHasAudioItems(this.project!, track.id),
+ );
+ const hasSoloTracks = audioTracks.some((track) => track.solo);
+ for (const track of audioTracks) {
this.realtimeAudioGraph.createTrack({
trackId: track.id,
volume: 1.0,
@@ -597,14 +602,14 @@ export class PlaybackController {
const { timeline, mediaLibrary } = this.project;
for (const track of timeline.tracks) {
- if (track.type !== "audio" && track.type !== "video") continue;
-
for (const clip of track.clips) {
const clipEnd = clip.startTime + clip.duration;
if (clipEnd <= time || clip.startTime > time + 1) continue;
const mediaItem = mediaLibrary.items.find((m) => m.id === clip.mediaId);
- if (!mediaItem?.blob) continue;
+ if (!mediaItem?.blob || !getMediaItemCapabilities(mediaItem).audio) {
+ continue;
+ }
const cachedBuffer = this.getOrDecodeAudioBuffer(mediaItem);
if (!cachedBuffer) continue;
@@ -639,11 +644,13 @@ export class PlaybackController {
const mediaIdsToPreload = new Set<string>();
for (const track of timeline.tracks) {
- if (track.type !== "audio" && track.type !== "video") continue;
-
for (const clip of track.clips) {
const mediaItem = mediaLibrary.items.find((m) => m.id === clip.mediaId);
- if (mediaItem?.blob && !this.audioBufferCache.has(mediaItem.id)) {
+ if (
+ mediaItem?.blob &&
+ getMediaItemCapabilities(mediaItem).audio &&
+ !this.audioBufferCache.has(mediaItem.id)
+ ) {
mediaIdsToPreload.add(mediaItem.id);
}
}
@@ -723,9 +730,13 @@ export class PlaybackController {
private pruneAudioBuffers(project: Project): void {
const referenced = new Set<string>();
for (const track of project.timeline.tracks) {
- if (track.type !== "audio" && track.type !== "video") continue;
for (const clip of track.clips) {
- referenced.add(clip.mediaId);
+ const mediaItem = project.mediaLibrary.items.find(
+ (candidate) => candidate.id === clip.mediaId,
+ );
+ if (getMediaItemCapabilities(mediaItem).audio) {
+ referenced.add(clip.mediaId);
+ }
}
}
diff --git a/packages/core/src/storage/project-serializer.test.ts b/packages/core/src/storage/project-serializer.test.ts
index d8bf2fe5..a36b845a 100644
--- a/packages/core/src/storage/project-serializer.test.ts
+++ b/packages/core/src/storage/project-serializer.test.ts
@@ -17,11 +17,13 @@ import type {
} from "./types";
import {
ProjectSerializer,
+ SCHEMA_VERSION,
normalizeMotionComposition,
normalizeProjectCreationFields,
normalizeProjectMotionFields,
} from "./project-serializer";
import { createCreationScene, createEmptyCreationState } from "../creation";
+import { UNIVERSAL_TRACKS_CAPABILITY } from "../timeline/timeline-items";
const makeVideoLayer = (
overrides: Partial<MotionVideoLayer> = {},
@@ -268,6 +270,44 @@ describe("normalizeProjectCreationFields", () => {
});
describe("ProjectSerializer round-trip", () => {
+ it("writes the universal-track reader requirement and preserves it", () => {
+ const serializer = new ProjectSerializer(new MemoryStorageEngine());
+ const project = makeProject({
+ capabilities: [UNIVERSAL_TRACKS_CAPABILITY],
+ minimumReaderVersion: "1.2.0",
+ });
+
+ const json = serializer.exportToJson(project);
+ const file = JSON.parse(json) as {
+ version: string;
+ minimumReaderVersion?: string;
+ capabilities?: string[];
+ };
+
+ expect(file.version).toBe(SCHEMA_VERSION);
+ expect(file.minimumReaderVersion).toBe("1.2.0");
+ expect(file.capabilities).toContain(UNIVERSAL_TRACKS_CAPABILITY);
+ expect(serializer.importFromJson(json).capabilities).toContain(
+ UNIVERSAL_TRACKS_CAPABILITY,
+ );
+ });
+
+ it("rejects a project that needs a newer reader", () => {
+ const serializer = new ProjectSerializer(new MemoryStorageEngine());
+ const json = JSON.stringify({
+ version: "9.0.0",
+ minimumReaderVersion: "9.0.0",
+ project: makeProject(),
+ });
+
+ expect(() => serializer.importFromJson(json)).toThrow(
+ /requires OpenReel project reader 9\.0\.0 or newer/,
+ );
+ expect(serializer.validateProjectJson(json)).toMatchObject({
+ valid: false,
+ });
+ });
+
it("preserves audioClips and video layers through export/import", () => {
const serializer = new ProjectSerializer(new MemoryStorageEngine());
const composition = makeComposition({
diff --git a/packages/core/src/storage/project-serializer.ts b/packages/core/src/storage/project-serializer.ts
index 920f7d9a..dacd555d 100644
--- a/packages/core/src/storage/project-serializer.ts
+++ b/packages/core/src/storage/project-serializer.ts
@@ -16,6 +16,10 @@ import { normalizeMotionCamera } from "../motion/motion-camera";
import { normalizeMotionLights } from "../motion/motion-lights";
import { normalizeMotionTracks } from "../motion/motion-tracking";
import { normalizeCreationState } from "../creation";
+import {
+ UNIVERSAL_TRACKS_MIN_READER_VERSION,
+ projectUsesUniversalTracks,
+} from "../timeline/timeline-items";
const MOTION_SHADER_CATEGORIES: ReadonlySet<MotionShaderCategory> = new Set([
"fill",
@@ -75,10 +79,52 @@ export function normalizeGeneratedShaders(
export interface ProjectFile {
readonly version: string;
+ readonly minimumReaderVersion?: string;
+ readonly capabilities?: readonly string[];
readonly project: Project;
}
-export const SCHEMA_VERSION = "1.0.0";
+export const SCHEMA_VERSION = "1.2.0";
+
+function compareVersions(left: string, right: string): number {
+ const parse = (value: string): number[] =>
+ value
+ .split(".")
+ .slice(0, 3)
+ .map((part) => Number.parseInt(part, 10) || 0);
+ const leftParts = parse(left);
+ const rightParts = parse(right);
+ for (let index = 0; index < 3; index += 1) {
+ const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
+ if (difference !== 0) return difference;
+ }
+ return 0;
+}
+
+function getProjectFileCompatibility(project: Project): Pick<
+ ProjectFile,
+ "minimumReaderVersion" | "capabilities"
+> {
+ const capabilities = project.capabilities ?? [];
+ return {
+ minimumReaderVersion: projectUsesUniversalTracks(project)
+ ? UNIVERSAL_TRACKS_MIN_READER_VERSION
+ : project.minimumReaderVersion,
+ capabilities: capabilities.length > 0 ? capabilities : undefined,
+ };
+}
+
+function assertReaderCompatibility(projectFile: ProjectFile): void {
+ const minimumReaderVersion = projectFile.minimumReaderVersion;
+ if (
+ minimumReaderVersion &&
+ compareVersions(minimumReaderVersion, SCHEMA_VERSION) > 0
+ ) {
+ throw new Error(
+ `This project requires OpenReel project reader ${minimumReaderVersion} or newer. Current reader: ${SCHEMA_VERSION}.`,
+ );
+ }
+}
function normalizeMotionAudioClips(
composition: Pick<MotionComposition, "audioClips">,
@@ -192,6 +238,7 @@ export class ProjectSerializer {
exportToJson(project: Project): string {
const projectFile: ProjectFile = {
version: SCHEMA_VERSION,
+ ...getProjectFileCompatibility(project),
project: this.stripMediaBlobs(project),
};
return JSON.stringify(projectFile, null, 2);
@@ -199,6 +246,7 @@ export class ProjectSerializer {
importFromJson(json: string): Project {
const projectFile = JSON.parse(json) as ProjectFile;
+ assertReaderCompatibility(projectFile);
if (projectFile.version !== SCHEMA_VERSION) {
return this.migrateProject(projectFile);
@@ -230,6 +278,7 @@ export class ProjectSerializer {
exportToJsonWithMetadata(project: Project, description?: string): string {
const projectFile: ProjectFileWithMetadata = {
version: SCHEMA_VERSION,
+ ...getProjectFileCompatibility(project),
project: this.stripMediaBlobs(project),
metadata: {
exportedAt: Date.now(),
@@ -259,6 +308,16 @@ export class ProjectSerializer {
);
}
+ if (
+ projectFile.minimumReaderVersion &&
+ compareVersions(projectFile.minimumReaderVersion, SCHEMA_VERSION) > 0
+ ) {
+ result.errors.push(
+ `Project requires reader ${projectFile.minimumReaderVersion} or newer`,
+ );
+ result.valid = false;
+ }
+
if (!projectFile.project) {
result.errors.push("Missing project field");
result.valid = false;
diff --git a/packages/core/src/storage/schema-types.ts b/packages/core/src/storage/schema-types.ts
index ebbe400d..fff2bfad 100644
--- a/packages/core/src/storage/schema-types.ts
+++ b/packages/core/src/storage/schema-types.ts
@@ -7,6 +7,8 @@ export interface ValidationResult {
export interface ProjectFileWithMetadata {
version: string;
+ minimumReaderVersion?: string;
+ capabilities?: readonly string[];
project: any;
metadata?: {
exportedAt: number;
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index fd170c57..6e2c52c0 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -3,7 +3,6 @@ export * from "./title-engine";
export * from "./text-animation";
export * from "./subtitle-engine";
export * from "./speech-to-text-engine";
-export * from "./transcription-service";
export * from "./caption-animation-renderer";
export * from "./text-animation-presets";
export * from "./character-animator";
diff --git a/packages/core/src/text/title-engine.render-scale.test.ts b/packages/core/src/text/title-engine.render-scale.test.ts
new file mode 100644
index 00000000..8b1fbfcd
--- /dev/null
+++ b/packages/core/src/text/title-engine.render-scale.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { TitleEngine } from "./title-engine";
+
+describe("TitleEngine render scale", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("scales project-space text pixels for a smaller output canvas", () => {
+ const scale = vi.fn();
+ const ctx = {
+ clearRect: vi.fn(),
+ save: vi.fn(),
+ restore: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ scale,
+ measureText: vi.fn(() => ({ width: 200 })),
+ fillRect: vi.fn(),
+ strokeText: vi.fn(),
+ fillText: vi.fn(),
+ font: "",
+ fillStyle: "",
+ strokeStyle: "",
+ lineWidth: 0,
+ textAlign: "center",
+ textBaseline: "middle",
+ globalAlpha: 1,
+ shadowColor: "transparent",
+ shadowBlur: 0,
+ shadowOffsetX: 0,
+ shadowOffsetY: 0,
+ letterSpacing: "0px",
+ };
+
+ class MockOffscreenCanvas {
+ constructor(
+ readonly width: number,
+ readonly height: number,
+ ) {}
+
+ getContext() {
+ return ctx;
+ }
+ }
+
+ vi.stubGlobal("OffscreenCanvas", MockOffscreenCanvas);
+
+ const engine = new TitleEngine();
+ const clip = engine.createTextClip({
+ trackId: "text-track",
+ startTime: 0,
+ text: "Scaled title",
+ style: {
+ fontSize: 96,
+ strokeWidth: 4,
+ letterSpacing: 8,
+ },
+ });
+
+ const result = engine.renderText(clip, 540, 960, 0, {
+ x: 540 / 1080,
+ y: 960 / 1920,
+ });
+
+ expect(result).toMatchObject({ width: 540, height: 960 });
+ expect(scale).toHaveBeenCalledWith(0.5, 0.5);
+ expect(ctx.font).toBe('normal bold 96px "Inter"');
+ expect(ctx.lineWidth).toBe(4);
+ expect(ctx.letterSpacing).toBe("8px");
+ });
+});
diff --git a/packages/core/src/text/title-engine.ts b/packages/core/src/text/title-engine.ts
index 56094a36..de5d21c6 100644
--- a/packages/core/src/text/title-engine.ts
+++ b/packages/core/src/text/title-engine.ts
@@ -215,6 +215,7 @@ export class TitleEngine {
width: number,
height: number,
time: number = 0,
+ contentScale: { x: number; y: number } = { x: 1, y: 1 },
): TextRenderResult {
let canvas: HTMLCanvasElement | OffscreenCanvas;
let ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
@@ -274,7 +275,10 @@ export class TitleEngine {
ctx.translate(posX, posY);
ctx.rotate((transform.rotation * Math.PI) / 180);
- ctx.scale(transform.scale.x, transform.scale.y);
+ ctx.scale(
+ transform.scale.x * contentScale.x,
+ transform.scale.y * contentScale.y,
+ );
ctx.globalAlpha = opacity;
this.applyTextStyle(ctx, style);
diff --git a/packages/core/src/text/transcription-service.ts b/packages/core/src/text/transcription-service.ts
deleted file mode 100644
index 07430f51..00000000
--- a/packages/core/src/text/transcription-service.ts
+++ /dev/null
@@ -1,447 +0,0 @@
-import type { Subtitle, SubtitleStyle, Clip } from "../types/timeline";
-import type { MediaItem } from "../types/project";
-
-export interface CloudflareWhisperWord {
- word: string;
- start: number;
- end: number;
-}
-
-export interface CloudflareWhisperResponse {
- text: string;
- word_count?: number;
- words?: CloudflareWhisperWord[];
- vtt?: string;
-}
-
-export interface WhisperTranscriptionProgress {
- phase:
- | "extracting"
- | "uploading"
- | "transcribing"
- | "processing"
- | "complete"
- | "error";
- progress: number;
- message: string;
-}
-
-export interface TranscriptionConfig {
- apiEndpoint: string;
- apiKey?: string;
- language?: string;
- targetLanguage?: string;
- maxSegmentDuration?: number;
- maxWordsPerSegment?: number;
-}
-
-const DEFAULT_SUBTITLE_STYLE: SubtitleStyle = {
- fontFamily: "Arial",
- fontSize: 24,
- color: "#ffffff",
- backgroundColor: "rgba(0, 0, 0, 0.7)",
- position: "bottom",
-};
-
-export class TranscriptionService {
- private config: TranscriptionConfig;
- private audioContext: AudioContext | null = null;
-
- constructor(config: TranscriptionConfig) {
- this.config = {
- maxSegmentDuration: 5,
- maxWordsPerSegment: 10,
- ...config,
- };
- }
-
- async transcribeClip(
- clip: Clip,
- mediaItem: MediaItem,
- onProgress?: (progress: WhisperTranscriptionProgress) => void,
- ): Promise<Subtitle[]> {
- try {
- onProgress?.({
- phase: "extracting",
- progress: 0,
- message: "Extracting audio from video...",
- });
-
- const audioBlob = await this.extractAudioFromClip(clip, mediaItem);
-
- onProgress?.({
- phase: "uploading",
- progress: 25,
- message: "Uploading audio for transcription...",
- });
-
- const whisperResponse = await this.sendToWhisper(audioBlob, onProgress);
-
- onProgress?.({
- phase: "processing",
- progress: 90,
- message: "Processing transcription...",
- });
-
- const subtitles = this.convertToSubtitles(whisperResponse, clip);
-
- onProgress?.({
- phase: "complete",
- progress: 100,
- message: `Generated ${subtitles.length} subtitles`,
- });
-
- return subtitles;
- } catch (error) {
- onProgress?.({
- phase: "error",
- progress: 0,
- message:
- error instanceof Error ? error.message : "Transcription failed",
- });
- throw error;
- }
- }
-
- private async extractAudioFromClip(
- clip: Clip,
- mediaItem: MediaItem,
- ): Promise<Blob> {
- if (!this.audioContext) {
- this.audioContext = new AudioContext();
- }
-
- let arrayBuffer: ArrayBuffer;
-
- if (mediaItem.blob) {
- arrayBuffer = await mediaItem.blob.arrayBuffer();
- } else if (mediaItem.fileHandle) {
- const file = await mediaItem.fileHandle.getFile();
- arrayBuffer = await file.arrayBuffer();
- } else {
- throw new Error("No media source available for audio extraction");
- }
-
- const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
-
- const inPoint = clip.inPoint || 0;
- const outPoint = clip.outPoint || audioBuffer.duration;
- // A sped-up clip consumes clip.duration * speed seconds of SOURCE audio, so
- // the extracted window spans the source range the clip actually plays — not
- // just clip.duration source seconds (which would truncate a 2x clip's
- // captions to the first half).
- const speed = clip.speed || 1;
- const duration = Math.min(outPoint - inPoint, clip.duration * speed);
-
- const sampleRate = audioBuffer.sampleRate;
- const startSample = Math.floor(inPoint * sampleRate);
- const endSample = Math.floor((inPoint + duration) * sampleRate);
- const numSamples = endSample - startSample;
-
- const offlineContext = new OfflineAudioContext(1, numSamples, sampleRate);
- const source = offlineContext.createBufferSource();
-
- const trimmedBuffer = offlineContext.createBuffer(
- 1,
- numSamples,
- sampleRate,
- );
- const channelData = trimmedBuffer.getChannelData(0);
- const sourceData = audioBuffer.getChannelData(0);
-
- for (let i = 0; i < numSamples; i++) {
- channelData[i] = sourceData[startSample + i] || 0;
- }
-
- source.buffer = trimmedBuffer;
- source.connect(offlineContext.destination);
- source.start(0);
-
- const renderedBuffer = await offlineContext.startRendering();
- return this.audioBufferToWav(renderedBuffer);
- }
-
- private audioBufferToWav(buffer: AudioBuffer): Blob {
- const numChannels = buffer.numberOfChannels;
- const sampleRate = buffer.sampleRate;
- const format = 1;
- const bitDepth = 16;
-
- const bytesPerSample = bitDepth / 8;
- const blockAlign = numChannels * bytesPerSample;
- const byteRate = sampleRate * blockAlign;
- const dataSize = buffer.length * blockAlign;
- const headerSize = 44;
- const totalSize = headerSize + dataSize;
-
- const arrayBuffer = new ArrayBuffer(totalSize);
- const view = new DataView(arrayBuffer);
-
- const writeString = (offset: number, str: string) => {
- for (let i = 0; i < str.length; i++) {
- view.setUint8(offset + i, str.charCodeAt(i));
- }
- };
-
- writeString(0, "RIFF");
- view.setUint32(4, totalSize - 8, true);
- writeString(8, "WAVE");
- writeString(12, "fmt ");
- view.setUint32(16, 16, true);
- view.setUint16(20, format, true);
- view.setUint16(22, numChannels, true);
- view.setUint32(24, sampleRate, true);
- view.setUint32(28, byteRate, true);
- view.setUint16(32, blockAlign, true);
- view.setUint16(34, bitDepth, true);
- writeString(36, "data");
- view.setUint32(40, dataSize, true);
-
- const channelData = buffer.getChannelData(0);
- let offset = 44;
- for (let i = 0; i < buffer.length; i++) {
- const sample = Math.max(-1, Math.min(1, channelData[i]));
- const intSample = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
- view.setInt16(offset, intSample, true);
- offset += 2;
- }
-
- return new Blob([arrayBuffer], { type: "audio/wav" });
- }
-
- private async sendToWhisper(
- audioBlob: Blob,
- onProgress?: (progress: WhisperTranscriptionProgress) => void,
- ): Promise<CloudflareWhisperResponse> {
- const formData = new FormData();
- formData.append("audio", audioBlob, "audio.wav");
-
- if (this.config.language) {
- formData.append("language", this.config.language);
- }
- if (this.config.targetLanguage) {
- formData.append("target_language", this.config.targetLanguage);
- }
-
- onProgress?.({
- phase: "transcribing",
- progress: 30,
- message: "Uploading audio...",
- });
-
- const response = await fetch(this.config.apiEndpoint, {
- method: "POST",
- body: formData,
- });
-
- if (!response.ok) {
- if (response.status === 429) {
- throw new Error(
- "Rate limit reached. Please wait a minute before transcribing more audio. This free service is limited to 10 requests per minute.",
- );
- }
- const errorText = await response.text();
- throw new Error(
- `Transcription failed: ${response.status} - ${errorText}`,
- );
- }
-
- const submitResult = await response.json();
-
- if (!submitResult.jobId) {
- return submitResult as CloudflareWhisperResponse;
- }
-
- const baseUrl = this.config.apiEndpoint.replace(/\/transcribe$/, "").replace(/\/$/, "");
- const pollUrl = `${baseUrl}/jobs/${submitResult.jobId}`;
-
- return this.pollForResult(pollUrl, onProgress);
- }
-
- private async pollForResult(
- pollUrl: string,
- onProgress?: (progress: WhisperTranscriptionProgress) => void,
- ): Promise<CloudflareWhisperResponse> {
- const maxAttempts = 120;
- const pollInterval = 3000;
-
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
-
- const response = await fetch(pollUrl);
- if (!response.ok) {
- if (response.status === 404) {
- throw new Error("Transcription job not found");
- }
- continue;
- }
-
- const job = await response.json();
-
- if (job.status === "processing") {
- const progress = 30 + Math.round((job.progress || 0) * 0.6);
- onProgress?.({
- phase: "transcribing",
- progress,
- message: this.config.targetLanguage
- ? `Transcribing and translating to ${this.config.targetLanguage}...`
- : "Transcribing audio...",
- });
- continue;
- }
-
- if (job.status === "completed" && job.result) {
- return job.result as CloudflareWhisperResponse;
- }
-
- if (job.status === "failed") {
- throw new Error(job.error || "Transcription failed on server");
- }
- }
-
- throw new Error("Transcription timed out after 6 minutes");
- }
-
- private convertToSubtitles(
- response: CloudflareWhisperResponse,
- clip: Clip,
- ): Subtitle[] {
- if (!response.words || response.words.length === 0) {
- if (!response.text) return [];
-
- return [
- {
- id: this.generateId(),
- text: response.text.trim(),
- startTime: clip.startTime,
- endTime: clip.startTime + clip.duration,
- style: DEFAULT_SUBTITLE_STYLE,
- words: undefined,
- animationStyle: "none",
- },
- ];
- }
-
- return this.groupWordsIntoSubtitles(
- response.words,
- clip.startTime,
- clip.speed || 1,
- );
- }
-
- private groupWordsIntoSubtitles(
- words: CloudflareWhisperWord[],
- clipStartTime: number,
- speed: number,
- ): Subtitle[] {
- const subtitles: Subtitle[] = [];
- const maxWords = this.config.maxWordsPerSegment || 10;
- const maxDuration = this.config.maxSegmentDuration || 5;
-
- let currentWords: CloudflareWhisperWord[] = [];
- let groupStart = 0;
-
- for (const word of words) {
- if (currentWords.length === 0) {
- groupStart = word.start;
- }
-
- const wouldExceedWords = currentWords.length >= maxWords;
- const wouldExceedDuration = word.end - groupStart > maxDuration;
- const isPunctuation = /[.!?]$/.test(word.word);
-
- if (
- (wouldExceedWords || wouldExceedDuration) &&
- currentWords.length > 0
- ) {
- subtitles.push(
- this.createSubtitleFromWords(currentWords, clipStartTime, speed),
- );
- currentWords = [word];
- groupStart = word.start;
- } else {
- currentWords.push(word);
-
- if (isPunctuation && currentWords.length >= 3) {
- subtitles.push(
- this.createSubtitleFromWords(currentWords, clipStartTime, speed),
- );
- currentWords = [];
- }
- }
- }
-
- if (currentWords.length > 0) {
- subtitles.push(
- this.createSubtitleFromWords(currentWords, clipStartTime, speed),
- );
- }
-
- return subtitles;
- }
-
- private createSubtitleFromWords(
- words: CloudflareWhisperWord[],
- clipStartTime: number,
- speed: number,
- ): Subtitle {
- const text = words
- .map((w) => w.word)
- .join(" ")
- .trim();
- // Word times are SOURCE-relative seconds (the audio was trimmed to the
- // clip window before transcription, so 0 = inPoint). A source-second plays
- // back compressed/stretched by `speed` on the timeline.
- const safeSpeed = speed || 1;
- const startTime = clipStartTime + words[0].start / safeSpeed;
- const endTime = clipStartTime + words[words.length - 1].end / safeSpeed;
-
- return {
- id: this.generateId(),
- text,
- startTime,
- endTime,
- style: DEFAULT_SUBTITLE_STYLE,
- words: words.map((w) => ({
- text: w.word,
- startTime: clipStartTime + w.start / safeSpeed,
- endTime: clipStartTime + w.end / safeSpeed,
- })),
- animationStyle: "none",
- };
- }
-
- private generateId(): string {
- return `sub-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
- }
-
- dispose(): void {
- if (this.audioContext) {
- this.audioContext.close();
- this.audioContext = null;
- }
- }
-}
-
-let transcriptionServiceInstance: TranscriptionService | null = null;
-
-export function getTranscriptionService(): TranscriptionService | null {
- return transcriptionServiceInstance;
-}
-
-export function initializeTranscriptionService(
- config: TranscriptionConfig,
-): TranscriptionService {
- if (transcriptionServiceInstance) {
- transcriptionServiceInstance.dispose();
- }
- transcriptionServiceInstance = new TranscriptionService(config);
- return transcriptionServiceInstance;
-}
-
-export function disposeTranscriptionService(): void {
- if (transcriptionServiceInstance) {
- transcriptionServiceInstance.dispose();
- transcriptionServiceInstance = null;
- }
-}
diff --git a/packages/core/src/timeline/clip-manager.test.ts b/packages/core/src/timeline/clip-manager.test.ts
index 117ac9fb..23222e50 100644
--- a/packages/core/src/timeline/clip-manager.test.ts
+++ b/packages/core/src/timeline/clip-manager.test.ts
@@ -633,4 +633,26 @@ describe("ClipManager - Helper Methods", () => {
const clips = clipManager.getTrackClips(timeline, "non-existent");
expect(clips.length).toBe(0);
});
+
+ it("accepts every media kind on every normal track", () => {
+ const trackTypes: Track["type"][] = [
+ "video",
+ "audio",
+ "image",
+ "text",
+ "graphics",
+ ];
+ const mediaTypes = ["video", "audio", "image"] as const;
+
+ for (const trackType of trackTypes) {
+ for (const mediaType of mediaTypes) {
+ expect(
+ clipManager.canTrackAcceptClip(
+ createMockTrack({ type: trackType }),
+ mediaType,
+ ),
+ ).toBe(true);
+ }
+ }
+ });
});
diff --git a/packages/core/src/timeline/clip-manager.ts b/packages/core/src/timeline/clip-manager.ts
index 7c4497d3..a2152c1e 100644
--- a/packages/core/src/timeline/clip-manager.ts
+++ b/packages/core/src/timeline/clip-manager.ts
@@ -392,22 +392,10 @@ export class ClipManager {
}
canTrackAcceptClip(
- track: Track,
- mediaType: "video" | "audio" | "image",
+ _track: Track,
+ _mediaType: "video" | "audio" | "image",
): boolean {
- // Video tracks can accept video and image
- if (track.type === "video") {
- return mediaType === "video" || mediaType === "image";
- }
- // Audio tracks can only accept audio
- if (track.type === "audio") {
- return mediaType === "audio";
- }
- // Image tracks can only accept images
- if (track.type === "image") {
- return mediaType === "image";
- }
- return false;
+ return true;
}
setSnapToGrid(enabled: boolean): void {
diff --git a/packages/core/src/timeline/index.ts b/packages/core/src/timeline/index.ts
index 7ae58b00..a749fb22 100644
--- a/packages/core/src/timeline/index.ts
+++ b/packages/core/src/timeline/index.ts
@@ -45,3 +45,32 @@ export {
} from "./nested-sequence-engine";
export { calculateProjectDuration } from "./project-duration";
+
+export {
+ UNIVERSAL_TRACKS_CAPABILITY,
+ UNIVERSAL_TRACKS_MIN_READER_VERSION,
+ getTimelineItems,
+ getTrackItems,
+ resolveTimelineItem,
+ getTimelineItemCapabilities,
+ getMediaItemCapabilities,
+ getVisibleTrackRenderOrder,
+ trackHasVisualItems,
+ trackHasAudioItems,
+ isStandardTrack,
+ projectUsesUniversalTracks,
+ withUniversalTracksCapability,
+ type TimelineItemKind,
+ type TimelineItemCapabilities,
+ type ResolvedTimelineItem,
+ type TimelineTrackRenderEntry,
+} from "./timeline-items";
+
+export {
+ isTimelineIntervalClear,
+ resolveTimelinePlacement,
+ timelineIntervalsOverlap,
+ type TimelinePlacementPolicy,
+ type TimelinePlacementRequest,
+ type TimelinePlacementResult,
+} from "./timeline-placement";
diff --git a/packages/core/src/timeline/timeline-items.test.ts b/packages/core/src/timeline/timeline-items.test.ts
new file mode 100644
index 00000000..ef92b532
--- /dev/null
+++ b/packages/core/src/timeline/timeline-items.test.ts
@@ -0,0 +1,217 @@
+import { describe, expect, it } from "vitest";
+import type { Clip, MediaItem, Project, Track } from "../types";
+import type { TextClip } from "../text/types";
+import {
+ UNIVERSAL_TRACKS_CAPABILITY,
+ getMediaItemCapabilities,
+ getTimelineItemCapabilities,
+ getTimelineItems,
+ getTrackItems,
+ getVisibleTrackRenderOrder,
+ trackHasAudioItems,
+ trackHasVisualItems,
+ withUniversalTracksCapability,
+} from "./timeline-items";
+
+const transform = {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+};
+
+const clip = (id: string, mediaId: string, trackId = "mixed"): Clip => ({
+ id,
+ mediaId,
+ trackId,
+ startTime: id === "audio-clip" ? 2 : 0,
+ duration: 2,
+ inPoint: 0,
+ outPoint: 2,
+ effects: [],
+ audioEffects: [],
+ transform,
+ volume: 1,
+ keyframes: [],
+});
+
+const track: Track = {
+ id: "mixed",
+ type: "text",
+ name: "Legacy Text 1",
+ clips: [clip("video-clip", "video"), clip("audio-clip", "audio")],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+};
+
+const media = (
+ id: string,
+ type: MediaItem["type"],
+ hasVideo: boolean,
+ hasAudio: boolean,
+): MediaItem => ({
+ id,
+ name: id,
+ type,
+ fileHandle: null,
+ blob: null,
+ thumbnailUrl: null,
+ waveformData: null,
+ metadata: {
+ duration: 2,
+ width: hasVideo ? 1920 : 0,
+ height: hasVideo ? 1080 : 0,
+ frameRate: hasVideo ? 30 : 0,
+ codec: "test",
+ sampleRate: hasAudio ? 48000 : 0,
+ channels: hasAudio ? 2 : 0,
+ fileSize: 1,
+ hasVideo,
+ hasAudio,
+ },
+});
+
+const textClip: TextClip = {
+ id: "text-clip",
+ trackId: "mixed",
+ startTime: 4,
+ duration: 2,
+ text: "Mixed",
+ style: {
+ fontFamily: "Inter",
+ fontSize: 24,
+ fontWeight: 400,
+ fontStyle: "normal",
+ color: "#fff",
+ textAlign: "center",
+ verticalAlign: "middle",
+ lineHeight: 1.2,
+ letterSpacing: 0,
+ },
+ transform,
+ keyframes: [],
+};
+
+const project: Project = {
+ id: "project",
+ name: "Mixed",
+ createdAt: 1,
+ modifiedAt: 1,
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48000,
+ channels: 2,
+ },
+ mediaLibrary: {
+ items: [
+ media("video", "video", true, true),
+ media("audio", "audio", false, true),
+ ],
+ },
+ timeline: { tracks: [track], subtitles: [], duration: 6, markers: [] },
+ textClips: [textClip],
+};
+
+describe("universal timeline item model", () => {
+ it("keeps imported still images visual when stream metadata hasVideo is false", () => {
+ const importedImage = media("image", "image", false, false);
+ const mixedTrackProject: Project = {
+ ...project,
+ mediaLibrary: {
+ items: [...project.mediaLibrary.items, importedImage],
+ },
+ timeline: {
+ ...project.timeline,
+ tracks: [
+ {
+ ...track,
+ clips: [
+ clip("video-clip", "video"),
+ {
+ ...clip("image-clip", "image"),
+ startTime: 2,
+ },
+ ],
+ },
+ ],
+ },
+ };
+
+ expect(getMediaItemCapabilities(importedImage)).toEqual({
+ visual: true,
+ audio: false,
+ });
+ expect(
+ getTimelineItemCapabilities(
+ getTrackItems(mixedTrackProject, "mixed").find(
+ (item) => item.id === "image-clip",
+ )!,
+ ),
+ ).toMatchObject({ visual: true, audio: false });
+ expect(trackHasVisualItems(mixedTrackProject, "mixed")).toBe(true);
+ });
+
+ it("renders lower timeline tracks first and keeps index zero on top", () => {
+ const top = { ...track, id: "top", hidden: false };
+ const hidden = { ...track, id: "hidden", hidden: true };
+ const bottom = { ...track, id: "bottom", hidden: false };
+
+ expect(
+ getVisibleTrackRenderOrder([top, hidden, bottom]).map(
+ ({ track: orderedTrack, originalIndex }) => [
+ orderedTrack.id,
+ originalIndex,
+ ],
+ ),
+ ).toEqual([
+ ["bottom", 2],
+ ["top", 0],
+ ]);
+ });
+
+ it("resolves media and overlays from one legacy-typed track", () => {
+ expect(getTrackItems(project, "mixed").map((item) => item.kind)).toEqual([
+ "media",
+ "media",
+ "text",
+ ]);
+ expect(getTimelineItems(project)).toHaveLength(3);
+ });
+
+ it("derives visual and audio behavior from content instead of track type", () => {
+ const items = getTrackItems(project, "mixed");
+ const video = items.find((item) => item.id === "video-clip")!;
+ const audio = items.find((item) => item.id === "audio-clip")!;
+ const text = items.find((item) => item.id === "text-clip")!;
+
+ expect(getTimelineItemCapabilities(video)).toMatchObject({
+ visual: true,
+ audio: true,
+ });
+ expect(getTimelineItemCapabilities(audio)).toMatchObject({
+ visual: false,
+ audio: true,
+ });
+ expect(getTimelineItemCapabilities(text)).toMatchObject({
+ visual: true,
+ audio: false,
+ textEditable: true,
+ });
+ expect(trackHasVisualItems(project, "mixed")).toBe(true);
+ expect(trackHasAudioItems(project, "mixed")).toBe(true);
+ });
+
+ it("marks a project with the reader requirement exactly once", () => {
+ const once = withUniversalTracksCapability(project);
+ const twice = withUniversalTracksCapability(once);
+ expect(once.capabilities).toContain(UNIVERSAL_TRACKS_CAPABILITY);
+ expect(once.minimumReaderVersion).toBe("1.2.0");
+ expect(twice).toBe(once);
+ });
+});
diff --git a/packages/core/src/timeline/timeline-items.ts b/packages/core/src/timeline/timeline-items.ts
new file mode 100644
index 00000000..3ae98aa1
--- /dev/null
+++ b/packages/core/src/timeline/timeline-items.ts
@@ -0,0 +1,293 @@
+import type {
+ Clip,
+ MediaItem,
+ Project,
+ Track,
+} from "../types";
+import type { TextClip } from "../text/types";
+import type { ShapeClip, StickerClip, SVGClip } from "../graphics/types";
+import type { AdjustmentLayer } from "../video/adjustment-layer-engine";
+import type { MotionCompositionInstance } from "../motion/types";
+
+export const UNIVERSAL_TRACKS_CAPABILITY = "universal-tracks-v1";
+export const UNIVERSAL_TRACKS_MIN_READER_VERSION = "1.2.0";
+
+export type TimelineItemKind =
+ | "media"
+ | "text"
+ | "shape"
+ | "svg"
+ | "sticker"
+ | "adjustment"
+ | "motion";
+
+interface TimelineItemBase<TKind extends TimelineItemKind, TItem> {
+ readonly id: string;
+ readonly trackId: string;
+ readonly kind: TKind;
+ readonly startTime: number;
+ readonly duration: number;
+ readonly item: TItem;
+}
+
+export type ResolvedTimelineItem =
+ | (TimelineItemBase<"media", Clip> & { readonly mediaItem?: MediaItem })
+ | TimelineItemBase<"text", TextClip>
+ | TimelineItemBase<"shape", ShapeClip>
+ | TimelineItemBase<"svg", SVGClip>
+ | TimelineItemBase<"sticker", StickerClip>
+ | TimelineItemBase<"adjustment", AdjustmentLayer>
+ | TimelineItemBase<"motion", MotionCompositionInstance>;
+
+export interface TimelineItemCapabilities {
+ readonly visual: boolean;
+ readonly audio: boolean;
+ readonly transformable: boolean;
+ readonly trimSource: boolean;
+ readonly transitionSource: boolean;
+ readonly textEditable: boolean;
+ readonly graphicEditable: boolean;
+}
+
+export interface TimelineTrackRenderEntry {
+ readonly track: Track;
+ readonly originalIndex: number;
+}
+
+/**
+ * Returns visible tracks in canvas painter order. The timeline stores the
+ * front-most track at index 0, so rendering must walk from the last visible
+ * track to the first.
+ */
+export function getVisibleTrackRenderOrder(
+ tracks: readonly Track[],
+): TimelineTrackRenderEntry[] {
+ return tracks
+ .map((track, originalIndex) => ({ track, originalIndex }))
+ .filter(({ track }) => !track.hidden)
+ .reverse();
+}
+
+const VISUAL_ONLY_CAPABILITIES: TimelineItemCapabilities = {
+ visual: true,
+ audio: false,
+ transformable: true,
+ trimSource: false,
+ transitionSource: false,
+ textEditable: false,
+ graphicEditable: false,
+};
+
+function mediaHasVideo(mediaItem: MediaItem | undefined): boolean {
+ if (!mediaItem) return false;
+ // Static images are visual timeline items even though importers correctly
+ // describe them as having no encoded video stream.
+ if (mediaItem.type === "image") return true;
+ if (typeof mediaItem.metadata.hasVideo === "boolean") {
+ return mediaItem.metadata.hasVideo;
+ }
+ return mediaItem.type === "video";
+}
+
+function mediaHasAudio(mediaItem: MediaItem | undefined): boolean {
+ if (!mediaItem) return false;
+ if (typeof mediaItem.metadata.hasAudio === "boolean") {
+ return mediaItem.metadata.hasAudio;
+ }
+ if (mediaItem.type === "audio") return true;
+ if (mediaItem.type !== "video") return false;
+ return mediaItem.metadata.channels > 0 || mediaItem.metadata.sampleRate > 0;
+}
+
+export function getMediaItemCapabilities(
+ mediaItem: MediaItem | undefined,
+): Pick<TimelineItemCapabilities, "visual" | "audio"> {
+ return {
+ visual: mediaHasVideo(mediaItem),
+ audio: mediaHasAudio(mediaItem),
+ };
+}
+
+function mediaItemRef(
+ project: Project,
+ trackId: string,
+ clip: Clip,
+): ResolvedTimelineItem {
+ return {
+ id: clip.id,
+ trackId,
+ kind: "media",
+ startTime: clip.startTime,
+ duration: clip.duration,
+ item: clip,
+ mediaItem: project.mediaLibrary.items.find(
+ (candidate) => candidate.id === clip.mediaId,
+ ),
+ };
+}
+
+export function getTimelineItems(project: Project): ResolvedTimelineItem[] {
+ const items: ResolvedTimelineItem[] = [];
+
+ for (const track of project.timeline.tracks) {
+ for (const clip of track.clips) {
+ items.push(mediaItemRef(project, track.id, clip));
+ }
+ }
+
+ for (const clip of project.textClips ?? []) {
+ items.push({
+ id: clip.id,
+ trackId: clip.trackId,
+ kind: "text",
+ startTime: clip.startTime,
+ duration: clip.duration,
+ item: clip,
+ });
+ }
+
+ for (const clip of project.shapeClips ?? []) {
+ items.push({
+ id: clip.id,
+ trackId: clip.trackId,
+ kind: "shape",
+ startTime: clip.startTime,
+ duration: clip.duration,
+ item: clip,
+ });
+ }
+
+ for (const clip of project.svgClips ?? []) {
+ items.push({
+ id: clip.id,
+ trackId: clip.trackId,
+ kind: "svg",
+ startTime: clip.startTime,
+ duration: clip.duration,
+ item: clip,
+ });
+ }
+
+ for (const clip of project.stickerClips ?? []) {
+ items.push({
+ id: clip.id,
+ trackId: clip.trackId,
+ kind: "sticker",
+ startTime: clip.startTime,
+ duration: clip.duration,
+ item: clip,
+ });
+ }
+
+ for (const layer of project.adjustmentLayers ?? []) {
+ items.push({
+ id: layer.id,
+ trackId: layer.trackId,
+ kind: "adjustment",
+ startTime: layer.startTime,
+ duration: layer.duration,
+ item: layer,
+ });
+ }
+
+ for (const instance of project.motionInstances ?? []) {
+ if (!instance.trackId) continue;
+ items.push({
+ id: instance.id,
+ trackId: instance.trackId,
+ kind: "motion",
+ startTime: instance.startTime,
+ duration: instance.duration,
+ item: instance,
+ });
+ }
+
+ return items.sort(
+ (left, right) =>
+ left.startTime - right.startTime || left.id.localeCompare(right.id),
+ );
+}
+
+export function getTrackItems(
+ project: Project,
+ trackId: string,
+): ResolvedTimelineItem[] {
+ return getTimelineItems(project).filter((item) => item.trackId === trackId);
+}
+
+export function resolveTimelineItem(
+ project: Project,
+ itemId: string,
+): ResolvedTimelineItem | null {
+ return getTimelineItems(project).find((item) => item.id === itemId) ?? null;
+}
+
+export function getTimelineItemCapabilities(
+ item: ResolvedTimelineItem,
+): TimelineItemCapabilities {
+ if (item.kind === "media") {
+ const { visual, audio } = getMediaItemCapabilities(item.mediaItem);
+ return {
+ visual,
+ audio,
+ transformable: visual,
+ trimSource: true,
+ transitionSource:
+ visual &&
+ (item.mediaItem?.type === "video" || item.mediaItem?.type === "image"),
+ textEditable: false,
+ graphicEditable: false,
+ };
+ }
+
+ if (item.kind === "text") {
+ return { ...VISUAL_ONLY_CAPABILITIES, textEditable: true };
+ }
+ if (
+ item.kind === "shape" ||
+ item.kind === "svg" ||
+ item.kind === "sticker"
+ ) {
+ return { ...VISUAL_ONLY_CAPABILITIES, graphicEditable: true };
+ }
+ if (item.kind === "motion") {
+ return { ...VISUAL_ONLY_CAPABILITIES, trimSource: true };
+ }
+ return {
+ ...VISUAL_ONLY_CAPABILITIES,
+ transformable: false,
+ trimSource: true,
+ };
+}
+
+export function trackHasVisualItems(project: Project, trackId: string): boolean {
+ return getTrackItems(project, trackId).some(
+ (item) => getTimelineItemCapabilities(item).visual,
+ );
+}
+
+export function trackHasAudioItems(project: Project, trackId: string): boolean {
+ return getTrackItems(project, trackId).some(
+ (item) => getTimelineItemCapabilities(item).audio,
+ );
+}
+
+export function isStandardTrack(_track: Track): boolean {
+ return true;
+}
+
+export function projectUsesUniversalTracks(project: Project): boolean {
+ return (project.capabilities ?? []).includes(UNIVERSAL_TRACKS_CAPABILITY);
+}
+
+export function withUniversalTracksCapability(project: Project): Project {
+ if (projectUsesUniversalTracks(project)) return project;
+ return {
+ ...project,
+ capabilities: [
+ ...(project.capabilities ?? []),
+ UNIVERSAL_TRACKS_CAPABILITY,
+ ],
+ minimumReaderVersion: UNIVERSAL_TRACKS_MIN_READER_VERSION,
+ };
+}
diff --git a/packages/core/src/timeline/timeline-placement.test.ts b/packages/core/src/timeline/timeline-placement.test.ts
new file mode 100644
index 00000000..73bd2fb5
--- /dev/null
+++ b/packages/core/src/timeline/timeline-placement.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+import type { Project } from "../types";
+import { resolveTimelinePlacement } from "./timeline-placement";
+
+function projectWithTracks(
+ tracks: Array<{
+ id: string;
+ locked?: boolean;
+ clips?: Array<{ id: string; startTime: number; duration: number }>;
+ }>,
+): Project {
+ return {
+ id: "project",
+ name: "Placement",
+ createdAt: 0,
+ modifiedAt: 0,
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48_000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [] },
+ timeline: {
+ duration: 10,
+ tracks: tracks.map((track) => ({
+ id: track.id,
+ name: track.id,
+ type: "video",
+ mode: "standard",
+ locked: track.locked ?? false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ transitions: [],
+ clips: (track.clips ?? []).map((clip) => ({
+ ...clip,
+ mediaId: "media",
+ trackId: track.id,
+ })),
+ })),
+ },
+ } as unknown as Project;
+}
+
+describe("resolveTimelinePlacement", () => {
+ it("keeps an item on the requested row when the interval is clear", () => {
+ const project = projectWithTracks([{ id: "target" }]);
+ expect(
+ resolveTimelinePlacement(project, {
+ targetTrackId: "target",
+ startTime: 2,
+ duration: 3,
+ policy: "stack-above",
+ }),
+ ).toEqual({ ok: true, trackId: "target", startTime: 2 });
+ });
+
+ it("reuses the nearest clear unlocked row above an overlap", () => {
+ const project = projectWithTracks([
+ { id: "far" },
+ { id: "nearest" },
+ {
+ id: "target",
+ clips: [{ id: "existing", startTime: 1, duration: 4 }],
+ },
+ ]);
+ expect(
+ resolveTimelinePlacement(project, {
+ targetTrackId: "target",
+ startTime: 2,
+ duration: 2,
+ policy: "stack-above",
+ }),
+ ).toEqual({ ok: true, trackId: "nearest", startTime: 2 });
+ });
+
+ it("creates one row immediately above when no existing row has room", () => {
+ const project = projectWithTracks([
+ {
+ id: "above",
+ clips: [{ id: "above-clip", startTime: 1, duration: 4 }],
+ },
+ {
+ id: "target",
+ clips: [{ id: "target-clip", startTime: 1, duration: 4 }],
+ },
+ ]);
+ expect(
+ resolveTimelinePlacement(project, {
+ targetTrackId: "target",
+ startTime: 2,
+ duration: 2,
+ policy: "stack-above",
+ newTrackId: "new-track",
+ }),
+ ).toEqual({
+ ok: true,
+ trackId: "new-track",
+ startTime: 2,
+ createdTrack: { id: "new-track", position: 1 },
+ });
+ });
+});
diff --git a/packages/core/src/timeline/timeline-placement.ts b/packages/core/src/timeline/timeline-placement.ts
new file mode 100644
index 00000000..03b2c6c5
--- /dev/null
+++ b/packages/core/src/timeline/timeline-placement.ts
@@ -0,0 +1,118 @@
+import type { Project } from "../types";
+import { getTrackItems, isStandardTrack } from "./timeline-items";
+
+export type TimelinePlacementPolicy = "gap" | "stack-above";
+
+export interface TimelinePlacementRequest {
+ readonly targetTrackId: string;
+ readonly startTime: number;
+ readonly duration: number;
+ readonly policy: TimelinePlacementPolicy;
+ readonly excludeItemIds?: readonly string[];
+ readonly newTrackId?: string;
+}
+
+export type TimelinePlacementResult =
+ | {
+ readonly ok: true;
+ readonly trackId: string;
+ readonly startTime: number;
+ readonly createdTrack?: { readonly id: string; readonly position: number };
+ }
+ | {
+ readonly ok: false;
+ readonly reason: "track-not-found" | "track-locked" | "overlap";
+ };
+
+const PLACEMENT_EPSILON = 0.0001;
+
+export function timelineIntervalsOverlap(
+ leftStart: number,
+ leftDuration: number,
+ rightStart: number,
+ rightDuration: number,
+): boolean {
+ const leftEnd = leftStart + leftDuration;
+ const rightEnd = rightStart + rightDuration;
+ return (
+ leftStart < rightEnd - PLACEMENT_EPSILON &&
+ rightStart < leftEnd - PLACEMENT_EPSILON
+ );
+}
+
+export function isTimelineIntervalClear(
+ project: Project,
+ trackId: string,
+ startTime: number,
+ duration: number,
+ excludeItemIds: readonly string[] = [],
+): boolean {
+ const excluded = new Set(excludeItemIds);
+ return getTrackItems(project, trackId).every(
+ (item) =>
+ excluded.has(item.id) ||
+ !timelineIntervalsOverlap(
+ startTime,
+ duration,
+ item.startTime,
+ item.duration,
+ ),
+ );
+}
+
+/** Resolve the destination row without mutating the project. */
+export function resolveTimelinePlacement(
+ project: Project,
+ request: TimelinePlacementRequest,
+): TimelinePlacementResult {
+ const targetIndex = project.timeline.tracks.findIndex(
+ (track) => track.id === request.targetTrackId,
+ );
+ if (targetIndex < 0) return { ok: false, reason: "track-not-found" };
+
+ const target = project.timeline.tracks[targetIndex];
+ if (target.locked && request.policy === "gap") {
+ return { ok: false, reason: "track-locked" };
+ }
+
+ const startTime = Math.max(0, request.startTime);
+ if (
+ !target.locked &&
+ isTimelineIntervalClear(
+ project,
+ target.id,
+ startTime,
+ request.duration,
+ request.excludeItemIds,
+ )
+ ) {
+ return { ok: true, trackId: target.id, startTime };
+ }
+
+ if (request.policy === "gap") return { ok: false, reason: "overlap" };
+
+ for (let index = targetIndex - 1; index >= 0; index -= 1) {
+ const candidate = project.timeline.tracks[index];
+ if (
+ !candidate.locked &&
+ isStandardTrack(candidate) &&
+ isTimelineIntervalClear(
+ project,
+ candidate.id,
+ startTime,
+ request.duration,
+ request.excludeItemIds,
+ )
+ ) {
+ return { ok: true, trackId: candidate.id, startTime };
+ }
+ }
+
+ const newTrackId = request.newTrackId ?? `track-${crypto.randomUUID()}`;
+ return {
+ ok: true,
+ trackId: newTrackId,
+ startTime,
+ createdTrack: { id: newTrackId, position: targetIndex },
+ };
+}
diff --git a/packages/core/src/timeline/track-manager.ts b/packages/core/src/timeline/track-manager.ts
index ebbe3b47..3130f061 100644
--- a/packages/core/src/timeline/track-manager.ts
+++ b/packages/core/src/timeline/track-manager.ts
@@ -291,20 +291,8 @@ export function getTrackClips(track: Track): Clip[] {
}
export function canAcceptMediaType(
- track: Track,
- mediaType: "video" | "audio" | "image",
+ _track: Track,
+ _mediaType: "video" | "audio" | "image",
): boolean {
- // Video tracks can accept video and image
- if (track.type === "video") {
- return mediaType === "video" || mediaType === "image";
- }
- // Audio tracks can only accept audio
- if (track.type === "audio") {
- return mediaType === "audio";
- }
- // Image tracks can only accept images
- if (track.type === "image") {
- return mediaType === "image";
- }
- return false;
+ return true;
}
diff --git a/packages/core/src/types/actions.ts b/packages/core/src/types/actions.ts
index 390ef5d3..de90cda1 100644
--- a/packages/core/src/types/actions.ts
+++ b/packages/core/src/types/actions.ts
@@ -8,6 +8,7 @@ import type {
Marker,
Effect,
Clip,
+ Track,
Keyframe,
ChromaKeySettings,
SpeedKeyframe,
@@ -127,6 +128,9 @@ export type TrackAction =
position?: number;
/** Pre-assigned track ID. When omitted, the executor generates one. */
trackId?: string;
+ mode?: "standard";
+ role?: Track["role"];
+ name?: string;
};
}
| {
@@ -136,6 +140,9 @@ export type TrackAction =
position?: number;
/** Pre-assigned ID enables deterministic history and collaboration. */
trackId?: string;
+ /** Filled by the executor so redo recreates the same item IDs. */
+ itemIdMap?: Record<string, string>;
+ transitionIdMap?: Record<string, string>;
};
}
| { type: "track/remove"; params: { trackId: string } }
@@ -155,6 +162,9 @@ export type ClipAction =
mediaId: string;
startTime: number;
sourceClip?: Clip;
+ /** Pre-assigned ID keeps grouped placement deterministic on redo. */
+ clipId?: string;
+ duration?: number;
};
}
| { type: "clip/remove"; params: { clipId: string } }
@@ -440,6 +450,20 @@ export type AdjustmentAction =
| { type: "adjustment/setAll"; params: { layers: AdjustmentLayer[] } }
| { type: "mask/setAll"; params: { masks: Mask[] } }
| { type: "multicam/setAll"; params: { groups: MultiCamGroup[] } }
+ | {
+ type: "multicam/applyEdit";
+ params: {
+ outputTrack?: import("./timeline").Track;
+ outputTracks?: import("./timeline").Track[];
+ outputTrackPosition?: number;
+ sourceTrackIds: string[];
+ groups: MultiCamGroup[];
+ };
+ }
+ | {
+ type: "multicam/restoreEdit";
+ params: Record<string, unknown>;
+ }
| {
type: "nested/setAll";
params: {
diff --git a/packages/core/src/types/project.ts b/packages/core/src/types/project.ts
index 3a1e3c1e..6bad5f1e 100644
--- a/packages/core/src/types/project.ts
+++ b/packages/core/src/types/project.ts
@@ -44,6 +44,10 @@ export interface Project {
readonly motionInstances?: MotionCompositionInstance[];
readonly generatedShaders?: readonly MotionShaderDef[];
readonly creation?: CreationProjectState;
+ /** Feature capabilities required to edit this project without data loss. */
+ readonly capabilities?: readonly string[];
+ /** Oldest project reader version that can safely open this project. */
+ readonly minimumReaderVersion?: string;
}
export interface MediaLibrary {
@@ -89,4 +93,7 @@ export interface MediaMetadata {
readonly fileSize: number;
/** Number of audio tracks in the file (may be > 1 for multi-track video/audio files) */
readonly audioTrackCount?: number;
+ /** Optional source-stream flags preserved by modern importers. */
+ readonly hasVideo?: boolean;
+ readonly hasAudio?: boolean;
}
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index 8cea5558..e56203bd 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -36,7 +36,21 @@ export interface TimelineBeatAnalysis {
export interface Track {
readonly id: string;
+ /**
+ * Legacy serialization hint retained for older OpenReel readers. New code
+ * must resolve behavior from the timeline item, not from this value.
+ */
readonly type: "video" | "audio" | "image" | "text" | "graphics";
+ /** Standard tracks accept every timeline item kind. Missing means standard. */
+ readonly mode?: "standard";
+ /** Editorial meaning used for naming, captions, and audio mixing. */
+ readonly role?:
+ | "general"
+ | "captions"
+ | "dialogue"
+ | "music"
+ | "effects"
+ | "ambience";
readonly name: string;
readonly clips: Clip[];
readonly transitions: Transition[];
diff --git a/packages/core/src/video/canvas-fit.test.ts b/packages/core/src/video/canvas-fit.test.ts
new file mode 100644
index 00000000..fb9f00f7
--- /dev/null
+++ b/packages/core/src/video/canvas-fit.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import { resolveCanvasFitDimensions } from "./canvas-fit";
+
+describe("resolveCanvasFitDimensions", () => {
+ const sourceWidth = 1920;
+ const sourceHeight = 1080;
+ const canvasWidth = 1080;
+ const canvasHeight = 1920;
+
+ it("contains a landscape source inside a portrait canvas", () => {
+ expect(
+ resolveCanvasFitDimensions(
+ "contain",
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ ),
+ ).toEqual({ width: 1080, height: 607.5 });
+ });
+
+ it("treats a missing or none fit mode as contain", () => {
+ const expected = { width: 1080, height: 607.5 };
+ expect(
+ resolveCanvasFitDimensions(
+ undefined,
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ ),
+ ).toEqual(expected);
+ expect(
+ resolveCanvasFitDimensions(
+ "none",
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ ),
+ ).toEqual(expected);
+ });
+
+ it("covers a portrait canvas without distorting the source", () => {
+ const dimensions = resolveCanvasFitDimensions(
+ "cover",
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ );
+
+ expect(dimensions.width).toBeCloseTo(3413.333, 3);
+ expect(dimensions.height).toBe(1920);
+ });
+
+ it("stretches the source to the canvas", () => {
+ expect(
+ resolveCanvasFitDimensions(
+ "stretch",
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ ),
+ ).toEqual({ width: 1080, height: 1920 });
+ });
+
+ it("uses the cropped source aspect ratio", () => {
+ const dimensions = resolveCanvasFitDimensions(
+ "cover",
+ 960,
+ 1080,
+ canvasWidth,
+ canvasHeight,
+ );
+
+ expect(dimensions.width).toBeCloseTo(1706.667, 3);
+ expect(dimensions.height).toBe(1920);
+ });
+
+ it("returns safe dimensions for invalid inputs", () => {
+ expect(resolveCanvasFitDimensions("cover", 0, 0, 1080, 1920)).toEqual({
+ width: 1080,
+ height: 1920,
+ });
+ });
+});
diff --git a/packages/core/src/video/canvas-fit.ts b/packages/core/src/video/canvas-fit.ts
new file mode 100644
index 00000000..f4eccb88
--- /dev/null
+++ b/packages/core/src/video/canvas-fit.ts
@@ -0,0 +1,58 @@
+import type { FitMode } from "../types/timeline";
+
+export interface CanvasFitDimensions {
+ width: number;
+ height: number;
+}
+
+/**
+ * Resolve the size used to draw a source into a canvas. The source dimensions
+ * should describe the visible source rectangle, after cropping when present.
+ */
+export function resolveCanvasFitDimensions(
+ fitMode: FitMode | undefined,
+ sourceWidth: number,
+ sourceHeight: number,
+ canvasWidth: number,
+ canvasHeight: number,
+): CanvasFitDimensions {
+ if (
+ !Number.isFinite(sourceWidth) ||
+ !Number.isFinite(sourceHeight) ||
+ !Number.isFinite(canvasWidth) ||
+ !Number.isFinite(canvasHeight) ||
+ sourceWidth <= 0 ||
+ sourceHeight <= 0 ||
+ canvasWidth <= 0 ||
+ canvasHeight <= 0
+ ) {
+ return {
+ width: Math.max(0, Number.isFinite(canvasWidth) ? canvasWidth : 0),
+ height: Math.max(0, Number.isFinite(canvasHeight) ? canvasHeight : 0),
+ };
+ }
+
+ const mode = !fitMode || fitMode === "none" ? "contain" : fitMode;
+ if (mode === "stretch") {
+ return { width: canvasWidth, height: canvasHeight };
+ }
+
+ const sourceAspect = sourceWidth / sourceHeight;
+ const canvasAspect = canvasWidth / canvasHeight;
+ const fitByHeight =
+ mode === "cover"
+ ? sourceAspect > canvasAspect
+ : sourceAspect <= canvasAspect;
+
+ if (fitByHeight) {
+ return {
+ width: canvasHeight * sourceAspect,
+ height: canvasHeight,
+ };
+ }
+
+ return {
+ width: canvasWidth,
+ height: canvasWidth / sourceAspect,
+ };
+}
diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.ts
index 315bf8ca..e4e30a2a 100644
--- a/packages/core/src/video/index.ts
+++ b/packages/core/src/video/index.ts
@@ -1,4 +1,5 @@
export * from "./video-engine";
+export * from "./canvas-fit";
export * from "./video-effects-engine";
export * from "./color-grading-engine";
export * from "./color-grading-defaults";
diff --git a/packages/core/src/video/multicam-engine.test.ts b/packages/core/src/video/multicam-engine.test.ts
new file mode 100644
index 00000000..d4a633c7
--- /dev/null
+++ b/packages/core/src/video/multicam-engine.test.ts
@@ -0,0 +1,256 @@
+import { describe, expect, it } from "vitest";
+import type { Clip } from "../types/timeline";
+import { DEFAULT_MULTICAM_EDIT_POLICY } from "../multicam/automatic-edit";
+import { DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS } from "../multicam/manifest";
+import { MultiCamEngine, type MultiCamGroup } from "./multicam-engine";
+
+function group(updates: Partial<MultiCamGroup> = {}): MultiCamGroup {
+ return {
+ id: "group-1",
+ name: "Interview",
+ angles: [
+ {
+ id: "a",
+ name: "Host",
+ clipId: "clip-a",
+ trackId: "source-a",
+ offset: 0,
+ color: "#f00",
+ isActive: true,
+ },
+ {
+ id: "b",
+ name: "Guest",
+ clipId: "clip-b",
+ trackId: "source-b",
+ offset: 0.25,
+ color: "#0f0",
+ isActive: false,
+ },
+ ],
+ activeAngleId: "a",
+ syncPoint: 10,
+ duration: 8,
+ createdAt: 1,
+ ...updates,
+ };
+}
+
+function clip(id: string): Clip {
+ return {
+ id,
+ mediaId: `media-${id}`,
+ trackId: `track-${id}`,
+ startTime: 0,
+ duration: 12,
+ inPoint: 1,
+ outPoint: 13,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ };
+}
+
+describe("MultiCamEngine automatic edits", () => {
+ it("normalizes legacy groups and persists switch changes on the group", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([group()]);
+
+ engine.addSwitch("group-1", "b", 2, {
+ reason: "speaker",
+ confidence: 0.9,
+ });
+
+ expect(engine.getAllGroups()[0]?.switches).toEqual([
+ expect.objectContaining({
+ groupId: "group-1",
+ angleId: "b",
+ time: 2,
+ reason: "speaker",
+ confidence: 0.9,
+ }),
+ ]);
+ });
+
+ it("converts a decision list into stable, persisted switches", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([group()]);
+
+ const switches = engine.applyAutomaticEdit(
+ "group-1",
+ {
+ duration: 6,
+ segments: [
+ { angleId: "a", startTime: 0, endTime: 3, reason: "speaker", confidence: 1 },
+ { angleId: "b", startTime: 3, endTime: 6, reason: "speaker", confidence: 0.8 },
+ ],
+ },
+ DEFAULT_MULTICAM_EDIT_POLICY,
+ 50,
+ );
+
+ expect(switches.map(({ angleId, time }) => ({ angleId, time }))).toEqual([
+ { angleId: "a", time: 0 },
+ { angleId: "b", time: 3 },
+ ]);
+ expect(engine.getGroup("group-1")).toMatchObject({
+ duration: 6,
+ activeAngleId: "a",
+ automaticEdit: {
+ activityWindowMs: 50,
+ policy: DEFAULT_MULTICAM_EDIT_POLICY,
+ },
+ });
+ });
+
+ it("builds trimmed output clips at the group sync point", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([
+ group({
+ switches: [
+ { id: "s1", groupId: "group-1", angleId: "a", time: 0, reason: "speaker" },
+ { id: "s2", groupId: "group-1", angleId: "b", time: 3, reason: "speaker" },
+ ],
+ duration: 6,
+ }),
+ ]);
+
+ const output = engine.buildSequenceClips(
+ "group-1",
+ "multicam-output",
+ new Map([
+ ["clip-a", clip("clip-a")],
+ ["clip-b", clip("clip-b")],
+ ]),
+ );
+
+ expect(output).toHaveLength(2);
+ expect(output[0]?.clip).toMatchObject({
+ mediaId: "media-clip-a",
+ trackId: "multicam-output",
+ startTime: 10,
+ duration: 3,
+ inPoint: 1,
+ outPoint: 4,
+ metadata: { multicam: { groupId: "group-1", angleId: "a" } },
+ });
+ expect(output[1]?.clip).toMatchObject({
+ mediaId: "media-clip-b",
+ startTime: 13,
+ duration: 3,
+ inPoint: 4.25,
+ outPoint: 7.25,
+ });
+ });
+
+ it("applies a raw audio offset independently of clip playback speed", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([
+ group({
+ switches: [
+ { id: "s1", groupId: "group-1", angleId: "b", time: 2 },
+ ],
+ activeAngleId: "b",
+ duration: 4,
+ }),
+ ]);
+ const fastClip = { ...clip("clip-b"), speed: 2 };
+
+ const output = engine.buildSequenceClips(
+ "group-1",
+ "output",
+ new Map([["clip-b", fastClip]]),
+ );
+
+ expect(output[0]?.clip.inPoint).toBe(1.25);
+ expect(output[1]?.clip.inPoint).toBe(5.25);
+ });
+
+ it("removes switches that reference a deleted angle", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([
+ group({
+ switches: [{ id: "s1", groupId: "group-1", angleId: "b", time: 2 }],
+ }),
+ ]);
+
+ engine.removeAngle("group-1", "b");
+
+ expect(engine.getSwitches("group-1")).toEqual([]);
+ });
+
+ it("materializes split layouts as grouped panel tracks with morph keyframes", () => {
+ const engine = new MultiCamEngine();
+ engine.loadGroups([group({
+ manifest: {
+ spec: "openreel-multicam/v1",
+ fps: 25,
+ sync: { method: "audio-crosscorr", reference: "a" },
+ participants: [
+ { id: "p1", name: "Host", audio: "a", seat: "left" },
+ { id: "p2", name: "Guest", audio: "b", seat: "right" },
+ ],
+ cameras: [
+ { id: "a", type: "closeup", subject: "p1", file: "a.mp4", clipId: "clip-a" },
+ { id: "b", type: "closeup", subject: "p2", file: "b.mp4", clipId: "clip-b" },
+ ],
+ constraints: DEFAULT_MULTICAM_MANIFEST_CONSTRAINTS,
+ },
+ shotPlan: {
+ spec: "openreel-multicam-edit/v1",
+ durationMs: 4_000,
+ shots: [
+ {
+ startMs: 0,
+ endMs: 2_000,
+ reason: "speaker",
+ confidence: 1,
+ transitionIn: { type: "cut", durationMs: 0 },
+ layout: {
+ template: "solo",
+ panels: [{ cameraId: "a", subject: "p1", rect: { x: 0, y: 0, width: 1, height: 1 } }],
+ },
+ },
+ {
+ startMs: 2_000,
+ endMs: 4_000,
+ reason: "sustained-overlap",
+ confidence: 0.9,
+ transitionIn: { type: "layout-morph", durationMs: 200 },
+ layout: {
+ template: "split2",
+ panels: [
+ { cameraId: "a", subject: "p1", rect: { x: 0, y: 0, width: 0.5, height: 1 } },
+ { cameraId: "b", subject: "p2", rect: { x: 0.5, y: 0, width: 0.5, height: 1 } },
+ ],
+ },
+ },
+ ],
+ },
+ })]);
+
+ const tracks = engine.buildShotPlanTracks(
+ "group-1",
+ "output",
+ new Map([["clip-a", clip("clip-a")], ["clip-b", clip("clip-b")]]),
+ { width: 1920, height: 1080 },
+ );
+
+ expect(tracks).toHaveLength(2);
+ expect(tracks[0]?.clips[1]?.transform).toMatchObject({
+ position: { x: -480, y: 0 },
+ scale: { x: 0.5, y: 1 },
+ });
+ expect(tracks[0]?.clips[1]?.keyframes).toHaveLength(4);
+ expect(tracks[1]?.clips[0]?.volume).toBe(0);
+ expect(new Set(tracks.flatMap((track) => track.clips.map((entry) => entry.id))).size).toBe(3);
+ });
+});
diff --git a/packages/core/src/video/multicam-engine.ts b/packages/core/src/video/multicam-engine.ts
index c42270d9..e6ee4642 100644
--- a/packages/core/src/video/multicam-engine.ts
+++ b/packages/core/src/video/multicam-engine.ts
@@ -1,3 +1,13 @@
+import type {
+ MulticamEditDecisionList,
+ MulticamEditPolicy,
+} from "../multicam/automatic-edit";
+import type { Clip, Track } from "../types/timeline";
+import type { ProjectSettings } from "../types/project";
+import type { MulticamManifest } from "../multicam/manifest";
+import type { MulticamShotPlan } from "../multicam/shot-planner";
+import type { MulticamShotPolicy } from "../multicam/shot-planner";
+
export interface CameraAngle {
id: string;
name: string;
@@ -6,6 +16,7 @@ export interface CameraAngle {
offset: number;
color: string;
isActive: boolean;
+ driftSecondsPerSecond?: number;
}
export interface MultiCamGroup {
@@ -16,6 +27,23 @@ export interface MultiCamGroup {
syncPoint: number;
duration: number;
createdAt: number;
+ switches?: AngleSwitch[];
+ outputTrackId?: string;
+ outputTrackIds?: string[];
+ automaticEdit?: MulticamAutomaticEditMetadata;
+ manifest?: MulticamManifest;
+ analysisArtifactId?: string;
+ shotPlan?: MulticamShotPlan;
+ editPolicy?: MulticamShotPolicy;
+ annotations?: MulticamSegmentAnnotation[];
+}
+
+export interface MulticamSegmentAnnotation {
+ id: string;
+ startMs: number;
+ endMs: number;
+ note: string;
+ createdAt: number;
}
export interface AngleSwitch {
@@ -23,6 +51,22 @@ export interface AngleSwitch {
groupId: string;
angleId: string;
time: number;
+ reason?: string;
+ confidence?: number;
+ reviewStatus?: "pending" | "accepted";
+}
+
+export interface MulticamAutomaticEditMetadata {
+ generatedAt: number;
+ activityWindowMs: number;
+ policy: MulticamEditPolicy;
+}
+
+export interface MulticamSequenceClip {
+ angleId: string;
+ reason?: string;
+ confidence?: number;
+ clip: Clip;
}
export interface SyncResult {
@@ -42,9 +86,26 @@ const ANGLE_COLORS = [
"#ec4899",
];
+function cloneGroup(group: MultiCamGroup): MultiCamGroup {
+ return {
+ ...group,
+ angles: group.angles.map((angle) => ({ ...angle })),
+ switches: (group.switches ?? []).map((switchItem) => ({ ...switchItem })),
+ automaticEdit: group.automaticEdit
+ ? {
+ ...group.automaticEdit,
+ policy: { ...group.automaticEdit.policy },
+ }
+ : undefined,
+ manifest: group.manifest ? structuredClone(group.manifest) : undefined,
+ shotPlan: group.shotPlan ? structuredClone(group.shotPlan) : undefined,
+ editPolicy: group.editPolicy ? structuredClone(group.editPolicy) : undefined,
+ annotations: group.annotations ? structuredClone(group.annotations) : undefined,
+ };
+}
+
export class MultiCamEngine {
private groups: Map<string, MultiCamGroup> = new Map();
- private switches: Map<string, AngleSwitch[]> = new Map();
constructor() {}
@@ -69,10 +130,10 @@ export class MultiCamEngine {
syncPoint: 0,
duration: 0,
createdAt: Date.now(),
+ switches: [],
};
this.groups.set(id, group);
- this.switches.set(id, []);
return group;
}
@@ -82,18 +143,18 @@ export class MultiCamEngine {
}
getAllGroups(): MultiCamGroup[] {
- return Array.from(this.groups.values());
+ return Array.from(this.groups.values(), cloneGroup);
}
loadGroups(groups: MultiCamGroup[]): void {
this.groups.clear();
for (const group of groups) {
- this.groups.set(group.id, group);
+ const normalized = cloneGroup(group);
+ this.groups.set(group.id, normalized);
}
}
deleteGroup(groupId: string): boolean {
- this.switches.delete(groupId);
return this.groups.delete(groupId);
}
@@ -124,6 +185,9 @@ export class MultiCamEngine {
if (index === -1) return false;
group.angles.splice(index, 1);
+ group.switches = (group.switches ?? []).filter(
+ (switchItem) => switchItem.angleId !== angleId,
+ );
if (group.activeAngleId === angleId && group.angles.length > 0) {
group.activeAngleId = group.angles[0].id;
@@ -158,6 +222,7 @@ export class MultiCamEngine {
groupId: string,
angleId: string,
time: number,
+ details: Pick<AngleSwitch, "reason" | "confidence"> = {},
): AngleSwitch | null {
const group = this.groups.get(groupId);
if (!group) return null;
@@ -170,37 +235,173 @@ export class MultiCamEngine {
groupId,
angleId,
time,
+ ...details,
};
- const switches = this.switches.get(groupId) || [];
+ const switches = group.switches ?? [];
switches.push(switchItem);
switches.sort((a, b) => a.time - b.time);
- this.switches.set(groupId, switches);
+ group.switches = switches;
return switchItem;
}
removeSwitch(groupId: string, switchId: string): boolean {
- const switches = this.switches.get(groupId);
+ const group = this.groups.get(groupId);
+ const switches = group?.switches;
if (!switches) return false;
const index = switches.findIndex((s) => s.id === switchId);
if (index === -1) return false;
+ const removed = switches[index]!;
switches.splice(index, 1);
+ const plan = group?.shotPlan;
+ if (plan) {
+ const shotIndex = plan.shots.findIndex(
+ (shot) => Math.abs(shot.startMs / 1_000 - removed.time) < 0.001,
+ );
+ if (shotIndex > 0) {
+ plan.shots[shotIndex - 1]!.endMs = plan.shots[shotIndex]!.endMs;
+ plan.shots.splice(shotIndex, 1);
+ const previous = plan.shots[shotIndex - 1];
+ const next = plan.shots[shotIndex];
+ if (
+ previous &&
+ next &&
+ JSON.stringify(previous.layout) === JSON.stringify(next.layout)
+ ) {
+ previous.endMs = next.endMs;
+ plan.shots.splice(shotIndex, 1);
+ }
+ }
+ }
return true;
}
getSwitches(groupId: string): AngleSwitch[] {
- return this.switches.get(groupId) || [];
+ return this.groups.get(groupId)?.switches ?? [];
+ }
+
+ replaceSwitches(
+ groupId: string,
+ switches: readonly Omit<AngleSwitch, "id" | "groupId">[],
+ ): AngleSwitch[] {
+ const group = this.groups.get(groupId);
+ if (!group) return [];
+ const angleIds = new Set(group.angles.map((angle) => angle.id));
+ group.switches = switches
+ .filter(
+ (switchItem) =>
+ angleIds.has(switchItem.angleId) &&
+ Number.isFinite(switchItem.time) &&
+ switchItem.time >= 0 &&
+ switchItem.time < group.duration,
+ )
+ .map((switchItem, index) => ({
+ ...switchItem,
+ id: `switch_${group.id}_${Math.round(switchItem.time * 1_000)}_${index}`,
+ groupId: group.id,
+ }))
+ .sort((a, b) => a.time - b.time);
+ return group.switches;
+ }
+
+ applyAutomaticEdit(
+ groupId: string,
+ edit: MulticamEditDecisionList,
+ policy: MulticamEditPolicy,
+ activityWindowMs: number,
+ ): AngleSwitch[] {
+ const group = this.groups.get(groupId);
+ if (!group) return [];
+ group.duration = edit.duration;
+ group.automaticEdit = {
+ generatedAt: Date.now(),
+ activityWindowMs,
+ policy: { ...policy },
+ };
+ const switches = this.replaceSwitches(
+ groupId,
+ edit.segments.map((segment) => ({
+ angleId: segment.angleId,
+ time: segment.startTime,
+ reason: segment.reason,
+ confidence: segment.confidence,
+ reviewStatus: segment.startTime === 0 ? "accepted" : "pending",
+ })),
+ );
+ if (switches[0]) {
+ this.setActiveAngle(groupId, switches[0].angleId);
+ }
+ return switches;
+ }
+
+ acceptSwitch(groupId: string, switchId: string): boolean {
+ const switchItem = this.groups
+ .get(groupId)
+ ?.switches?.find((entry) => entry.id === switchId);
+ if (!switchItem) return false;
+ switchItem.reviewStatus = "accepted";
+ return true;
+ }
+
+ nudgeSwitch(
+ groupId: string,
+ switchId: string,
+ deltaSeconds: number,
+ minimumShotSeconds = 0.1,
+ ): boolean {
+ const switches = this.groups.get(groupId)?.switches;
+ if (!switches) return false;
+ const index = switches.findIndex((entry) => entry.id === switchId);
+ if (index <= 0) return false;
+ const previous = switches[index - 1]!;
+ const current = switches[index]!;
+ const previousTime = current.time;
+ const next = switches[index + 1];
+ current.time = Math.min(
+ (next?.time ?? this.groups.get(groupId)?.duration ?? current.time) -
+ minimumShotSeconds,
+ Math.max(previous.time + minimumShotSeconds, current.time + deltaSeconds),
+ );
+ current.reviewStatus = "pending";
+ const plan = this.groups.get(groupId)?.shotPlan;
+ if (plan) {
+ const shotIndex = plan.shots.findIndex(
+ (shot) => Math.abs(shot.startMs / 1_000 - previousTime) < 0.001,
+ );
+ if (shotIndex > 0) {
+ plan.shots[shotIndex - 1]!.endMs = current.time * 1_000;
+ plan.shots[shotIndex]!.startMs = current.time * 1_000;
+ }
+ }
+ switches.sort((left, right) => left.time - right.time);
+ return true;
+ }
+
+ setOutputTrack(groupId: string, trackId: string | undefined): boolean {
+ const group = this.groups.get(groupId);
+ if (!group) return false;
+ group.outputTrackId = trackId;
+ group.outputTrackIds = trackId ? [trackId] : [];
+ return true;
+ }
+
+ setOutputTracks(groupId: string, trackIds: readonly string[]): boolean {
+ const group = this.groups.get(groupId);
+ if (!group) return false;
+ group.outputTrackIds = [...trackIds];
+ group.outputTrackId = trackIds[0];
+ return true;
}
getAngleAtTime(groupId: string, time: number): CameraAngle | null {
const group = this.groups.get(groupId);
if (!group) return null;
- const switches = this.switches.get(groupId) || [];
- let activeAngleId = group.angles[0]?.id;
+ const switches = group.switches ?? [];
+ let activeAngleId = group.activeAngleId || group.angles[0]?.id;
for (const sw of switches) {
if (sw.time <= time) {
@@ -335,13 +536,14 @@ export class MultiCamEngine {
if (group) {
group.angles = [];
group.activeAngleId = "";
+ group.switches = [];
+ group.outputTrackId = undefined;
+ group.automaticEdit = undefined;
}
- this.switches.set(groupId, []);
}
clearAll(): void {
this.groups.clear();
- this.switches.clear();
}
exportGroupAsSequence(
@@ -350,7 +552,7 @@ export class MultiCamEngine {
const group = this.groups.get(groupId);
if (!group) return [];
- const switches = this.switches.get(groupId) || [];
+ const switches = group.switches ?? [];
const sequence: { clipId: string; startTime: number; endTime: number }[] =
[];
@@ -368,7 +570,7 @@ export class MultiCamEngine {
return sequence;
}
- let currentAngleId = group.angles[0]?.id;
+ let currentAngleId = group.activeAngleId || group.angles[0]?.id;
let currentStartTime = 0;
for (let i = 0; i < switches.length; i++) {
@@ -398,6 +600,222 @@ export class MultiCamEngine {
return sequence;
}
+
+ buildSequenceClips(
+ groupId: string,
+ outputTrackId: string,
+ sourceClips: ReadonlyMap<string, Clip>,
+ ): MulticamSequenceClip[] {
+ const group = this.groups.get(groupId);
+ if (!group) return [];
+
+ const switchByTime = new Map(
+ (group.switches ?? []).map((switchItem) => [switchItem.time, switchItem]),
+ );
+ return this.exportGroupAsSequence(groupId).flatMap((segment) => {
+ const angle = group.angles.find((item) => item.clipId === segment.clipId);
+ const source = sourceClips.get(segment.clipId);
+ if (!angle || !source) return [];
+
+ const playbackRate = Math.max(0.01, source.speed ?? 1);
+ const requestedInPoint =
+ source.inPoint +
+ segment.startTime * playbackRate +
+ angle.offset +
+ (angle.driftSecondsPerSecond ?? 0) * segment.startTime;
+ const inPoint = Math.max(source.inPoint, requestedInPoint);
+ const skippedTimeline = (inPoint - requestedInPoint) / playbackRate;
+ const timelineStart = segment.startTime + skippedTimeline;
+ const requestedDuration = segment.endTime - timelineStart;
+ const availableDuration = Math.max(
+ 0,
+ (source.outPoint - inPoint) / playbackRate,
+ );
+ const duration = Math.min(requestedDuration, availableDuration);
+ if (duration <= 0) return [];
+
+ const switchItem = switchByTime.get(segment.startTime);
+ const multicamMetadata = {
+ groupId,
+ angleId: angle.id,
+ reason: switchItem?.reason,
+ confidence: switchItem?.confidence,
+ };
+ const clip: Clip = {
+ ...structuredClone(source),
+ id: `${source.id}-multicam-${Math.round(timelineStart * 1_000)}`,
+ trackId: outputTrackId,
+ startTime: group.syncPoint + timelineStart,
+ duration,
+ inPoint,
+ outPoint: inPoint + duration * playbackRate,
+ metadata: {
+ ...source.metadata,
+ multicam: multicamMetadata,
+ },
+ };
+ return [{
+ angleId: angle.id,
+ reason: switchItem?.reason,
+ confidence: switchItem?.confidence,
+ clip,
+ }];
+ });
+ }
+
+ buildShotPlanTracks(
+ groupId: string,
+ outputTrackId: string,
+ sourceClips: ReadonlyMap<string, Clip>,
+ settings: Pick<ProjectSettings, "width" | "height">,
+ ): Track[] {
+ const group = this.groups.get(groupId);
+ const plan = group?.shotPlan;
+ const manifest = group?.manifest;
+ if (!group || !plan || !manifest) return [];
+ const panelCount = plan.shots.reduce(
+ (maximum, shot) => Math.max(maximum, shot.layout.panels.length),
+ 1,
+ );
+ return Array.from({ length: panelCount }, (_, panelIndex) => {
+ const trackId = panelIndex === 0
+ ? outputTrackId
+ : `${outputTrackId}-panel-${panelIndex + 1}`;
+ const clips = plan.shots.flatMap((shot, shotIndex) => {
+ const panel = shot.layout.panels[panelIndex];
+ if (!panel) return [];
+ const camera = manifest.cameras.find((entry) => entry.id === panel.cameraId);
+ const angle = group.angles.find(
+ (entry) => entry.id === panel.cameraId || entry.clipId === camera?.clipId,
+ );
+ const source = angle ? sourceClips.get(angle.clipId) : undefined;
+ if (!angle || !source) return [];
+ const segmentStart = shot.startMs / 1_000;
+ const segmentEnd = shot.endMs / 1_000;
+ const playbackRate = Math.max(0.01, source.speed ?? 1);
+ const requestedInPoint =
+ source.inPoint +
+ segmentStart * playbackRate +
+ angle.offset +
+ (angle.driftSecondsPerSecond ?? 0) * segmentStart;
+ const inPoint = Math.max(source.inPoint, requestedInPoint);
+ const skippedTimeline = (inPoint - requestedInPoint) / playbackRate;
+ const timelineStart = segmentStart + skippedTimeline;
+ const availableDuration = Math.max(
+ 0,
+ (source.outPoint - inPoint) / playbackRate,
+ );
+ const duration = Math.min(segmentEnd - timelineStart, availableDuration);
+ if (duration <= 0) return [];
+ const targetPosition = {
+ x:
+ source.transform.position.x +
+ (panel.rect.x + panel.rect.width / 2 - 0.5) * settings.width,
+ y:
+ source.transform.position.y +
+ (panel.rect.y + panel.rect.height / 2 - 0.5) * settings.height,
+ };
+ const targetScale = {
+ x: source.transform.scale.x * panel.rect.width,
+ y: source.transform.scale.y * panel.rect.height,
+ };
+ const previousPanel = plan.shots[shotIndex - 1]?.layout.panels.find(
+ (entry) => entry.cameraId === panel.cameraId,
+ );
+ const morphDuration = Math.min(
+ duration,
+ shot.transitionIn.type === "layout-morph"
+ ? shot.transitionIn.durationMs / 1_000
+ : 0,
+ );
+ const morphKeyframes = previousPanel && morphDuration > 0
+ ? [
+ {
+ id: `${groupId}-${shot.startMs}-${panelIndex}-position-start`,
+ time: 0,
+ property: "transform.position",
+ value: {
+ x: source.transform.position.x +
+ (previousPanel.rect.x + previousPanel.rect.width / 2 - 0.5) * settings.width,
+ y: source.transform.position.y +
+ (previousPanel.rect.y + previousPanel.rect.height / 2 - 0.5) * settings.height,
+ },
+ easing: "ease-in-out" as const,
+ },
+ {
+ id: `${groupId}-${shot.startMs}-${panelIndex}-position-end`,
+ time: morphDuration,
+ property: "transform.position",
+ value: targetPosition,
+ easing: "ease-in-out" as const,
+ },
+ {
+ id: `${groupId}-${shot.startMs}-${panelIndex}-scale-start`,
+ time: 0,
+ property: "transform.scale",
+ value: {
+ x: source.transform.scale.x * previousPanel.rect.width,
+ y: source.transform.scale.y * previousPanel.rect.height,
+ },
+ easing: "ease-in-out" as const,
+ },
+ {
+ id: `${groupId}-${shot.startMs}-${panelIndex}-scale-end`,
+ time: morphDuration,
+ property: "transform.scale",
+ value: targetScale,
+ easing: "ease-in-out" as const,
+ },
+ ]
+ : [];
+ const clip: Clip = {
+ ...structuredClone(source),
+ id: `${source.id}-multicam-${shot.startMs}-panel-${panelIndex + 1}`,
+ trackId,
+ startTime: group.syncPoint + timelineStart,
+ duration,
+ inPoint,
+ outPoint: inPoint + duration * playbackRate,
+ volume: panelIndex === 0 ? source.volume : 0,
+ transform: {
+ ...structuredClone(source.transform),
+ position: targetPosition,
+ scale: targetScale,
+ fitMode: "cover",
+ crop: panel.crop,
+ },
+ keyframes: [...structuredClone(source.keyframes), ...morphKeyframes],
+ metadata: {
+ ...source.metadata,
+ multicam: {
+ groupId,
+ angleId: angle.id,
+ panelIndex,
+ layout: shot.layout.template,
+ rect: panel.rect,
+ reason: shot.reason,
+ confidence: shot.confidence,
+ },
+ },
+ };
+ return [clip];
+ });
+ return {
+ id: trackId,
+ type: "video",
+ name: panelIndex === 0
+ ? `${group.name} Auto Edit`
+ : `${group.name} Panel ${panelIndex + 1}`,
+ clips,
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ groupId: `multicam-layout-${group.id}`,
+ };
+ });
+ }
}
export const multicamEngine = new MultiCamEngine();
diff --git a/packages/core/src/video/video-engine-export-effects.test.ts b/packages/core/src/video/video-engine-export-effects.test.ts
index 168a2827..1a194169 100644
--- a/packages/core/src/video/video-engine-export-effects.test.ts
+++ b/packages/core/src/video/video-engine-export-effects.test.ts
@@ -347,6 +347,38 @@ describe("VideoEngine export frame effects", () => {
expect(whiteBalancedBitmap.close).toHaveBeenCalledTimes(1);
});
+ it("does not scale an output-sized decoded frame twice", async () => {
+ const outputSizedBitmap = makeBitmap("output-sized", 320, 180);
+ const finalBitmap = makeBitmap("scaled-final", 320, 180);
+ vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue(finalBitmap));
+
+ const project = makeProject(makeClip([], {} as ClipColorGrading));
+ const { VideoEngine } = await import("./video-engine");
+ const engine = new VideoEngine();
+ Object.assign(engine as unknown as Record<string, unknown>, {
+ initialized: true,
+ mediabunny: {},
+ });
+ vi.spyOn(
+ engine as unknown as {
+ decodeFrameWithMediaBunny: () => Promise<ImageBitmap>;
+ },
+ "decodeFrameWithMediaBunny",
+ ).mockResolvedValue(outputSizedBitmap);
+
+ await engine.renderFrame(project, 1, 320, 180);
+
+ expect(ctx.scale).toHaveBeenCalledWith(1, 1);
+ expect(ctx.scale).not.toHaveBeenCalledWith(0.5, 0.5);
+ expect(ctx.drawImage).toHaveBeenCalledWith(
+ outputSizedBitmap,
+ -160,
+ -90,
+ 320,
+ 180,
+ );
+ });
+
it("recreates the effects engine and retries a transient export failure", async () => {
const sourceBitmap = makeBitmap("retry-source");
const processedBitmap = makeBitmap("retry-processed");
diff --git a/packages/core/src/video/video-engine-text-scale.test.ts b/packages/core/src/video/video-engine-text-scale.test.ts
new file mode 100644
index 00000000..a75f2600
--- /dev/null
+++ b/packages/core/src/video/video-engine-text-scale.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { titleEngine } from "../text/title-engine";
+import { DEFAULT_TEXT_STYLE, DEFAULT_TEXT_TRANSFORM } from "../text/types";
+import type { TextClip } from "../text/types";
+
+describe("VideoEngine text output scaling", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it("passes the project-to-output ratio to TitleEngine", async () => {
+ vi.stubGlobal("self", {
+ onmessage: null,
+ postMessage: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ });
+
+ const renderedCanvas = {} as OffscreenCanvas;
+ const renderText = vi.spyOn(titleEngine, "renderText").mockReturnValue({
+ canvas: renderedCanvas,
+ width: 540,
+ height: 960,
+ textMetrics: { width: 0, height: 0, lines: [] },
+ });
+ const ctx = {
+ drawImage: vi.fn(),
+ } as unknown as OffscreenCanvasRenderingContext2D;
+ const clip: TextClip = {
+ id: "title-1",
+ trackId: "text-track",
+ startTime: 0,
+ duration: 5,
+ text: "Scaled title",
+ style: DEFAULT_TEXT_STYLE,
+ transform: DEFAULT_TEXT_TRANSFORM,
+ keyframes: [],
+ effects: [],
+ };
+
+ const { VideoEngine } = await import("./video-engine");
+ const engine = new VideoEngine() as unknown as {
+ renderTextClipToCanvasCtx(
+ context: OffscreenCanvasRenderingContext2D,
+ textClip: TextClip,
+ time: number,
+ width: number,
+ height: number,
+ projectWidth: number,
+ projectHeight: number,
+ ): Promise<void>;
+ };
+
+ await engine.renderTextClipToCanvasCtx(
+ ctx,
+ clip,
+ 0,
+ 540,
+ 960,
+ 1080,
+ 1920,
+ );
+
+ expect(renderText).toHaveBeenCalledWith(clip, 540, 960, 0, {
+ x: 0.5,
+ y: 0.5,
+ });
+ expect(ctx.drawImage).toHaveBeenCalledWith(renderedCanvas, 0, 0);
+ });
+});
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 7e40cad1..3d85c099 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -84,6 +84,11 @@ import { MotionHighQualityRenderer } from "../motion/motion-gpu-render";
import { renderAuroraPreviewToImageBitmap } from "../motion/native-aurora-bridge";
import type { MotionAsset } from "../motion/types";
import { resolveCreationMotionSceneBinding } from "../creation/render-binding";
+import { resolveCanvasFitDimensions } from "./canvas-fit";
+import {
+ getMediaItemCapabilities,
+ getVisibleTrackRenderOrder,
+} from "../timeline/timeline-items";
const DEFAULT_CACHE_CONFIG: FrameCacheConfig = {
maxFrames: 100,
@@ -654,17 +659,7 @@ export class VideoEngine {
const activeSubtitles = this.getActiveSubtitles(timeline, time);
- const allRenderableTracks = timeline.tracks
- .map((track, idx) => ({ track, originalIndex: idx }))
- .filter(
- ({ track }) =>
- (track.type === "video" ||
- track.type === "image" ||
- track.type === "text" ||
- track.type === "graphics") &&
- !track.hidden,
- )
- .sort((a, b) => b.originalIndex - a.originalIndex);
+ const allRenderableTracks = getVisibleTrackRenderOrder(timeline.tracks);
if (
!this.compositeCanvas ||
@@ -706,22 +701,34 @@ export class VideoEngine {
(clip) => clip.behindSubject,
);
const subjectStreamId = `video-engine:text-behind-subject:${allRenderableTracks
- .filter(
- ({ track }) => track.type === "video" || track.type === "image",
- )
.flatMap(({ track }) =>
track.clips
.filter(
(clip) =>
- time >= clip.startTime && time < clip.startTime + clip.duration,
+ time >= clip.startTime &&
+ time < clip.startTime + clip.duration &&
+ getMediaItemCapabilities(
+ mediaLibrary.items.find((item) => item.id === clip.mediaId),
+ ).visual,
)
.map((clip) => clip.id),
)
.sort()
.join("|") || "canvas"}`;
+ await this.renderMotionInstancesToCanvasCtx(
+ ctx,
+ project,
+ time,
+ width,
+ height,
+ scaleX,
+ scaleY,
+ null,
+ );
+
for (const { track } of allRenderableTracks) {
- if (track.type === "video" || track.type === "image") {
+ {
// If a clip-to-clip transition is active in this track at `time`,
// decode both participating clips, blend them, and draw the result.
// The clip IDs that were rendered as part of the transition are
@@ -741,7 +748,11 @@ export class VideoEngine {
subjectFrame = await this.captureSubjectFrame(ctx, width, height);
}
- const clips = this.getClipsAtTime(track, time);
+ const clips = this.getClipsAtTime(track, time).filter((clip) =>
+ getMediaItemCapabilities(
+ mediaLibrary.items.find((item) => item.id === clip.mediaId),
+ ).visual,
+ );
for (const clip of clips) {
if (renderedTransitionClips.has(clip.id)) continue;
const clipInfo = this.createClipRenderInfo(clip, time);
@@ -767,10 +778,7 @@ export class VideoEngine {
x: transform.position.x * scaleX,
y: transform.position.y * scaleY,
},
- scale: {
- x: transform.scale.x * scaleX,
- y: transform.scale.y * scaleY,
- },
+ scale: { ...transform.scale },
};
let processed = compoundFrame;
try {
@@ -944,10 +952,7 @@ export class VideoEngine {
x: finalTransform.position.x * scaleX,
y: finalTransform.position.y * scaleY,
},
- scale: {
- x: finalTransform.scale.x * scaleX,
- y: finalTransform.scale.y * scaleY,
- },
+ scale: { ...finalTransform.scale },
};
let processedBitmap = bitmap;
@@ -1024,38 +1029,60 @@ export class VideoEngine {
}
}
}
- }
- // Overlays composite on top of all clip tracks, matching the preview's layering.
- for (const shapeClip of activeShapeClips) {
- await this.renderShapeClipToCanvasCtx(ctx, shapeClip, time, width, height);
- }
- for (const svgClip of activeSVGClips) {
- await this.renderSVGClipToCanvasCtx(ctx, svgClip, time, width, height);
- }
- for (const stickerClip of activeStickerClips) {
- await this.renderStickerClipToCanvasCtx(ctx, stickerClip, time, width, height);
- }
- await this.renderMotionInstancesToCanvasCtx(
- ctx,
- project,
- time,
- width,
- height,
- scaleX,
- scaleY,
- );
- for (const textClip of activeTextClips) {
- await this.renderTextClipWithSubjectMask(
+ for (const shapeClip of activeShapeClips.filter(
+ (clip) => clip.trackId === track.id,
+ )) {
+ await this.renderShapeClipToCanvasCtx(
+ ctx,
+ shapeClip,
+ time,
+ width,
+ height,
+ );
+ }
+ for (const svgClip of activeSVGClips.filter(
+ (clip) => clip.trackId === track.id,
+ )) {
+ await this.renderSVGClipToCanvasCtx(ctx, svgClip, time, width, height);
+ }
+ for (const stickerClip of activeStickerClips.filter(
+ (clip) => clip.trackId === track.id,
+ )) {
+ await this.renderStickerClipToCanvasCtx(
+ ctx,
+ stickerClip,
+ time,
+ width,
+ height,
+ );
+ }
+ await this.renderMotionInstancesToCanvasCtx(
ctx,
- textClip,
+ project,
time,
width,
height,
- subjectFrame,
- options.realtime ?? false,
- subjectStreamId,
+ scaleX,
+ scaleY,
+ track.id,
);
+ for (const textClip of activeTextClips.filter(
+ (clip) => clip.trackId === track.id,
+ )) {
+ await this.renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ time,
+ width,
+ height,
+ settings.width,
+ settings.height,
+ subjectFrame,
+ options.realtime ?? false,
+ subjectStreamId,
+ );
+ }
}
subjectFrame?.close();
@@ -1180,6 +1207,7 @@ export class VideoEngine {
height: number,
scaleX: number,
scaleY: number,
+ targetTrackId?: string | null,
): Promise<void> {
const compositions = project.motionCompositions ?? [];
const instances = (project.motionInstances ?? [])
@@ -1194,6 +1222,12 @@ export class VideoEngine {
})
.filter(({ instance, track }) => {
if (track?.hidden) return false;
+ if (
+ targetTrackId !== undefined &&
+ (instance.trackId ?? null) !== targetTrackId
+ ) {
+ return false;
+ }
return (
time >= instance.startTime &&
time < instance.startTime + instance.duration
@@ -1351,75 +1385,36 @@ export class VideoEngine {
ctx.rotate((transform.rotation * Math.PI) / 180);
ctx.scale(transform.scale.x, transform.scale.y);
- if (transform.crop) {
- const sx = transform.crop.x * frame.width;
- const sy = transform.crop.y * frame.height;
- const sWidth = transform.crop.width * frame.width;
- const sHeight = transform.crop.height * frame.height;
-
- const croppedAspect = sWidth / sHeight;
- const canvasAspect = canvasWidth / canvasHeight;
-
- let cropDrawWidth: number;
- let cropDrawHeight: number;
-
- if (croppedAspect > canvasAspect) {
- cropDrawWidth = canvasWidth;
- cropDrawHeight = canvasWidth / croppedAspect;
- } else {
- cropDrawHeight = canvasHeight;
- cropDrawWidth = canvasHeight * croppedAspect;
- }
+ const crop = transform.crop;
+ const sourceWidth = crop ? crop.width * frame.width : frame.width;
+ const sourceHeight = crop ? crop.height * frame.height : frame.height;
+ const { width: drawWidth, height: drawHeight } =
+ resolveCanvasFitDimensions(
+ transform.fitMode,
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ );
+ const drawX = -drawWidth * transform.anchor.x;
+ const drawY = -drawHeight * transform.anchor.y;
- const cropDrawX = -cropDrawWidth * transform.anchor.x;
- const cropDrawY = -cropDrawHeight * transform.anchor.y;
+ if (crop) {
+ const sx = crop.x * frame.width;
+ const sy = crop.y * frame.height;
ctx.drawImage(
frame,
sx,
sy,
- sWidth,
- sHeight,
- cropDrawX,
- cropDrawY,
- cropDrawWidth,
- cropDrawHeight,
+ sourceWidth,
+ sourceHeight,
+ drawX,
+ drawY,
+ drawWidth,
+ drawHeight,
);
} else {
- // Treat a missing or "none" fit as "contain" so clips preserve their
- // aspect ratio on export/compositing, matching the preview.
- const fitMode =
- !transform.fitMode || transform.fitMode === "none"
- ? "contain"
- : transform.fitMode;
- let drawWidth = frame.width;
- let drawHeight = frame.height;
-
- const sourceAspect = frame.width / frame.height;
- const canvasAspect = canvasWidth / canvasHeight;
- if (fitMode === "stretch") {
- drawWidth = canvasWidth;
- drawHeight = canvasHeight;
- } else if (fitMode === "cover") {
- if (sourceAspect > canvasAspect) {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- } else {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- }
- } else {
- if (sourceAspect > canvasAspect) {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- } else {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- }
- }
-
- const drawX = -drawWidth * transform.anchor.x;
- const drawY = -drawHeight * transform.anchor.y;
ctx.drawImage(frame, drawX, drawY, drawWidth, drawHeight);
}
@@ -1496,17 +1491,18 @@ export class VideoEngine {
): Promise<void> {
const baseTracks = timeline.tracks
.map((track, idx) => ({ track, idx }))
- .filter(
- ({ track }) =>
- (track.type === "video" || track.type === "image") && !track.hidden,
- )
+ .filter(({ track }) => !track.hidden)
// Highest index renders behind, so the bottom-most layer is the backdrop.
.sort((a, b) => b.idx - a.idx);
let frame: ImageBitmap | null = null;
let ownsFrame = false;
for (const { track } of baseTracks) {
- const clips = this.getClipsAtTime(track, time);
+ const clips = this.getClipsAtTime(track, time).filter((candidate) =>
+ getMediaItemCapabilities(
+ mediaLibrary.items.find((item) => item.id === candidate.mediaId),
+ ).visual,
+ );
if (clips.length === 0) continue;
const clip = clips[0];
const clipInfo = this.createClipRenderInfo(clip, time);
@@ -1711,6 +1707,8 @@ export class VideoEngine {
time: number,
width: number,
height: number,
+ projectWidth: number,
+ projectHeight: number,
subjectFrame: ImageBitmap | null,
realtime: boolean,
streamId: string,
@@ -1733,7 +1731,15 @@ export class VideoEngine {
}
if (!textClip.behindSubject || !subjectFrame || !subjectMask) {
- await this.renderTextClipToCanvasCtx(ctx, textClip, time, width, height);
+ await this.renderTextClipToCanvasCtx(
+ ctx,
+ textClip,
+ time,
+ width,
+ height,
+ projectWidth,
+ projectHeight,
+ );
return;
}
@@ -1746,6 +1752,8 @@ export class VideoEngine {
time,
width,
height,
+ projectWidth,
+ projectHeight,
);
if (
!this.applySubjectOcclusionMask(
@@ -1763,13 +1771,12 @@ export class VideoEngine {
private getActiveTextClips(timeline: Timeline, time: number): TextClip[] {
const allTextClips = titleEngine.getAllTextClips();
- const textTracks = timeline.tracks.filter(
- (t) => t.type === "text" && !t.hidden,
+ const visibleTrackIds = new Set(
+ timeline.tracks.filter((track) => !track.hidden).map((track) => track.id),
);
- const textTrackIds = new Set(textTracks.map((t) => t.id));
return allTextClips.filter((clip) => {
- if (!textTrackIds.has(clip.trackId)) return false;
+ if (!visibleTrackIds.has(clip.trackId)) return false;
const clipEnd = clip.startTime + clip.duration;
return time >= clip.startTime && time < clipEnd;
});
@@ -1777,13 +1784,12 @@ export class VideoEngine {
private getActiveShapeClips(timeline: Timeline, time: number): ShapeClip[] {
const allShapeClips = graphicsEngine.getAllShapeClips();
- const graphicsTracks = timeline.tracks.filter(
- (t) => t.type === "graphics" && !t.hidden,
+ const visibleTrackIds = new Set(
+ timeline.tracks.filter((track) => !track.hidden).map((track) => track.id),
);
- const graphicsTrackIds = new Set(graphicsTracks.map((t) => t.id));
return allShapeClips.filter((clip) => {
- if (!graphicsTrackIds.has(clip.trackId)) return false;
+ if (!visibleTrackIds.has(clip.trackId)) return false;
const clipEnd = clip.startTime + clip.duration;
return time >= clip.startTime && time < clipEnd;
});
@@ -1794,13 +1800,12 @@ export class VideoEngine {
time: number,
): import("../graphics/types").SVGClip[] {
const allSVGClips = graphicsEngine.getAllSVGClips();
- const graphicsTracks = timeline.tracks.filter(
- (t) => t.type === "graphics" && !t.hidden,
+ const visibleTrackIds = new Set(
+ timeline.tracks.filter((track) => !track.hidden).map((track) => track.id),
);
- const graphicsTrackIds = new Set(graphicsTracks.map((t) => t.id));
return allSVGClips.filter((clip) => {
- if (!graphicsTrackIds.has(clip.trackId)) return false;
+ if (!visibleTrackIds.has(clip.trackId)) return false;
const clipEnd = clip.startTime + clip.duration;
return time >= clip.startTime && time < clipEnd;
});
@@ -1811,13 +1816,12 @@ export class VideoEngine {
time: number,
): import("../graphics/types").StickerClip[] {
const allStickerClips = graphicsEngine.getAllStickerClips();
- const graphicsTracks = timeline.tracks.filter(
- (t) => t.type === "graphics" && !t.hidden,
+ const visibleTrackIds = new Set(
+ timeline.tracks.filter((track) => !track.hidden).map((track) => track.id),
);
- const graphicsTrackIds = new Set(graphicsTracks.map((t) => t.id));
return allStickerClips.filter((clip) => {
- if (!graphicsTrackIds.has(clip.trackId)) return false;
+ if (!visibleTrackIds.has(clip.trackId)) return false;
const clipEnd = clip.startTime + clip.duration;
return time >= clip.startTime && time < clipEnd;
});
@@ -1829,6 +1833,8 @@ export class VideoEngine {
time: number,
width: number,
height: number,
+ projectWidth: number,
+ projectHeight: number,
): Promise<void> {
const clipLocalTime = time - textClip.startTime;
const result = titleEngine.renderText(
@@ -1836,6 +1842,10 @@ export class VideoEngine {
width,
height,
clipLocalTime,
+ {
+ x: projectWidth > 0 ? width / projectWidth : 1,
+ y: projectHeight > 0 ? height / projectHeight : 1,
+ },
);
await this.drawOverlayCanvasWithEffects(
@@ -2224,7 +2234,14 @@ export class VideoEngine {
const mediaB = clipB
? mediaLibrary.items.find((m) => m.id === clipB.mediaId)
: undefined;
- if (!mediaA?.blob || (clipB && !mediaB?.blob)) return rendered;
+ if (
+ !mediaA?.blob ||
+ !getMediaItemCapabilities(mediaA).visual ||
+ (clipB &&
+ (!mediaB?.blob || !getMediaItemCapabilities(mediaB).visual))
+ ) {
+ return rendered;
+ }
let bitmapA: ImageBitmap | null = null;
let bitmapB: ImageBitmap | null = null;
@@ -3400,75 +3417,36 @@ export class VideoEngine {
ctx.scale(transform.scale.x, transform.scale.y);
- if (transform.crop) {
- const sx = transform.crop.x * frame.width;
- const sy = transform.crop.y * frame.height;
- const sWidth = transform.crop.width * frame.width;
- const sHeight = transform.crop.height * frame.height;
-
- const croppedAspect = sWidth / sHeight;
- const canvasAspect = canvasWidth / canvasHeight;
-
- let cropDrawWidth: number;
- let cropDrawHeight: number;
-
- if (croppedAspect > canvasAspect) {
- cropDrawWidth = canvasWidth;
- cropDrawHeight = canvasWidth / croppedAspect;
- } else {
- cropDrawHeight = canvasHeight;
- cropDrawWidth = canvasHeight * croppedAspect;
- }
+ const crop = transform.crop;
+ const sourceWidth = crop ? crop.width * frame.width : frame.width;
+ const sourceHeight = crop ? crop.height * frame.height : frame.height;
+ const { width: drawWidth, height: drawHeight } =
+ resolveCanvasFitDimensions(
+ transform.fitMode,
+ sourceWidth,
+ sourceHeight,
+ canvasWidth,
+ canvasHeight,
+ );
+ const drawX = -drawWidth * transform.anchor.x;
+ const drawY = -drawHeight * transform.anchor.y;
- const cropDrawX = -cropDrawWidth * transform.anchor.x;
- const cropDrawY = -cropDrawHeight * transform.anchor.y;
+ if (crop) {
+ const sx = crop.x * frame.width;
+ const sy = crop.y * frame.height;
ctx.drawImage(
frame,
sx,
sy,
- sWidth,
- sHeight,
- cropDrawX,
- cropDrawY,
- cropDrawWidth,
- cropDrawHeight,
+ sourceWidth,
+ sourceHeight,
+ drawX,
+ drawY,
+ drawWidth,
+ drawHeight,
);
} else {
- // Treat a missing or "none" fit as "contain" so clips preserve their
- // aspect ratio on export/compositing, matching the preview.
- const fitMode =
- !transform.fitMode || transform.fitMode === "none"
- ? "contain"
- : transform.fitMode;
- let drawWidth = frame.width;
- let drawHeight = frame.height;
-
- const sourceAspect = frame.width / frame.height;
- const canvasAspect = canvasWidth / canvasHeight;
- if (fitMode === "stretch") {
- drawWidth = canvasWidth;
- drawHeight = canvasHeight;
- } else if (fitMode === "cover") {
- if (sourceAspect > canvasAspect) {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- } else {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- }
- } else {
- if (sourceAspect > canvasAspect) {
- drawWidth = canvasWidth;
- drawHeight = canvasWidth / sourceAspect;
- } else {
- drawHeight = canvasHeight;
- drawWidth = canvasHeight * sourceAspect;
- }
- }
-
- const drawX = -drawWidth * transform.anchor.x;
- const drawY = -drawHeight * transform.anchor.y;
ctx.drawImage(frame, drawX, drawY, drawWidth, drawHeight);
}
diff --git a/packages/ui/src/components/slider.tsx b/packages/ui/src/components/slider.tsx
index 686e91ae..e6ae01cf 100644
--- a/packages/ui/src/components/slider.tsx
+++ b/packages/ui/src/components/slider.tsx
@@ -6,7 +6,7 @@ import { cn } from "@openreel/ui/lib/utils"
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
->(({ className, ...props }, ref) => (
+>(({ className, "aria-label": ariaLabel, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
@@ -18,7 +18,10 @@ const Slider = React.forwardRef<
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-background-tertiary">
<SliderPrimitive.Range className="absolute h-full bg-text-secondary" />
</SliderPrimitive.Track>
- <SliderPrimitive.Thumb className="block h-2.5 w-2.5 rounded-full bg-white shadow-sm ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
+ <SliderPrimitive.Thumb
+ aria-label={ariaLabel}
+ className="block h-2.5 w-2.5 rounded-full bg-white shadow-sm ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
+ />
</SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName
diff --git a/packages/ui/src/components/toolcraft-menu.tsx b/packages/ui/src/components/toolcraft-menu.tsx
index 4a58d35d..939c822b 100644
--- a/packages/ui/src/components/toolcraft-menu.tsx
+++ b/packages/ui/src/components/toolcraft-menu.tsx
@@ -187,6 +187,10 @@ export function ToolcraftContextMenu({
<ContextMenuContent
className={cn("min-w-40", className)}
style={menuWidth ? { width: toCssSize(menuWidth) } : undefined}
+ onPointerDown={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onMouseUp={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
>
{renderContextOptions(items, size)}
</ContextMenuContent>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6b115fb2..713c03b7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -26,6 +26,34 @@ importers:
specifier: ^0.1.1
+ apps/cloud:
+ dependencies:
+ '@openreel/fxpkg':
+ specifier: workspace:*
+ version: link:../../packages/fxpkg
+ hono:
+ specifier: ^4.11.4
+ version: 4.12.23
+ jose:
+ specifier: ^6.2.3
+ version: 6.2.3
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
+ devDependencies:
+ '@cloudflare/workers-types':
+ specifier: ^4.20260117.0
+ version: 4.20260117.0
+ typescript:
+ specifier: ^5.5.2
+ version: 5.9.3
+ vitest:
+ specifier: ^1.6.0
+ version: 1.6.1(@types/[email protected])(@vitest/[email protected])([email protected])
+ wrangler:
+ specifier: ^3.101.0
+ version: 3.114.17(@cloudflare/[email protected])
+
apps/desktop:
dependencies:
electron-updater:
@@ -46,7 +74,7 @@ importers:
version: 24.13.3([email protected])
tsup:
specifier: ^8.0.0
typescript:
specifier: ^5.4.5
version: 5.9.3
@@ -167,10 +195,10 @@ importers:
version: 8.5.6
tailwindcss:
specifier: ^3.4.4
- version: 3.4.18
+ version: 3.4.18([email protected])
tailwindcss-animate:
specifier: ^1.0.7
- version: 1.0.7([email protected])
typescript:
specifier: ^5.4.5
version: 5.9.3
@@ -279,7 +307,7 @@ importers:
version: 8.5.6
tailwindcss:
specifier: ^3.4.4
- version: 3.4.18
+ version: 3.4.18([email protected])
typescript:
specifier: ^5.4.5
version: 5.9.3
@@ -304,6 +332,9 @@ importers:
'@huggingface/transformers':
specifier: 3.8.1
version: 3.8.1
+ '@mediapipe/tasks-vision':
+ specifier: ^0.10.35
+ version: 0.10.35
'@openreel/agent':
specifier: workspace:*
version: link:../../packages/agent
@@ -328,6 +359,9 @@ importers:
gsap:
specifier: ^3.14.2
version: 3.14.2
+ idb-keyval:
+ specifier: ^6.2.2
+ version: 6.2.2
lucide-react:
specifier: ^0.555.0
version: 0.555.0([email protected])
@@ -340,9 +374,15 @@ importers:
react-dom:
specifier: ^19.2.7
version: 19.2.7([email protected])
+ react-markdown:
+ specifier: ^10.1.0
+ version: 10.1.0(@types/[email protected])([email protected])
react-syntax-highlighter:
specifier: ^16.1.0
version: 16.1.0([email protected])
+ remark-gfm:
+ specifier: ^4.0.1
+ version: 4.0.1
three:
specifier: ^0.182.0
version: 0.182.0
@@ -403,10 +443,10 @@ importers:
version: 8.5.6
tailwindcss:
specifier: ^3.4.4
- version: 3.4.18
+ version: 3.4.18([email protected])
tailwindcss-animate:
specifier: ^1.0.7
- version: 1.0.7([email protected])
typescript:
specifier: ^5.4.5
version: 5.9.3
@@ -450,7 +490,7 @@ importers:
version: 20.19.41
tsup:
specifier: ^8.0.0
typescript:
specifier: ^5.4.5
version: 5.9.3
@@ -490,6 +530,9 @@ importers:
mediabunny:
specifier: ^1.25.3
version: 1.25.3
+ onnxruntime-web:
+ specifier: 1.21.0
+ version: 1.21.0
polygon-clipping:
specifier: 0.15.7
version: 0.15.7
@@ -499,6 +542,9 @@ importers:
uuid:
specifier: ^13.0.0
version: 13.0.0
+ yaml:
+ specifier: ^2.4.2
+ version: 2.9.0
devDependencies:
'@types/three':
specifier: ^0.182.0
@@ -2762,6 +2808,9 @@ packages:
resolution: {integrity: sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
+
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -2783,6 +2832,9 @@ packages:
resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}
+
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
@@ -2899,6 +2951,9 @@ packages:
resolution: {integrity: sha512-LZ2NqIHFhvFwxG0qZeLL9DvdNAHPGCY5dIRwBhyYeU+LfLhcStE1ImjsuTG/WaVh3XysGaeLW8Rqq7cGkPCFvw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ '@ungap/[email protected]':
+ resolution: {integrity: sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg==}
+
'@vitejs/[email protected]':
resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}
engines: {node: ^14.18.0 || >=16.0.0}
@@ -3082,6 +3137,9 @@ packages:
peerDependencies:
postcss: ^8.1.0
+ resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}
+
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
@@ -3188,6 +3246,9 @@ packages:
resolution: {integrity: sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==}
+ resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
+
resolution: {integrity: sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw==}
engines: {node: '>=4'}
@@ -3196,6 +3257,9 @@ packages:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
+
resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}
@@ -3426,6 +3490,9 @@ packages:
resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}
+ resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
+
resolution: {integrity: sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==}
@@ -3564,6 +3631,10 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==}
engines: {node: '>=18'}
@@ -3585,6 +3656,7 @@ packages:
resolution: {integrity: sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options.
hasBin: true
peerDependencies:
jiti: '*'
@@ -3613,6 +3685,9 @@ packages:
resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}
engines: {node: '>=4.0'}
+ resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
+
resolution: {integrity: sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==}
@@ -3634,6 +3709,9 @@ packages:
resolution: {integrity: sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA==}
+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}
+
resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==}
engines: {node: '>= 10.17.0'}
@@ -3931,6 +4009,12 @@ packages:
resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}
+ resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
+
+ resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
+
resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==}
@@ -3946,6 +4030,10 @@ packages:
resolution: {integrity: sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==}
+ resolution: {integrity: sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==}
+ engines: {node: '>=16.9.0'}
+
resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}
engines: {node: '>=10'}
@@ -3954,6 +4042,9 @@ packages:
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
+
resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}
@@ -4029,6 +4120,9 @@ packages:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
+ resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
+
resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}
@@ -4081,6 +4175,10 @@ packages:
resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
engines: {node: '>=0.12.0'}
+ resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==}
engines: {node: '>=0.10.0'}
@@ -4126,6 +4224,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
+ resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==}
+
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
@@ -4262,6 +4363,9 @@ packages:
resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
+ resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
+
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
@@ -4310,6 +4414,9 @@ packages:
resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
+
resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}
engines: {node: '>=10'}
@@ -4318,6 +4425,51 @@ packages:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}
+
+ resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==}
+
+ resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==}
+
+ resolution: {integrity: sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==}
+
+ resolution: {integrity: sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==}
+
+ resolution: {integrity: sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==}
+
+ resolution: {integrity: sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==}
+
+ resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
+
+ resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
+
+ resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}
+
+ resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
+
+ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
+
+ resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}
+
+ resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}
+
+ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}
+
resolution: {integrity: sha512-+LDXv/kybsElRQCmMlrdbKmPNvegeIyouGeOUzW5DJ8+M56H4G6wyEL2AJ1A45UcOB+U62qJMV7tuFO9S7yA7g==}
@@ -4331,6 +4483,90 @@ packages:
resolution: {integrity: sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==}
+ resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
+
+ resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}
+
+ resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}
+
+ resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}
+
+ resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==}
+
+ resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}
+
+ resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}
+
+ resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
+
+ resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
+
+ resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}
+
+ resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}
+
+ resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}
+
+ resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==}
+
+ resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==}
+
+ resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==}
+
+ resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==}
+
+ resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==}
+
+ resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==}
+
+ resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}
+
+ resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}
+
+ resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==}
+
+ resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==}
+
+ resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==}
+
+ resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==}
+
+ resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==}
+
+ resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}
+
+ resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}
+
+ resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}
+
resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
engines: {node: '>=8.6'}
@@ -4805,6 +5041,12 @@ packages:
resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}
+ resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
+ peerDependencies:
+ '@types/react': '>=18'
+ react: '>=18'
+
resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==}
engines: {node: '>=0.10.0'}
@@ -4885,6 +5127,18 @@ packages:
resolution: {integrity: sha512-QXOrHQF5jOpjjLfiNk5GFnWhRXvxjUVnlFxkeDmewR5sXkr3iM46Zo+CnRR8B+MDVqkULW4EcLVcRBNOPXHosw==}
+ resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
+
+ resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
+
+ resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}
+
+ resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
+
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -5102,6 +5356,9 @@ packages:
resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}
+ resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
+
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
@@ -5125,6 +5382,12 @@ packages:
resolution: {integrity: sha512-631UJ6O00eNGfMiWG78ck80dfBab8X6IVFB51jZK5Icd7XAs60Z5y7QdSd/wGIklnWvRbUNloVzhOKKmutxQ6Q==}
+ resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}
+
+ resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
+
resolution: {integrity: sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw==}
@@ -5238,6 +5501,12 @@ packages:
resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
hasBin: true
+ resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
+
+ resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
+
resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==}
@@ -5305,6 +5574,24 @@ packages:
resolution: {integrity: sha512-od496pShMen7nOy5VmVJCnq8rptd45vh6Nx/r2iPbrba6pa6p+tS2ywuIHRZ/OBvSbQZB0kWvpO9XBNVFXHD3Q==}
+ resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
+
+ resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}
+
+ resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
+
+ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
+
+ resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}
+
+ resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}
+
resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}
engines: {node: '>= 4.0.0'}
@@ -5368,6 +5655,12 @@ packages:
resolution: {integrity: sha512-veufcmxri4e3XSrT0xwfUR7kguIkaxBeosDg00yDWhk49wdwkSUrvvsm7nc75e1PUyvIeZj6nS8VQRYz2/S4Xg==}
engines: {node: '>=0.6.0'}
+ resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}
+
+ resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}
+
resolution: {integrity: sha512-YAXkfvGtuTzwWbDSACdJSg4A4DZiAqckWe90Zapc/sEX3XvHcw1NdurM/6od8J207tSDqNbSsgdCacBgvJKFuA==}
engines: {node: ^18.0.0 || >=20.0.0}
@@ -5546,6 +5839,11 @@ packages:
resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
+
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
@@ -5602,6 +5900,9 @@ packages:
react:
optional: true
+ resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
+
snapshots:
@@ -5949,8 +6250,7 @@ snapshots:
'@cloudflare/[email protected]':
optional: true
- '@cloudflare/[email protected]':
- optional: true
+ '@cloudflare/[email protected]': {}
'@cspotcode/[email protected]':
dependencies:
@@ -7425,6 +7725,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/estree': 1.0.8
+
'@types/[email protected]': {}
@@ -7450,6 +7754,10 @@ snapshots:
dependencies:
'@types/node': 20.19.41
+ '@types/[email protected]':
+ dependencies:
+ '@types/unist': 3.0.3
+
'@types/[email protected]': {}
@@ -7606,6 +7914,8 @@ snapshots:
'@typescript-eslint/types': 8.53.0
eslint-visitor-keys: 4.2.1
+ '@ungap/[email protected]': {}
+
dependencies:
'@babel/core': 7.28.5
@@ -7840,6 +8150,8 @@ snapshots:
postcss: 8.5.6
postcss-value-parser: 4.2.0
+
@@ -7963,6 +8275,8 @@ snapshots:
+
dependencies:
assertion-error: 1.1.0
@@ -7978,6 +8292,8 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
+
@@ -8187,6 +8503,10 @@ snapshots:
+ dependencies:
+ dequal: 2.0.3
+
@@ -8427,6 +8747,8 @@ snapshots:
+
dependencies:
'@babel/core': 7.28.5
@@ -8506,6 +8828,8 @@ snapshots:
+
@@ -8530,6 +8854,8 @@ snapshots:
+
dependencies:
debug: 4.4.3
@@ -8839,6 +9165,30 @@ snapshots:
dependencies:
'@types/hast': 3.0.4
+ dependencies:
+ '@types/estree': 1.0.8
+ '@types/hast': 3.0.4
+ '@types/unist': 3.0.3
+ comma-separated-tokens: 2.0.3
+ devlop: 1.1.0
+ estree-util-is-identifier-name: 3.0.0
+ hast-util-whitespace: 3.0.0
+ mdast-util-mdx-expression: 2.0.1
+ mdast-util-mdx-jsx: 3.2.0
+ mdast-util-mdxjs-esm: 2.0.1
+ property-information: 7.1.0
+ space-separated-tokens: 2.0.2
+ style-to-js: 1.1.21
+ unist-util-position: 5.0.0
+ vfile-message: 4.0.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.4
+
dependencies:
'@types/hast': 3.0.4
@@ -8857,6 +9207,8 @@ snapshots:
+
dependencies:
lru-cache: 6.0.0
@@ -8865,6 +9217,8 @@ snapshots:
dependencies:
whatwg-encoding: 3.1.1
+
@@ -8941,6 +9295,8 @@ snapshots:
+
dependencies:
loose-envify: 1.4.0
@@ -8985,6 +9341,8 @@ snapshots:
+
dependencies:
isobject: 3.0.1
@@ -9019,6 +9377,8 @@ snapshots:
+
@@ -9161,6 +9521,8 @@ snapshots:
+
dependencies:
js-tokens: 4.0.0
@@ -9209,12 +9571,167 @@ snapshots:
pify: 4.0.1
semver: 5.7.2
+
dependencies:
escape-string-regexp: 4.0.0
+ dependencies:
+ '@types/mdast': 4.0.4
+ escape-string-regexp: 5.0.0
+ unist-util-is: 6.0.1
+ unist-util-visit-parents: 6.0.2
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ decode-named-character-reference: 1.2.0
+ devlop: 1.1.0
+ mdast-util-to-string: 4.0.0
+ micromark: 4.0.2
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-decode-string: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ unist-util-stringify-position: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-find-and-replace: 3.0.2
+ micromark-util-character: 2.1.1
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ micromark-util-normalize-identifier: 2.0.1
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ markdown-table: 3.0.4
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-gfm-autolink-literal: 2.0.1
+ mdast-util-gfm-footnote: 2.1.0
+ mdast-util-gfm-strikethrough: 2.0.0
+ mdast-util-gfm-table: 2.0.0
+ mdast-util-gfm-task-list-item: 2.0.0
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ parse-entities: 4.0.2
+ stringify-entities: 4.0.4
+ unist-util-stringify-position: 4.0.0
+ vfile-message: 4.0.3
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/estree-jsx': 1.0.5
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ unist-util-is: 6.0.1
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@ungap/structured-clone': 1.3.3
+ devlop: 1.1.0
+ micromark-util-sanitize-uri: 2.0.1
+ trim-lines: 3.0.1
+ unist-util-position: 5.0.0
+ unist-util-visit: 5.1.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ longest-streak: 3.1.0
+ mdast-util-phrasing: 4.1.0
+ mdast-util-to-string: 4.0.0
+ micromark-util-classify-character: 2.0.1
+ micromark-util-decode-string: 2.0.1
+ unist-util-visit: 5.1.0
+ zwitch: 2.0.4
+
+ dependencies:
+ '@types/mdast': 4.0.4
+
dependencies:
'@types/dom-mediacapture-transform': 0.1.11
@@ -9226,6 +9743,197 @@ snapshots:
+ dependencies:
+ decode-named-character-reference: 1.2.0
+ devlop: 1.1.0
+ micromark-factory-destination: 2.0.1
+ micromark-factory-label: 2.0.1
+ micromark-factory-space: 2.0.1
+ micromark-factory-title: 2.0.1
+ micromark-factory-whitespace: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-chunked: 2.0.1
+ micromark-util-classify-character: 2.0.1
+ micromark-util-html-tag-name: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-subtokenize: 2.1.0
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-core-commonmark: 2.0.3
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-chunked: 2.0.1
+ micromark-util-classify-character: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-extension-gfm-autolink-literal: 2.1.0
+ micromark-extension-gfm-footnote: 2.1.0
+ micromark-extension-gfm-strikethrough: 2.1.0
+ micromark-extension-gfm-table: 2.1.1
+ micromark-extension-gfm-tagfilter: 2.0.0
+ micromark-extension-gfm-task-list-item: 2.1.0
+ micromark-util-combine-extensions: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-chunked: 2.0.1
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ decode-named-character-reference: 1.2.0
+ micromark-util-character: 2.1.1
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-symbol: 2.0.1
+
+
+
+ dependencies:
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ micromark-util-types: 2.0.2
+
+ dependencies:
+ micromark-util-character: 2.1.1
+ micromark-util-encode: 2.0.1
+ micromark-util-symbol: 2.0.1
+
+ dependencies:
+ devlop: 1.1.0
+ micromark-util-chunked: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+
+
+
+ dependencies:
+ '@types/debug': 4.1.13
+ debug: 4.4.3
+ decode-named-character-reference: 1.2.0
+ devlop: 1.1.0
+ micromark-core-commonmark: 2.0.3
+ micromark-factory-space: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-chunked: 2.0.1
+ micromark-util-combine-extensions: 2.0.1
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-encode: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-resolve-all: 2.0.1
+ micromark-util-sanitize-uri: 2.0.1
+ micromark-util-subtokenize: 2.1.0
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
braces: 3.0.3
@@ -9552,19 +10260,21 @@ snapshots:
camelcase-css: 2.0.1
postcss: 8.5.6
dependencies:
lilconfig: 3.1.3
optionalDependencies:
jiti: 1.21.7
postcss: 8.5.6
+ yaml: 2.9.0
dependencies:
lilconfig: 3.1.3
optionalDependencies:
jiti: 2.7.0
postcss: 8.5.6
+ yaml: 2.9.0
dependencies:
@@ -9676,6 +10386,24 @@ snapshots:
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ '@types/react': 19.2.17
+ devlop: 1.1.0
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ mdast-util-to-hast: 13.2.1
+ react: 19.2.7
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ unified: 11.0.5
+ unist-util-visit: 5.1.0
+ vfile: 6.0.3
+ transitivePeerDependencies:
+ - supports-color
+
@@ -9776,6 +10504,40 @@ snapshots:
hastscript: 9.0.1
parse-entities: 4.0.2
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-gfm: 3.1.0
+ micromark-extension-gfm: 3.0.0
+ remark-parse: 11.0.0
+ remark-stringify: 11.0.0
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-from-markdown: 2.0.3
+ micromark-util-types: 2.0.2
+ unified: 11.0.5
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ '@types/hast': 3.0.4
+ '@types/mdast': 4.0.4
+ mdast-util-to-hast: 13.2.1
+ unified: 11.0.5
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/mdast': 4.0.4
+ mdast-util-to-markdown: 2.1.2
+ unified: 11.0.5
+
@@ -10043,6 +10805,11 @@ snapshots:
dependencies:
safe-buffer: 5.2.1
+ dependencies:
+ character-entities-html4: 2.1.0
+ character-entities-legacy: 3.0.0
+
dependencies:
ansi-regex: 5.0.1
@@ -10063,6 +10830,14 @@ snapshots:
dependencies:
js-tokens: 9.0.1
+ dependencies:
+ style-to-object: 1.0.14
+
+ dependencies:
+ inline-style-parser: 0.2.7
+
@@ -10091,11 +10866,11 @@ snapshots:
dependencies:
- tailwindcss: 3.4.18
+ tailwindcss: 3.4.18([email protected])
dependencies:
'@alloc/quick-lru': 5.2.0
arg: 5.0.2
@@ -10114,7 +10889,7 @@ snapshots:
postcss: 8.5.6
postcss-import: 15.1.0([email protected])
postcss-js: 4.1.0([email protected])
- postcss-load-config: 6.0.1([email protected])([email protected])
postcss-nested: 6.2.0([email protected])
postcss-selector-parser: 6.1.2
resolve: 1.22.11
@@ -10206,6 +10981,10 @@ snapshots:
+
+
dependencies:
utf8-byte-length: 1.0.5
@@ -10218,7 +10997,7 @@ snapshots:
dependencies:
bundle-require: 5.1.0([email protected])
cac: 6.7.14
@@ -10229,7 +11008,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1([email protected])([email protected])
resolve-from: 5.0.0
rollup: 4.53.3
source-map: 0.7.6
@@ -10274,6 +11053,39 @@ snapshots:
pathe: 2.0.3
ufo: 1.6.1
+ dependencies:
+ '@types/unist': 3.0.3
+ bail: 2.0.2
+ devlop: 1.1.0
+ extend: 3.0.2
+ is-plain-obj: 4.1.0
+ trough: 2.2.0
+ vfile: 6.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+ unist-util-visit-parents: 6.0.2
+
@@ -10327,6 +11139,16 @@ snapshots:
extsprintf: 1.4.1
optional: true
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-stringify-position: 4.0.0
+
+ dependencies:
+ '@types/unist': 3.0.3
+ vfile-message: 4.0.3
+
dependencies:
cac: 6.7.14
@@ -10485,6 +11307,8 @@ snapshots:
+
@@ -10535,3 +11359,5 @@ snapshots:
'@types/react': 19.2.17
immer: 11.0.1
react: 19.2.7
+