Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): export UX, .openscreen project files, exact crop ratios and a redesigned ruler
Etienne Lescotc2b68a018c14
diff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex 2ba9bd368..6baf50838 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -30,7 +30,7 @@ describe("DocumentService", () => {expect(doc.project.id).toMatch(/^proj_/);expect(doc.assets).toEqual([]);- const filePath = path.join(tempDir, `${doc.project.id}.axcut`);+ const filePath = path.join(tempDir, `${doc.project.id}.openscreen`);const raw = await fs.readFile(filePath, "utf8");expect(JSON.parse(raw)).toMatchObject({schemaVersion: 4,@@ -75,10 +75,29 @@ describe("DocumentService", () => {it("skips files that fail to parse rather than throwing", async () => {const a = await service.createProject("OK");- await fs.writeFile(path.join(tempDir, "garbage.axcut"), "not json", "utf8");+ await fs.writeFile(path.join(tempDir, "garbage.openscreen"), "not json", "utf8");const summaries = await service.listProjects();expect(summaries.map((s) => s.id)).toEqual([a.project.id]);});++ it("migrates a legacy .axcut project to .openscreen on access", async () => {+ // A project written by an older build: same document bytes, `.axcut` name.+ const created = await service.createProject("Legacy");+ const openscreenPath = path.join(tempDir, `${created.project.id}.openscreen`);+ const axcutPath = path.join(tempDir, `${created.project.id}.axcut`);+ await fs.rename(openscreenPath, axcutPath);++ // A fresh service (new process) must still surface and load it, renaming+ // the file across in the process.+ const fresh = new DocumentService(tempDir);+ const summaries = await fresh.listProjects();+ expect(summaries.map((s) => s.id)).toEqual([created.project.id]);+ await expect(fresh.getProject(created.project.id)).resolves.toMatchObject({+ project: { id: created.project.id, title: "Legacy" },+ });+ await expect(fs.access(axcutPath)).rejects.toBeTruthy();+ await expect(fs.access(openscreenPath)).resolves.toBeUndefined();+ });});describe("addAsset", () => {@@ -179,7 +198,7 @@ describe("DocumentService", () => {});describe("deleteProject", () => {- it("removes the .axcut file", async () => {+ it("removes the project file", async () => {const doc = await service.createProject("Bye");await service.deleteProject(doc.project.id);await expect(service.getProject(doc.project.id)).rejects.toBeInstanceOf(diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.tsindex ac008a51f..fc40d9b9a 100644--- a/electron/ai-edition/document-service.ts+++ b/electron/ai-edition/document-service.ts@@ -1,5 +1,8 @@// DocumentService — main-process owner of v3 AxcutDocument projects.-// Persists one .axcut JSON per project under userData/projects/. Slim port of+// Persists one .openscreen JSON per project under userData/projects/ (the file+// carries its own `schemaVersion`, so migration keys off the content, not the+// extension). Older builds wrote these same documents as `.axcut`; those are+// renamed to `.openscreen` on first access. Slim port of// axcut's apps/server/src/services/document-service.ts (no separate paths.ts —// uses app.getPath("userData") directly; no Python probe_media — assets carry// only path metadata, duration is filled in by the renderer).@@ -17,7 +20,10 @@ import {documentSchema,} from "../../src/lib/ai-edition/schema";-const PROJECT_FILE_EXTENSION = ".axcut";+const PROJECT_FILE_EXTENSION = ".openscreen";+// Older builds stored these same v3/v4 AxcutDocuments under `.axcut`. We read+// them for back-compat and rename them to PROJECT_FILE_EXTENSION on access.+const LEGACY_PROJECT_FILE_EXTENSION = ".axcut";export interface ProjectSummary {id: string;@@ -74,6 +80,7 @@ function safeProjectId(raw: string): string {export class DocumentService {private readonly projectsRoot: string;+ private legacyMigrationDone = false;constructor(projectsRoot: string) {this.projectsRoot = projectsRoot;@@ -81,6 +88,42 @@ export class DocumentService {async ensureProjectsDir(): Promise<void> {await fs.mkdir(this.projectsRoot, { recursive: true });+ await this.migrateLegacyExtensions();+ }++ // One-time-per-process pass renaming any legacy `.axcut` project files to+ // `.openscreen`. The document bytes are identical (same schemaVersion), so+ // this is a pure rename — no content migration involved.+ private async migrateLegacyExtensions(): Promise<void> {+ if (this.legacyMigrationDone) return;+ this.legacyMigrationDone = true;+ let entries: string[];+ try {+ entries = await fs.readdir(this.projectsRoot);+ } catch {+ return;+ }+ await Promise.all(+ entries+ .filter((name) => name.endsWith(LEGACY_PROJECT_FILE_EXTENSION))+ .map(async (name) => {+ const from = path.join(this.projectsRoot, name);+ const base = name.slice(0, -LEGACY_PROJECT_FILE_EXTENSION.length);+ const to = path.join(this.projectsRoot, `${base}${PROJECT_FILE_EXTENSION}`);+ try {+ // If a `.openscreen` already exists for this id it's authoritative;+ // drop the stale `.axcut`. Otherwise rename the legacy file across.+ await fs.access(to);+ await fs.unlink(from);+ } catch {+ await fs+ .rename(from, to)+ .catch((err) =>+ console.warn(`[ai-edition] failed to migrate ${from} -> ${to}:`, err),+ );+ }+ }),+ );}private fileFor(projectId: string): string {@@ -88,12 +131,18 @@ export class DocumentService {return path.join(this.projectsRoot, `${safe}${PROJECT_FILE_EXTENSION}`);}+ private legacyFileFor(projectId: string): string {+ const safe = safeProjectId(projectId);+ return path.join(this.projectsRoot, `${safe}${LEGACY_PROJECT_FILE_EXTENSION}`);+ }+async listProjects(): Promise<ProjectSummary[]> {await this.ensureProjectsDir();const entries = await fs.readdir(this.projectsRoot);- const axcutFiles = entries.filter((name) => name.endsWith(PROJECT_FILE_EXTENSION));+ // ensureProjectsDir (above) already migrated any legacy `.axcut` files.+ const projectFiles = entries.filter((name) => name.endsWith(PROJECT_FILE_EXTENSION));const summaries: ProjectSummary[] = [];- for (const name of axcutFiles) {+ for (const name of projectFiles) {const filePath = path.join(this.projectsRoot, name);try {const raw = await fs.readFile(filePath, "utf8");@@ -115,19 +164,31 @@ export class DocumentService {}async getProject(projectId: string): Promise<AxcutDocument> {- const filePath = this.fileFor(projectId);+ // Prefer the canonical `.openscreen` file, falling back to a not-yet-migrated+ // legacy `.axcut` so a project opened before its migration pass still loads.+ let raw: string;try {- const raw = await fs.readFile(filePath, "utf8");- return documentSchema.parse(JSON.parse(raw));+ raw = await fs.readFile(this.fileFor(projectId), "utf8");} catch (error) {- if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {- throw new DocumentNotFoundError(projectId);+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {+ throw new ProjectFileError(+ `Failed to read project ${projectId}: ${error instanceof Error ? error.message : String(error)}`,+ projectId,+ );+ }+ try {+ raw = await fs.readFile(this.legacyFileFor(projectId), "utf8");+ } catch (legacyError) {+ if ((legacyError as NodeJS.ErrnoException)?.code === "ENOENT") {+ throw new DocumentNotFoundError(projectId);+ }+ throw new ProjectFileError(+ `Failed to read project ${projectId}: ${legacyError instanceof Error ? legacyError.message : String(legacyError)}`,+ projectId,+ );}- throw new ProjectFileError(- `Failed to read project ${projectId}: ${error instanceof Error ? error.message : String(error)}`,- projectId,- );}+ return documentSchema.parse(JSON.parse(raw));}async createProject(title: string): Promise<AxcutDocument> {@@ -152,12 +213,14 @@ export class DocumentService {}async deleteProject(projectId: string): Promise<void> {- const filePath = this.fileFor(projectId);- try {- await fs.unlink(filePath);- } catch (error) {- if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {- throw error;+ // Remove the canonical file and any lingering legacy `.axcut` for this id.+ for (const filePath of [this.fileFor(projectId), this.legacyFileFor(projectId)]) {+ try {+ await fs.unlink(filePath);+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") {+ throw error;+ }}}}@@ -233,5 +296,8 @@ export class DocumentService {await this.ensureProjectsDir();const filePath = this.fileFor(doc.project.id);await fs.writeFile(filePath, JSON.stringify(doc, null, 2), "utf8");+ // A save supersedes any legacy `.axcut` for this id (ensureProjectsDir+ // usually renamed it already; this is a belt-and-braces cleanup).+ await fs.unlink(this.legacyFileFor(doc.project.id)).catch(() => undefined);}}diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex c4873896b..3bda7bffc 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -3030,9 +3030,19 @@ export function registerIpcHandlers(async function loadProjectFile(projectFolder?: string): Promise<ProjectFileResult> {try {- // Prefer the user's last opened-project folder if it still exists, else- // RECORDINGS_DIR. Validate here because the renderer can't stat the filesystem.+ // Default to the projects directory, where the editor actually stores+ // openable project files (one `.openscreen` per project). Prefer the user's+ // last opened-project folder if given and still valid; only fall back to+ // RECORDINGS_DIR if the projects dir doesn't exist yet (fresh install).+ // Validate here because the renderer can't stat the filesystem.+ const projectsDir = path.join(app.getPath("userData"), "projects");let defaultDir = RECORDINGS_DIR;+ try {+ const stats = await fs.stat(projectsDir);+ if (stats.isDirectory()) defaultDir = projectsDir;+ } catch {+ // projects dir not created yet — keep RECORDINGS_DIR fallback.+ }if (projectFolder) {try {const stats = await fs.stat(projectFolder);@@ -3043,7 +3053,7 @@ export function registerIpcHandlers(// Stat can fail if the folder was moved/deleted (expected) or on a// permission error (worth surfacing). We fall back either way, but log it.console.warn(- `Could not access remembered project folder "${projectFolder}", falling back to RECORDINGS_DIR:`,+ `Could not access remembered project folder "${projectFolder}", falling back to default:`,err,);}@@ -3055,7 +3065,9 @@ export function registerIpcHandlers(filters: [{name: mainT("dialogs", "fileDialogs.openscreenProject"),- extensions: [PROJECT_FILE_EXTENSION],+ // All projects are `.openscreen`; `.axcut` is kept only so files+ // written by older builds (pre-migration) still show up.+ extensions: [PROJECT_FILE_EXTENSION, "axcut"],},{ name: "JSON", extensions: ["json"] },{ name: mainT("dialogs", "fileDialogs.allFiles"), extensions: ["*"] },diff --git a/src/components/ai-edition/EditorEmptyState.tsx b/src/components/ai-edition/EditorEmptyState.tsxindex 306e62d49..f7e16a946 100644--- a/src/components/ai-edition/EditorEmptyState.tsx+++ b/src/components/ai-edition/EditorEmptyState.tsx@@ -18,6 +18,7 @@ import { useCallback, useRef, useState } from "react";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { useScopedT } from "@/contexts/I18nContext";import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";+import { documentSchema } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { nativeBridgeClient } from "@/native";import styles from "./NewEditorShell.module.css";@@ -71,23 +72,37 @@ export function EditorEmptyState({}}, [addAsset, ensureProject]);+ // A loaded project JSON is either a current AxcutDocument (has its own+ // `schemaVersion`) or a legacy EditorProjectData that must be migrated.+ // Discriminate on the version field so a current document is never fed to+ // the legacy migrator (which reads `.media`/`.editor` and would yield an+ // empty doc). Returns true once the project is saved and loaded.+ const openLoadedProject = useCallback(+ async (raw: unknown): Promise<boolean> => {+ const isAxcutDocument =+ typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;+ const doc = isAxcutDocument+ ? documentSchema.parse(raw)+ : migrateProjectDataToAxcutDocument(raw as never);+ const saved = await nativeBridgeClient.aiEdition.save(doc);+ if (!saved.success || !saved.document) return false;+ await loadProject(doc.project.id);+ return true;+ },+ [loadProject],+ );+const handleLoadProject = useCallback(async () => {try {const result = await window.electronAPI?.loadProjectFile?.();if (!result?.success || !result.project) return;- // ponytail: legacy v2 projects round-trip through the migrator.- // The bridge expects a v3 AxcutDocument.- const migrated = migrateProjectDataToAxcutDocument(result.project as never);- const saved = await nativeBridgeClient.aiEdition.save(migrated);- if (saved.success && saved.document) {- await loadProject(migrated.project.id);- } else {+ if (!(await openLoadedProject(result.project))) {setDropError("load-failed");}} catch {setDropError("load-failed");}- }, [loadProject]);+ }, [openLoadedProject]);const handleDragOver = useCallback((e: React.DragEvent) => {e.preventDefault();@@ -130,18 +145,14 @@ export function EditorEmptyState({return;}try {- const migrated = migrateProjectDataToAxcutDocument(result.project as never);- const saved = await nativeBridgeClient.aiEdition.save(migrated);- if (saved.success && saved.document) {- await loadProject(migrated.project.id);- } else {+ if (!(await openLoadedProject(result.project))) {setDropError("load-failed");}} catch {setDropError("load-failed");}},- [loadProject],+ [openLoadedProject],);return (diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsxindex c46645a4e..b62398f6d 100644--- a/src/components/ai-edition/ExportDialog.tsx+++ b/src/components/ai-edition/ExportDialog.tsx@@ -9,7 +9,7 @@// the new shell's modal style.import { Download, FileVideo, Loader2 } from "lucide-react";-import { useEffect, useRef, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { useScopedT } from "@/contexts/I18nContext";import {@@ -33,18 +33,21 @@ import styles from "./NewEditorShell.module.css";type Phase = "idle" | "configuring" | "rendering" | "writing" | "done" | "error";+// Target short side (px) for the two fixed quality tiers -- mirrors the legacy+// editor's SettingsPanel (MP4_EXPORT_SHORT_SIDES), used only to decide whether+// picking that tier would upscale past the source's actual resolution.+const MEDIUM_SHORT_SIDE = 720;+const HIGH_SHORT_SIDE = 1080;+const QUALITY_OPTIONS: Array<{value: ExportQuality;labelKey: string;- hintKey: string;+ /** Target short side for the upscale check; undefined for "source" (no fixed target). */+ targetShortSide?: number;}> = [- { value: "medium", labelKey: "exportQuality.low", hintKey: "exportDialog.qualitySmallerFile" },- { value: "good", labelKey: "exportQuality.medium", hintKey: "exportDialog.qualityRecommended" },- {- value: "source",- labelKey: "exportQuality.high",- hintKey: "exportDialog.qualityMatchRecording",- },+ { value: "medium", labelKey: "exportQuality.low", targetShortSide: MEDIUM_SHORT_SIDE },+ { value: "good", labelKey: "exportQuality.medium", targetShortSide: HIGH_SHORT_SIDE },+ { value: "source", labelKey: "exportQuality.high" },];interface ExportDialogProps {@@ -69,6 +72,21 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {const [savedPath, setSavedPath] = useState<string | null>(null);const cancelRef = useRef<{ cancel: () => void } | null>(null);+ const primaryAsset = useMemo(+ () =>+ document+ ? (document.assets.find((a) => a.id === document.project.primaryAssetId) ??+ document.assets[0])+ : null,+ [document],+ );+ // 0 means "not probed yet" (assetVideoSchema defaults) -- treat as unknown+ // rather than a real 0x0 source, else every tier would wrongly show Upscale.+ const sourceShortSide =+ primaryAsset?.video && primaryAsset.video.width > 0 && primaryAsset.video.height > 0+ ? Math.min(primaryAsset.video.width, primaryAsset.video.height)+ : null;+useEffect(() => {if (!open) {setPhase("idle");@@ -86,8 +104,7 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {const handleStart = async () => {if (!document) return;- const asset =- document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];+ const asset = primaryAsset;if (!asset) {setError(t("exportDialog.addVideoBeforeExporting"));setPhase("error");@@ -239,9 +256,18 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {}}><span style={{ color: "var(--fg)", fontWeight: 600 }}>{ts(q.labelKey)}</span>- <span style={{ font: "500 11px var(--font-body)", color: "var(--muted)" }}>- {t(q.hintKey)}- </span>+ {q.targetShortSide === undefined ? (+ <span style={{ font: "500 11px var(--font-body)", color: "var(--muted)" }}>+ {t("exportDialog.qualityMatchRecording")}+ </span>+ ) : (+ sourceShortSide !== null &&+ sourceShortSide < q.targetShortSide && (+ <span style={{ font: "500 11px var(--font-body)", color: "var(--warn)" }}>+ {t("exportDialog.qualityUpscaleWarning")}+ </span>+ )+ )}</button>))}</div>@@ -475,7 +501,11 @@ function FormatToggle({border: `1px solid ${active ? "var(--accent)" : "var(--border)"}`,borderRadius: 10,background: active ? "var(--accent-wash)" : "var(--surface)",- color: active ? "var(--accent-on)" : "var(--fg-2)",+ // Selection is conveyed by border + wash background (like the quality+ // cards below), not by swapping text color -- `--accent-on` is meant+ // for text on a SOLID accent fill, and paired with the near-transparent+ // `--accent-wash` it read as near-invisible dark-on-dark text.+ color: "var(--fg)",cursor: "pointer",font: "600 14px/1 var(--font-body)",}}diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsxindex e35c39ed6..0f96e832e 100644--- a/src/components/ai-edition/LeftPanel.tsx+++ b/src/components/ai-edition/LeftPanel.tsx@@ -663,6 +663,14 @@ function ChatStripPanel() {Array<{ id: string; title: string; messageCount: number; createdAt: string }>>([]);const [activeSessionId, setActiveSessionId] = useState<string | null>(null);+ // Mirror in a ref so refreshSessions can read the current selection without+ // listing activeSessionId in its deps — otherwise refreshSessions is recreated+ // on every selection change, which re-runs the project effect below (with+ // preferFirst=true) and forces the selection back to list[0]. That feedback+ // loop is what made "new conversation" jump to the oldest chat instead of the+ // freshly-created empty one.+ const activeSessionIdRef = useRef<string | null>(activeSessionId);+ activeSessionIdRef.current = activeSessionId;const scrollRef = useRef<HTMLDivElement | null>(null);const [reasoningOpen, setReasoningOpen] = useState(false);const reasoningButtonRef = useRef<HTMLButtonElement | null>(null);@@ -690,25 +698,22 @@ function ChatStripPanel() {}}, []);- const refreshSessions = useCallback(- async (pid: string, preferFirst = false) => {- try {- const list = await nativeBridgeClient.aiEdition.chatListSessions(pid);- setSessions(list);- if (list.length === 0) {- setActiveSessionId(null);- setMessages([]);- return;- }- if (preferFirst || !list.some((s) => s.id === activeSessionId)) {- setActiveSessionId(list[0].id);- }- } catch {- // ponytail: silent — shim mode or missing project+ const refreshSessions = useCallback(async (pid: string, preferFirst = false) => {+ try {+ const list = await nativeBridgeClient.aiEdition.chatListSessions(pid);+ setSessions(list);+ if (list.length === 0) {+ setActiveSessionId(null);+ setMessages([]);+ return;}- },- [activeSessionId],- );+ if (preferFirst || !list.some((s) => s.id === activeSessionIdRef.current)) {+ setActiveSessionId(list[0].id);+ }+ } catch {+ // ponytail: silent — shim mode or missing project+ }+ }, []);useEffect(() => {void refreshLlm();diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsxindex 735dfd60d..28d966f5a 100644--- a/src/components/ai-edition/Modals.tsx+++ b/src/components/ai-edition/Modals.tsx@@ -182,7 +182,21 @@ export function OpenProjectModal({}}/></div>- <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 12 }}>+ <div+ style={{+ display: "flex",+ flexDirection: "column",+ gap: 2,+ marginBottom: 12,+ // Cap the list so the footer's "Browse files" button stays visible+ // instead of being pushed below the fold when there are many projects;+ // the list scrolls internally.+ maxHeight: "48vh",+ overflowY: "auto",+ scrollbarWidth: "thin",+ scrollbarColor: "var(--border-hi) transparent",+ }}+ >{filtered.length === 0 ? (<p style={{ color: "var(--muted)", fontSize: 12, padding: 16, textAlign: "center" }}>{t("openProjectDialog.noMatches", { query })}@@ -526,6 +540,20 @@ function detectRatio(r: CropRegion, videoAspectRatio: number): string {return "free";}+// Largest crop rectangle (percentages of the frame) whose fraction-space ratio+// is `fr` (= width/height, already converted from the visual ratio through the+// source's pixel aspect ratio), centered on whichever axis has slack. One+// dimension fills the frame; the other is derived so the result never overflows.+function centeredFitPct(fr: number): { x: number; y: number; w: number; h: number } {+ if (!(fr > 0)) return { x: 0, y: 0, w: 100, h: 100 };+ if (fr >= 1) {+ const h = 100 / fr;+ return { x: 0, y: (100 - h) / 2, w: 100, h };+ }+ const w = 100 * fr;+ return { x: (100 - w) / 2, y: 0, w, h: 100 };+}+const MIN_PCT = 4;const clampPct = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));@@ -719,12 +747,62 @@ export function EditClipModal({setCropTouched(true);setCropRatio(next);const candidate = CROP_RATIOS.find((c) => c.value === next);- if (candidate?.ratio && cropWPct > 0) {- // Convert the preset's visual ratio into the fraction-space ratio- // this crop's width/height percentages actually live in.- const fractionRatio = candidate.ratio / videoAspectRatio;- const newH = Math.round(cropWPct / fractionRatio);- setCropHPct(clampPct(newH, MIN_PCT, 100));+ // "Free" keeps whatever the user currently has; a preset snaps the crop to+ // the largest centered rectangle of that exact ratio (and, via the locked+ // field/handle logic below, keeps every later edit at that ratio).+ if (!candidate?.ratio) return;+ const fit = centeredFitPct(candidate.ratio / videoAspectRatio);+ setCropXPct(Math.round(fit.x));+ setCropYPct(Math.round(fit.y));+ setCropWPct(Math.round(fit.w));+ setCropHPct(Math.round(fit.h));+ };++ // Fraction-space width/height ratio the crop is locked to while a preset is+ // active (null for "Free"). Numeric fields and resize handles both honor it so+ // the user can move/scale the crop but never change its aspect ratio.+ const activePresetRatio = CROP_RATIOS.find((c) => c.value === cropRatio)?.ratio ?? null;+ const lockedFractionRatio = activePresetRatio ? activePresetRatio / videoAspectRatio : null;++ // Ratio-aware numeric field setters. With a preset active, changing one side+ // derives the other (and clamps both to the frame); "Free" edits each axis+ // independently. All keep the rectangle inside the frame.+ const applyCropX = (v: number) => {+ setCropTouched(true);+ setCropXPct(Math.round(clampPct(v, 0, 100 - cropWPct)));+ };+ const applyCropY = (v: number) => {+ setCropTouched(true);+ setCropYPct(Math.round(clampPct(v, 0, 100 - cropHPct)));+ };+ const applyCropW = (v: number) => {+ setCropTouched(true);+ if (lockedFractionRatio) {+ let w = clampPct(v, MIN_PCT, 100 - cropXPct);+ let h = w / lockedFractionRatio;+ if (h > 100 - cropYPct) {+ h = 100 - cropYPct;+ w = h * lockedFractionRatio;+ }+ setCropWPct(Math.round(w));+ setCropHPct(Math.round(h));+ } else {+ setCropWPct(Math.round(clampPct(v, MIN_PCT, 100 - cropXPct)));+ }+ };+ const applyCropH = (v: number) => {+ setCropTouched(true);+ if (lockedFractionRatio) {+ let h = clampPct(v, MIN_PCT, 100 - cropYPct);+ let w = h * lockedFractionRatio;+ if (w > 100 - cropXPct) {+ w = 100 - cropXPct;+ h = w / lockedFractionRatio;+ }+ setCropWPct(Math.round(w));+ setCropHPct(Math.round(h));+ } else {+ setCropHPct(Math.round(clampPct(v, MIN_PCT, 100 - cropYPct)));}};@@ -764,10 +842,8 @@ export function EditClipModal({const startX = e.clientX;const startY = e.clientY;const start = { x: cropXPct, y: cropYPct, w: cropWPct, h: cropHPct };- const activeRatio = CROP_RATIOS.find((c) => c.value === cropRatio)?.ratio ?? null;- // Same fraction-space conversion as handleCropRatioChange — locking to- // the raw visual ratio here would fight the source's own aspect ratio.- const activeFractionRatio = activeRatio ? activeRatio / videoAspectRatio : null;+ // Fraction-space ratio the resize is locked to (null for "Free").+ const fr = lockedFractionRatio;setCropTouched(true);const move = (ev: PointerEvent) => {const dxPct = ((ev.clientX - startX) / r.width) * 100;@@ -789,9 +865,31 @@ export function EditClipModal({if (edges.bottom) {h = clampPct(start.h + dyPct, MIN_PCT, 100 - start.y);}- if (activeFractionRatio) {- if (edges.left || edges.right) h = clampPct(w / activeFractionRatio, MIN_PCT, 100 - y);- else if (edges.top || edges.bottom) w = clampPct(h * activeFractionRatio, MIN_PCT, 100 - x);+ if (fr) {+ // Locked ratio: the crop stays a fixed shape anchored at the corner the+ // user isn't dragging. The dragged size is capped at the largest rect of+ // this ratio that fits from that anchor — so it's simply sized to fit,+ // never placed out of frame. (A crop can't leave the frame, so there is+ // no out-of-bounds state to correct after the fact.)+ const fixedLeft = !edges.left; // the x-edge that stays put+ const fixedTop = !edges.top; // the y-edge that stays put+ const anchorX = fixedLeft ? start.x : start.x + start.w;+ const anchorY = fixedTop ? start.y : start.y + start.h;+ const roomW = fixedLeft ? 100 - anchorX : anchorX;+ const roomH = fixedTop ? 100 - anchorY : anchorY;+ // Which axis the pointer drives; the other is derived from the ratio.+ const drivenByHeight = (edges.top || edges.bottom) && !(edges.left || edges.right);+ let nextW = Math.min(drivenByHeight ? h * fr : w, roomW, roomH * fr);+ nextW = Math.max(MIN_PCT, nextW);+ let nextH = nextW / fr;+ if (nextH < MIN_PCT) {+ nextH = MIN_PCT;+ nextW = nextH * fr;+ }+ w = nextW;+ h = nextH;+ x = fixedLeft ? anchorX : anchorX - w;+ y = fixedTop ? anchorY : anchorY - h;}setCropXPct(Math.round(x));setCropYPct(Math.round(y));@@ -1069,38 +1167,10 @@ export function EditClipModal({alignItems: "end",}}>- <CropField- label={t("cropDialog.fieldX")}- value={cropXPct}- onChange={(v) => {- setCropTouched(true);- setCropXPct(v);- }}- />- <CropField- label={t("cropDialog.fieldY")}- value={cropYPct}- onChange={(v) => {- setCropTouched(true);- setCropYPct(v);- }}- />- <CropField- label={t("cropDialog.fieldW")}- value={cropWPct}- onChange={(v) => {- setCropTouched(true);- setCropWPct(v);- }}- />- <CropField- label={t("cropDialog.fieldH")}- value={cropHPct}- onChange={(v) => {- setCropTouched(true);- setCropHPct(v);- }}- />+ <CropField label={t("cropDialog.fieldX")} value={cropXPct} onChange={applyCropX} />+ <CropField label={t("cropDialog.fieldY")} value={cropYPct} onChange={applyCropY} />+ <CropField label={t("cropDialog.fieldW")} value={cropWPct} onChange={applyCropW} />+ <CropField label={t("cropDialog.fieldH")} value={cropHPct} onChange={applyCropH} /><div style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 110 }}><labelstyle={{diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsxindex 0c2c6e9d5..3e6aec464 100644--- a/src/components/ai-edition/NewEditorShell.tsx+++ b/src/components/ai-edition/NewEditorShell.tsx@@ -6,7 +6,7 @@ import { useShortcuts } from "@/contexts/ShortcutsContext";import { migrateProjectDataToAxcutDocument } from "@/lib/ai-edition/document/migrate";import { replaceTimeline as replaceTimelineOp } from "@/lib/ai-edition/document/timeline";import { transcribeAsset } from "@/lib/ai-edition/document/transcribe";-import type { AxcutClip } from "@/lib/ai-edition/schema";+import { type AxcutClip, documentSchema } from "@/lib/ai-edition/schema";import { useProjectStore } from "@/lib/ai-edition/store/projectStore";import { useUndoRedoShortcuts } from "@/lib/ai-edition/store/undo";import { PLACEHOLDER_DURATION_SEC, useTimeline } from "@/lib/ai-edition/store/useTimeline";@@ -498,18 +498,27 @@ export function NewEditorShell() {[setTranscript],);- const handleLoadLegacyProject = useCallback(async () => {+ const handleBrowseProject = useCallback(async () => {try {const result = await window.electronAPI?.loadProjectFile();if (!result?.success || !result.project) return;- const legacy = result.project as EditorProjectData;- const migrated = migrateProjectDataToAxcutDocument(legacy);- const saved = await nativeBridgeClient.aiEdition.save(migrated);+ const raw = result.project as unknown;+ // A current project file already carries its own `schemaVersion` (v3/v4+ // AxcutDocument); an older legacy export is EditorProjectData and must be+ // migrated. Discriminate on the version field so a current document is+ // never fed to the legacy migrator (which reads `.media`/`.editor` and+ // would yield an empty doc).+ const isAxcutDocument =+ typeof raw === "object" && raw !== null && "schemaVersion" in raw && "timeline" in raw;+ const doc = isAxcutDocument+ ? documentSchema.parse(raw) // validates + upgrades v3 → v4+ : migrateProjectDataToAxcutDocument(raw as EditorProjectData);+ const saved = await nativeBridgeClient.aiEdition.save(doc);if (saved.success && saved.document) {- await loadProject(migrated.project.id);- toast.success("Legacy project migrated and loaded");+ await loadProject(doc.project.id);+ toast.success(isAxcutDocument ? "Project opened" : "Legacy project migrated and loaded");} else {- toast.error(saved.error ?? "Failed to save migrated project");+ toast.error(saved.error ?? "Failed to open project");}} catch (err) {toast.error("Could not load project", {@@ -1253,7 +1262,7 @@ export function NewEditorShell() {projects={projectSummaries}activeProjectId={projectId}onSelect={handleSelectProject}- onBrowse={handleLoadLegacyProject}+ onBrowse={handleBrowseProject}/><NewProjectModalopen={newProjectOpen}diff --git a/src/components/ai-edition/v4/EditorShellV4.module.css b/src/components/ai-edition/v4/EditorShellV4.module.cssindex db71f951d..3955b2777 100644--- a/src/components/ai-edition/v4/EditorShellV4.module.css+++ b/src/components/ai-edition/v4/EditorShellV4.module.css@@ -5,6 +5,11 @@.app {display: grid;+ /* Single column pinned to the window width. Without an explicit column the+ implicit `auto` track is sized to its widest row's content, so any wide+ child (e.g. a long clip's timeline) would stretch the grid past the window+ and push the top bar's right-side buttons off-screen. minmax(0,1fr) caps it. */+ grid-template-columns: minmax(0, 1fr);height: 100vh;width: 100%;min-width: 0;@@ -983,35 +988,98 @@font-weight: 600;color: var(--fg-2);}-.tlTracks {+/* Ruler + tracks live in one relative wrapper (between the toolbar and the zoom+ bar) so a single playhead overlay can span both. */+.tlBody {position: relative;flex: 1;min-height: 0;+ display: flex;+ flex-direction: column;+}+/* Fixed ruler header — the ruler ticks sit here, pinned right under the toolbar+ so they move with the header (not with the scrolling tracks) when the panel is+ resized. overflow:hidden clips the zoom-transformed canvas horizontally. Its+ canvas is exactly as wide as .tlTracks' because the tracks scrollbar is hidden+ (takes no width), so ticks stay aligned with the clips + playhead. */+.tlRulerRow {+ position: relative;+ flex-shrink: 0;padding: 8px 20px 0;overflow: hidden;cursor: text;}+.tlTracks {+ position: relative;+ flex: 1;+ min-height: 0;+ /* Top padding lives on .tlRulerRow now; keep the sides + bottom gap here. */+ padding: 0 20px 8px;+ /* Horizontal zoom/pan is done by transforming .tlCanvas, so x stays clipped;+ y scrolls when the panel is too short to show every lane + the main track. */+ overflow-x: hidden;+ overflow-y: auto;+ /* Hide the scrollbar so it NEVER consumes layout width. A space-taking+ scrollbar narrowed the content box only while visible, shifting the clips+ (and ruler/playhead) horizontally when it appeared and desyncing clicks from+ times. With it hidden, all three canvases stay full width and identical;+ scrolling still works via the wheel (see the wheel handler). */+ scrollbar-width: none;+ /* Bottom-anchor via column-reverse (the single child is .tlCanvas, so its+ internal lane→clip order is untouched): the main clip track sits at the+ bottom edge and stays visible as the panel shrinks, while the edit lanes+ above overflow the top and REMAIN reachable by scrolling up. `flex-end`+ would bottom-anchor too, but content it pushes past the top edge isn't+ scrollable — which is why the lanes couldn't be reached before. */+ display: flex;+ flex-direction: column-reverse;+ cursor: text;+}+.tlTracks::-webkit-scrollbar {+ display: none;+}.tlCanvas {position: relative;min-width: 100%;+ /* Keep natural height so .tlTracks (not the canvas) is what scrolls; without+ this the flex column would shrink the canvas and clip its own content. */+ flex-shrink: 0;will-change: transform, width;}+/* Playhead overlay: absolutely covers the ruler + tracks, fixed vertically (a+ cursor, so it doesn't scroll with the lanes). Same horizontal padding as the+ canvases (and the tracks scrollbar is hidden, so equal width) → its transformed+ line/head aligns exactly with ticks/clips. pointer-events pass through (except+ the diamond) so scrubbing still works. */+.tlPlayheadLayer {+ position: absolute;+ inset: 0;+ padding: 8px 20px;+ overflow: hidden;+ pointer-events: none;+ z-index: 6;+}+.tlPlayheadLayer .tlCanvas {+ height: 100%;+}+/* One continuous line from the ruler down through the clips, stopping just above+ the zoom/nav bar, with the draggable diamond head at the top (in the ruler). */.tlPlayhead {position: absolute;- top: 2px;- bottom: 66px;+ top: 0;+ bottom: 0;width: 2px;background: var(--accent);border-radius: 1px;- z-index: 6;box-shadow: 0 0 10px var(--accent-soft);pointer-events: none;}.tlPlayheadDiamond {position: absolute;- top: -5px;+ /* Caps the very top of the playhead line (the line runs down from here). */+ top: 0;left: 50%;- transform: translateX(-50%) rotate(45deg);+ transform: translate(-50%, -50%) rotate(45deg);width: 9px;height: 9px;background: var(--accent);@@ -1028,7 +1096,7 @@.tlRuler span {font-family: var(--font-mono);font-size: 10px;- color: var(--muted);+ color: var(--meta);}.tlLane {position: relative;diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex c82063401..bb67a5b40 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -61,6 +61,17 @@ function fmt(sec: number): string {return `${m}:${s.padStart(4, "0")}`;}+// Ruler tick labels sit on whole-second "nice" steps, so tenths are always+// ".0" noise — show clean M:SS (H:MM:SS past an hour) instead.+function fmtTick(sec: number): string {+ if (!Number.isFinite(sec) || sec < 0) sec = 0;+ const total = Math.round(sec);+ const h = Math.floor(total / 3600);+ const m = Math.floor((total % 3600) / 60);+ const ss = String(total % 60).padStart(2, "0");+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;+}+// Real per-clip audio waveform, sliced from the underlying asset's decoded// peaks (useAudioPeaks) down to this clip's [sourceStartSec, sourceEndSec]// range. A separate component (not inline in the clips .map) so each clip@@ -88,8 +99,10 @@ function ClipWaveform({const endBlock = Math.min(totalBlocks, Math.ceil(sourceEndSec * blocksPerSec));const rangeBlocks = Math.max(1, endBlock - startBlock);// One bar per ~120ms of clip duration — dense enough to read as a- // continuous waveform rather than a handful of scattered ticks.- const barCount = Math.max(20, Math.round((sourceEndSec - sourceStartSec) * 8));+ // continuous waveform — but capped so a long recording doesn't spawn+ // thousands of DOM nodes in a single clip (a clip is at most ~the timeline+ // width on screen, so beyond a few hundred bars they're sub-pixel anyway).+ const barCount = Math.min(400, Math.max(20, Math.round((sourceEndSec - sourceStartSec) * 8)));const result: number[] = [];for (let i = 0; i < barCount; i++) {const blockStart = startBlock + Math.floor((i / barCount) * rangeBlocks);@@ -169,6 +182,11 @@ export function V4Timeline({}) {const t = useScopedT("timeline");const tracksRef = useRef<HTMLDivElement | null>(null);+ // The transformed canvas is the true timeline coordinate frame — clips, pills+ // and the playhead are all positioned inside it. Time↔x math must measure THIS+ // (not the padded/scrollbar-inset tracks box), else clicks map to the wrong+ // time and the mapping drifts as the scrollbar appears/disappears.+ const canvasRef = useRef<HTMLDivElement | null>(null);const navRef = useRef<HTMLDivElement | null>(null);const clipsRef = useRef<HTMLDivElement | null>(null);// True while a clip pointer-drag actually moved the pointer past the@@ -254,15 +272,22 @@ export function V4Timeline({}));const rulerTicks = useMemo(() => {+ // Adaptive interval so a long recording shows ~a dozen labels instead of+ // one every 15s (which crams the ruler unreadably past a few minutes).+ const NICE_STEPS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600];+ const step = NICE_STEPS.find((s) => total / s <= 12) ?? NICE_STEPS[NICE_STEPS.length - 1];const out: string[] = [];- for (let t = 0; t <= total; t += 15) out.push(fmt(t));+ for (let t = 0; t <= total; t += step) out.push(fmtTick(t));return out;}, [total]);// ── interactions ────────────────────────────────────────────────const seekToClientX = useCallback((clientX: number) => {- const el = tracksRef.current;+ // Measure the canvas (the zoomed timeline frame): (clientX - left)/width+ // is the fraction along the FULL timeline under the cursor, so it stays+ // correct under zoom/pan and is unaffected by padding or the scrollbar.+ const el = canvasRef.current;if (!el) return;const r = el.getBoundingClientRect();const pct = Math.min(1, Math.max(0, (clientX - r.left) / r.width));@@ -305,7 +330,9 @@ export function V4Timeline({e.preventDefault();e.stopPropagation();tl.selectRegion(pill.kind, pill.id, { additive: e.shiftKey });- const el = tracksRef.current;+ // Scale drag deltas against the canvas (full zoomed timeline) width, so a+ // drag tracks the cursor exactly regardless of padding, scrollbar or zoom.+ const el = canvasRef.current;if (!el) return;const r = el.getBoundingClientRect();const startX = e.clientX;@@ -422,7 +449,9 @@ export function V4Timeline({[nav],);- // Scroll = pan, Ctrl+scroll = zoom around the cursor's timeline position.+ // Plain scroll = vertical scroll (the panel can be too short to show every+ // lane + the main track). Shift+scroll = horizontal pan. Ctrl+scroll = zoom+ // around the cursor's timeline position.// Attached as a native (non-passive) listener rather than React's onWheel:// React marks wheel handlers passive by default, so e.preventDefault()// there silently no-ops and the browser/OS still intercepts Ctrl+wheel as@@ -431,10 +460,10 @@ export function V4Timeline({const el = tracksRef.current;if (!el) return;const onWheelNative = (e: WheelEvent) => {- e.preventDefault();const r = el.getBoundingClientRect();const viewportPct = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));if (e.ctrlKey) {+ e.preventDefault();setNav((prev) => {const width = prev.end - prev.start;const cursorFrac = prev.start + viewportPct * width;@@ -443,14 +472,18 @@ export function V4Timeline({const start = Math.max(0, Math.min(1 - nextWidth, cursorFrac - viewportPct * nextWidth));return { start, end: start + nextWidth };});- } else {+ } else if (e.shiftKey) {+ e.preventDefault();setNav((prev) => {const width = prev.end - prev.start;- const delta = (e.deltaY / r.width) * width;+ // Shift often routes the wheel onto deltaX; accept whichever axis moved.+ const wheelDelta = e.deltaX !== 0 ? e.deltaX : e.deltaY;+ const delta = (wheelDelta / r.width) * width;const start = Math.max(0, Math.min(1 - width, prev.start + delta));return { start, end: start + width };});}+ // Otherwise let the native vertical scroll of .tlTracks run (no preventDefault).};el.addEventListener("wheel", onWheelNative, { passive: false });return () => el.removeEventListener("wheel", onWheelNative);@@ -928,7 +961,7 @@ export function V4Timeline({/><div className={styles.tlHints}><span className={styles.tlHint}>- <span className={styles.tlKbd}>Scroll</span> {t("labels.pan")}+ <span className={styles.tlKbd}>Shift+Scroll</span> {t("labels.pan")}</span><span className={styles.tlHint}><span className={styles.tlKbd}>Ctrl+Scroll</span> {t("labels.zoom")}@@ -936,152 +969,170 @@ export function V4Timeline({</div></div>- <div ref={tracksRef} className={styles.tlTracks} onPointerDown={startScrub}>- <div className={styles.tlCanvas} style={canvasStyle}>- <div- aria-hidden- className={styles.tlPlayhead}- style={{ left: `${pctOf(currentTimeSec)}%` }}- >- <span- className={styles.tlPlayheadDiamond}- style={{ pointerEvents: "auto", cursor: "grab" }}- onPointerDown={(e) => {- e.stopPropagation();- startScrub(e);- }}- />+ {/* Ruler + tracks share one relative wrapper so a single playhead overlay+ (below) can span both — one continuous line whose head aligns with the+ clips regardless of the tracks' scrollbar (scrollbar-gutter keeps all+ three canvases the same width). */}+ <div className={styles.tlBody}>+ {/* Fixed ruler header: the ruler ticks stay pinned right below the toolbar+ so they don't scroll off when the panel is short — only the lanes/clips+ below scroll. Shares the tracks' zoom/pan transform so ticks line up. */}+ <div className={styles.tlRulerRow} onPointerDown={startScrub}>+ <div className={styles.tlCanvas} style={canvasStyle}>+ <div className={styles.tlRuler}>+ {rulerTicks.map((t, i) => (+ <span key={`${t}-${i}`}>{t}</span>+ ))}+ </div></div>- {snapPct !== null ? (- <div aria-hidden className={styles.tlSnapGuide} style={{ left: `${snapPct}%` }} />- ) : null}+ </div>- <div className={styles.tlRuler}>- {rulerTicks.map((t, i) => (- <span key={`${t}-${i}`}>{t}</span>- ))}- </div>+ <div ref={tracksRef} className={styles.tlTracks} onPointerDown={startScrub}>+ <div ref={canvasRef} className={styles.tlCanvas} style={canvasStyle}>+ {snapPct !== null ? (+ <div aria-hidden className={styles.tlSnapGuide} style={{ left: `${snapPct}%` }} />+ ) : null}- {showLanes ? (- <>- <div className={styles.tlLane}>- {renderPills(annPills, t("toolbar.noAnnotationsYet"))}- </div>- <div className={styles.tlLane}>- {renderPills(speedPills, t("toolbar.constantSpeed"))}- </div>- <div className={styles.tlLane}>{renderPills(trimPills, t("toolbar.noTrims"))}</div>- <div className={styles.tlLane}>{renderPills(zoomPills, "")}</div>- </>- ) : null}+ {showLanes ? (+ <>+ <div className={styles.tlLane}>+ {renderPills(annPills, t("toolbar.noAnnotationsYet"))}+ </div>+ <div className={styles.tlLane}>+ {renderPills(speedPills, t("toolbar.constantSpeed"))}+ </div>+ <div className={styles.tlLane}>{renderPills(trimPills, t("toolbar.noTrims"))}</div>+ <div className={styles.tlLane}>{renderPills(zoomPills, "")}</div>+ </>+ ) : null}- <div- ref={clipsRef}- className={`${styles.tlClips}${dragOver ? ` ${styles.tlClipsDrag}` : ""}`}- onDragOver={(e) => {- e.preventDefault();- e.dataTransfer.dropEffect = "copy";- if (!dragOver) setDragOver(true);- }}- onDragLeave={() => setDragOver(false)}- onDrop={(e) => {- e.preventDefault();- setDragOver(false);- const id = e.dataTransfer.getData(ASSET_MIME);- if (id && onDropAsset) onDropAsset(id);- }}- >- {clips.map((c, i) => {- const dur = c.timelineEndSec - c.timelineStartSec;- const asset = tl.assets.find((a) => a.id === c.assetId);- const clipVideoUrl = videoSources.find((v) => v.id === c.assetId)?.src;- const selected = tl.clipSelection === c.id;- const dragging = clipDrag?.id === c.id;- // Siblings between the dragged clip's origin and its live- // target slide sideways (via the base .tlClip transition) to- // open a gap at the drop point; the dragged clip itself- // follows the pointer directly (see .tlClipDragging's- // transition:none override).- let clipTransform: string | undefined;- if (dragging) {- clipTransform = `translateX(${clipDrag.pointerDeltaX}px)`;- } else if (clipDrag) {- const { from, target, shiftPx } = clipDrag;- if (target > from && i > from && i <= target)- clipTransform = `translateX(${-shiftPx}px)`;- else if (target < from && i >= target && i < from)- clipTransform = `translateX(${shiftPx}px)`;- }- return (- <div- key={c.id}- data-clip-id={c.id}- className={`${styles.tlClip}${selected ? ` ${styles.tlClipSel}` : ""}${- dragging ? ` ${styles.tlClipDragging}` : ""- }`}- style={{ flex: `${dur} 0 0`, transform: clipTransform }}- onPointerDown={(e) => startClipDrag(e, c)}- onClick={(e) => {- e.stopPropagation();- // A completed reorder-drag also fires a click; don't let it- // double as a selection.- if (didClipDragRef.current) {- didClipDragRef.current = false;- return;- }- tl.selectClip(c.id);- }}- onDoubleClick={(e) => {- e.stopPropagation();- onEditClip(c);- }}- title={t("toolbar.dragToReorderHint")}- >- <ClipWaveform- videoUrl={clipVideoUrl}- assetDurationSec={asset?.durationSec}- sourceStartSec={c.sourceStartSec}- sourceEndSec={c.sourceEndSec ?? c.sourceStartSec + dur}- />- <div className={styles.tlClipLabel}>- <span- className={styles.tlClipIcon}- data-no-clip-drag- title={t("toolbar.editInOutPoints")}- onClick={(e) => {- e.stopPropagation();- onEditClip(c);- }}- >- <Pencil size={9} />- </span>- <span className={styles.tlClipName}>- {tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}- </span>+ <div+ ref={clipsRef}+ className={`${styles.tlClips}${dragOver ? ` ${styles.tlClipsDrag}` : ""}`}+ onDragOver={(e) => {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ if (!dragOver) setDragOver(true);+ }}+ onDragLeave={() => setDragOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setDragOver(false);+ const id = e.dataTransfer.getData(ASSET_MIME);+ if (id && onDropAsset) onDropAsset(id);+ }}+ >+ {clips.map((c, i) => {+ const dur = c.timelineEndSec - c.timelineStartSec;+ const asset = tl.assets.find((a) => a.id === c.assetId);+ const clipVideoUrl = videoSources.find((v) => v.id === c.assetId)?.src;+ const selected = tl.clipSelection === c.id;+ const dragging = clipDrag?.id === c.id;+ // Siblings between the dragged clip's origin and its live+ // target slide sideways (via the base .tlClip transition) to+ // open a gap at the drop point; the dragged clip itself+ // follows the pointer directly (see .tlClipDragging's+ // transition:none override).+ let clipTransform: string | undefined;+ if (dragging) {+ clipTransform = `translateX(${clipDrag.pointerDeltaX}px)`;+ } else if (clipDrag) {+ const { from, target, shiftPx } = clipDrag;+ if (target > from && i > from && i <= target)+ clipTransform = `translateX(${-shiftPx}px)`;+ else if (target < from && i >= target && i < from)+ clipTransform = `translateX(${shiftPx}px)`;+ }+ return (+ <div+ key={c.id}+ data-clip-id={c.id}+ className={`${styles.tlClip}${selected ? ` ${styles.tlClipSel}` : ""}${+ dragging ? ` ${styles.tlClipDragging}` : ""+ }`}+ style={{ flex: `${dur} 0 0`, transform: clipTransform }}+ onPointerDown={(e) => startClipDrag(e, c)}+ onClick={(e) => {+ e.stopPropagation();+ // A completed reorder-drag also fires a click; don't let it+ // double as a selection.+ if (didClipDragRef.current) {+ didClipDragRef.current = false;+ return;+ }+ tl.selectClip(c.id);+ }}+ onDoubleClick={(e) => {+ e.stopPropagation();+ onEditClip(c);+ }}+ title={t("toolbar.dragToReorderHint")}+ >+ <ClipWaveform+ videoUrl={clipVideoUrl}+ assetDurationSec={asset?.durationSec}+ sourceStartSec={c.sourceStartSec}+ sourceEndSec={c.sourceEndSec ?? c.sourceStartSec + dur}+ />+ <div className={styles.tlClipLabel}>+ <span+ className={styles.tlClipIcon}+ data-no-clip-drag+ title={t("toolbar.editInOutPoints")}+ onClick={(e) => {+ e.stopPropagation();+ onEditClip(c);+ }}+ >+ <Pencil size={9} />+ </span>+ <span className={styles.tlClipName}>+ {tl.assets.find((a) => a.id === c.assetId)?.label ?? c.assetId}+ </span>+ </div>+ {selected ? (+ <button+ type="button"+ data-no-clip-drag+ className={styles.tlClipDelete}+ title={t("toolbar.deleteClip")}+ aria-label={t("toolbar.deleteClip")}+ onClick={(e) => {+ e.stopPropagation();+ void tl.removeClip(c.id);+ }}+ >+ <Trash2 size={13} />+ </button>+ ) : null}</div>- {selected ? (- <button- type="button"- data-no-clip-drag- className={styles.tlClipDelete}- title={t("toolbar.deleteClip")}- aria-label={t("toolbar.deleteClip")}- onClick={(e) => {- e.stopPropagation();- void tl.removeClip(c.id);- }}- >- <Trash2 size={13} />- </button>- ) : null}+ );+ })}+ {dragOver ? (+ <div aria-hidden className={styles.tlDropHint}>+ {t("toolbar.dropToAdd")}</div>- );- })}- {dragOver ? (- <div aria-hidden className={styles.tlDropHint}>- {t("toolbar.dropToAdd")}- </div>- ) : null}+ ) : null}+ </div>+ </div>+ </div>++ {/* Single playhead overlay spanning the ruler + tracks: fixed vertically+ (a cursor, so it doesn't scroll with the lanes) and sharing the exact+ same zoom/pan transform + width as the canvases, so its line stays+ continuous from the ruler down through the clips and its head aligns. */}+ <div className={styles.tlPlayheadLayer} aria-hidden>+ <div className={styles.tlCanvas} style={canvasStyle}>+ <div className={styles.tlPlayhead} style={{ left: `${pctOf(currentTimeSec)}%` }}>+ <span+ className={styles.tlPlayheadDiamond}+ style={{ pointerEvents: "auto", cursor: "grab" }}+ onPointerDown={(e) => {+ e.stopPropagation();+ startScrub(e);+ }}+ />+ </div></div></div></div>diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.jsonindex c5a20f527..d7cccf227 100644--- a/src/i18n/locales/ar/editor.json+++ b/src/i18n/locales/ar/editor.json@@ -176,8 +176,7 @@"subtitle": "عرض المخطط الزمني إلى ملف","addVideoBeforeExporting": "أضف فيديو قبل التصدير.","quality": "الجودة",- "qualitySmallerFile": "ملف أصغر",- "qualityRecommended": "موصى به",+ "qualityUpscaleWarning": "تكبير الدقة","qualityMatchRecording": "مطابقة التسجيل","frameRate": "معدل الإطارات","codec": "الترميز",diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.jsonindex 64a1b7475..4847904c9 100644--- a/src/i18n/locales/en/editor.json+++ b/src/i18n/locales/en/editor.json@@ -176,8 +176,7 @@"subtitle": "Render the timeline to a file","addVideoBeforeExporting": "Add a video before exporting.","quality": "Quality",- "qualitySmallerFile": "Smaller file",- "qualityRecommended": "Recommended",+ "qualityUpscaleWarning": "Upscale","qualityMatchRecording": "Match recording","frameRate": "Frame rate","codec": "Codec",diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.jsonindex e68cdada9..33eadbba8 100644--- a/src/i18n/locales/es/editor.json+++ b/src/i18n/locales/es/editor.json@@ -176,8 +176,7 @@"subtitle": "Renderizar la línea de tiempo a un archivo","addVideoBeforeExporting": "Añade un vídeo antes de exportar.","quality": "Calidad",- "qualitySmallerFile": "Archivo más pequeño",- "qualityRecommended": "Recomendado",+ "qualityUpscaleWarning": "Upscaling","qualityMatchRecording": "Igual que la grabación","frameRate": "Fotogramas por segundo","codec": "Códec",diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.jsonindex 15aab5f9e..39585b7fb 100644--- a/src/i18n/locales/fr/editor.json+++ b/src/i18n/locales/fr/editor.json@@ -176,8 +176,7 @@"subtitle": "Rendre la timeline dans un fichier","addVideoBeforeExporting": "Ajoutez une vidéo avant d'exporter.","quality": "Qualité",- "qualitySmallerFile": "Fichier plus petit",- "qualityRecommended": "Recommandé",+ "qualityUpscaleWarning": "Upscaling","qualityMatchRecording": "Comme l'enregistrement","frameRate": "Fréquence d'images","codec": "Codec",diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.jsonindex 1fa3e2c76..7a0e16cac 100644--- a/src/i18n/locales/it/editor.json+++ b/src/i18n/locales/it/editor.json@@ -176,8 +176,7 @@"subtitle": "Esegui il rendering della timeline in un file","addVideoBeforeExporting": "Aggiungi un video prima di esportare.","quality": "Qualità",- "qualitySmallerFile": "File più piccolo",- "qualityRecommended": "Consigliato",+ "qualityUpscaleWarning": "Upscaling","qualityMatchRecording": "Come la registrazione","frameRate": "Frame rate","codec": "Codec",diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.jsonindex c8a3c3be8..6f7ef0fb8 100644--- a/src/i18n/locales/ja-JP/editor.json+++ b/src/i18n/locales/ja-JP/editor.json@@ -176,8 +176,7 @@"subtitle": "タイムラインをファイルに書き出します","addVideoBeforeExporting": "エクスポートする前に動画を追加してください。","quality": "画質",- "qualitySmallerFile": "ファイルサイズを小さく",- "qualityRecommended": "推奨",+ "qualityUpscaleWarning": "アップスケール","qualityMatchRecording": "録画と同じ","frameRate": "フレームレート","codec": "コーデック",diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.jsonindex 0e6b64c25..080c12312 100644--- a/src/i18n/locales/ko-KR/editor.json+++ b/src/i18n/locales/ko-KR/editor.json@@ -176,8 +176,7 @@"subtitle": "타임라인을 파일로 렌더링합니다","addVideoBeforeExporting": "내보내기 전에 동영상을 추가하세요.","quality": "화질",- "qualitySmallerFile": "파일 크기 작게",- "qualityRecommended": "권장",+ "qualityUpscaleWarning": "업스케일","qualityMatchRecording": "녹화와 동일","frameRate": "프레임 속도","codec": "코덱",diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.jsonindex 2026d7e57..2e1d15fc4 100644--- a/src/i18n/locales/pt-BR/editor.json+++ b/src/i18n/locales/pt-BR/editor.json@@ -176,8 +176,7 @@"subtitle": "Renderizar a linha do tempo para um arquivo","addVideoBeforeExporting": "Adicione um vídeo antes de exportar.","quality": "Qualidade",- "qualitySmallerFile": "Arquivo menor",- "qualityRecommended": "Recomendado",+ "qualityUpscaleWarning": "Upscaling","qualityMatchRecording": "Igual à gravação","frameRate": "Taxa de quadros","codec": "Codec",diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.jsonindex cb3344a5d..32bccb64f 100644--- a/src/i18n/locales/ru/editor.json+++ b/src/i18n/locales/ru/editor.json@@ -176,8 +176,7 @@"subtitle": "Рендеринг таймлайна в файл","addVideoBeforeExporting": "Добавьте видео перед экспортом.","quality": "Качество",- "qualitySmallerFile": "Меньший размер файла",- "qualityRecommended": "Рекомендуется",+ "qualityUpscaleWarning": "Апскейл","qualityMatchRecording": "Как в записи","frameRate": "Частота кадров","codec": "Кодек",diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.jsonindex 97ef65f6f..a5aed00ec 100644--- a/src/i18n/locales/tr/editor.json+++ b/src/i18n/locales/tr/editor.json@@ -176,8 +176,7 @@"subtitle": "Zaman çizelgesini bir dosyaya işleyin","addVideoBeforeExporting": "Dışa aktarmadan önce bir video ekleyin.","quality": "Kalite",- "qualitySmallerFile": "Daha küçük dosya",- "qualityRecommended": "Önerilen",+ "qualityUpscaleWarning": "Upscale","qualityMatchRecording": "Kayıtla eşleştir","frameRate": "Kare hızı","codec": "Codec",diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.jsonindex f1246c62e..658d72f24 100644--- a/src/i18n/locales/vi/editor.json+++ b/src/i18n/locales/vi/editor.json@@ -176,8 +176,7 @@"subtitle": "Kết xuất dòng thời gian thành tệp","addVideoBeforeExporting": "Thêm video trước khi xuất.","quality": "Chất lượng",- "qualitySmallerFile": "Tệp nhỏ hơn",- "qualityRecommended": "Đề xuất",+ "qualityUpscaleWarning": "Upscale","qualityMatchRecording": "Khớp với bản ghi","frameRate": "Tốc độ khung hình","codec": "Codec",diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.jsonindex 369d18f77..f4e64efae 100644--- a/src/i18n/locales/zh-CN/editor.json+++ b/src/i18n/locales/zh-CN/editor.json@@ -176,8 +176,7 @@"subtitle": "将时间轴渲染为文件","addVideoBeforeExporting": "导出前请先添加视频。","quality": "画质",- "qualitySmallerFile": "文件更小",- "qualityRecommended": "推荐",+ "qualityUpscaleWarning": "放大","qualityMatchRecording": "与录制一致","frameRate": "帧率","codec": "编码格式",diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.jsonindex 2c0478ed0..c957f6871 100644--- a/src/i18n/locales/zh-TW/editor.json+++ b/src/i18n/locales/zh-TW/editor.json@@ -176,8 +176,7 @@"subtitle": "將時間軸轉譯為檔案","addVideoBeforeExporting": "匯出前請先新增影片。","quality": "畫質",- "qualitySmallerFile": "檔案較小",- "qualityRecommended": "建議",+ "qualityUpscaleWarning": "放大","qualityMatchRecording": "與錄製內容相符","frameRate": "幀率","codec": "編碼格式",diff --git a/src/native/contracts.ts b/src/native/contracts.tsindex 9e5d699fb..0b40a7c4d 100644--- a/src/native/contracts.ts+++ b/src/native/contracts.ts@@ -91,8 +91,9 @@ export interface ProjectFileResult {}// ---- AI Edition domain (Phase 1+) ------------------------------------------// v3 AxcutDocument projects live under userData/projects/<id>.axcut. Project-// ids are uuid-prefixed strings (e.g. "proj_<uuid>"). Asset ids likewise.+// v3/v4 AxcutDocument projects live under userData/projects/<id>.openscreen+// (older builds used <id>.axcut, migrated on access). Project ids are+// uuid-prefixed strings (e.g. "proj_<uuid>"). Asset ids likewise.export interface AiEditionProjectSummary {id: string;