Open source CapCut alternative.
TypeScript
feat(site): add Cut, a standalone free video editor on the cut subdomain
David Le139801a23222
diff --git a/site/.gitignore b/site/.gitignoreindex 1df48291..30f2cc01 100644--- a/site/.gitignore+++ b/site/.gitignore@@ -42,3 +42,7 @@ yarn-error.log*next-env.d.ts/src/generated/prisma++# Cut (video editor) local runtime data — per-project media/exports + shared library+/projects/+/library/diff --git a/site/middleware.ts b/site/middleware.tsnew file mode 100644index 00000000..ea72783b--- /dev/null+++ b/site/middleware.ts@@ -0,0 +1,30 @@+import { NextResponse, type NextRequest } from "next/server";++// Cut (the video editor) is served on the cut.donkeyuse.com subdomain, but its+// routes live under /cut in this single site app. For requests on the Cut host we+// rewrite page paths to /cut/* so Cut's root-relative links (/, /library,+// /p/[id]) resolve to its routes, while the apex host keeps serving Donkey.+// /api/* and Next internals are left untouched — Cut's API handlers are mounted+// under the shared /api tree and don't collide with Donkey's.+//+// Local dev: add nothing to /etc/hosts — `cut.localhost` already resolves to+// 127.0.0.1, so http://cut.localhost:3000/ exercises this path.+const CUT_HOSTS = new Set(["cut.donkeyuse.com", "cut.localhost"]);++export function middleware(req: NextRequest) {+ const host = (req.headers.get("host") ?? "").split(":")[0];+ if (!CUT_HOSTS.has(host)) return NextResponse.next();++ const { pathname } = req.nextUrl;+ if (pathname.startsWith("/cut") || pathname.startsWith("/api")) {+ return NextResponse.next();+ }+ const url = req.nextUrl.clone();+ url.pathname = `/cut${pathname === "/" ? "" : pathname}`;+ return NextResponse.rewrite(url);+}++export const config = {+ // Run for page routes; skip Next internals and files with an extension.+ matcher: ["/((?!_next/|.*\\..*).*)"],+};diff --git a/site/next.config.ts b/site/next.config.tsindex 3a65376d..f93d1c29 100644--- a/site/next.config.ts+++ b/site/next.config.ts@@ -3,6 +3,8 @@ import type { NextConfig } from "next";const nextConfig: NextConfig = {pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],+ // Cut (the video editor) uploads large media through server actions.+ experimental: { serverActions: { bodySizeLimit: "4gb" } },};const withMDX = createMDX({diff --git a/site/package-lock.json b/site/package-lock.jsonindex a4bc9e73..b883a270 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -10,7 +10,9 @@"hasInstallScript": true,"license": "Apache-2.0","dependencies": {- "@base-ui/react": "^1.4.1",+ "@ai-sdk/react": "^4.0.15",+ "@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@base-ui/react": "^1.6.0","@better-auth/api-key": "1.6.11","@better-auth/core": "1.6.11","@better-auth/kysely-adapter": "1.6.11",@@ -26,23 +28,26 @@"@tailwindcss/typography": "^0.5.19","@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13",+ "ai": "^7.0.14","better-auth": "1.6.11","browser-use-sdk": "^3.8.4","class-variance-authority": "^0.7.1","clsx": "^2.1.1","defuddle": "^0.18.1","linkedom": "^0.18.12",- "lucide-react": "^1.16.0",+ "lucide-react": "^1.23.0","next": "16.2.6","openai": "^6.39.0","pg": "^8.20.0","react": "19.2.4","react-dom": "19.2.4",+ "react-markdown": "^10.1.0","shadcn": "^4.7.0","stripe": "^22.2.0","tailwind-merge": "^3.6.0","tw-animate-css": "^1.4.0",- "zod": "^4.4.3"+ "zod": "^4.4.3",+ "zustand": "^5.0.5"},"devDependencies": {"@tailwindcss/postcss": "^4",@@ -59,6 +64,90 @@"typescript": "^5"}},+ "node_modules/@ai-sdk/gateway": {+ "version": "4.0.12",+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-4.0.12.tgz",+ "integrity": "sha512-Y7Fy8xJwPz7ZC0DhSQG3HIVk+drup42hrIj6yqKlib3CxwiR0F7nYyUI8+kPrEtbZEoyKoRstvT4/o0HEyFBHA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "4.0.2",+ "@ai-sdk/provider-utils": "5.0.5",+ "@vercel/oidc": "3.2.0"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/@ai-sdk/mcp": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/@ai-sdk/mcp/-/mcp-2.0.7.tgz",+ "integrity": "sha512-DX1v5M/R4RD2yi1KSH2ERLKcb6h2qJF0DKt0PGTTpNJNK+meXMmouwSRZS8Y+JocbyHk7U9p6PgqVmKU/e5XhQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "4.0.2",+ "@ai-sdk/provider-utils": "5.0.5",+ "pkce-challenge": "^5.0.1"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/@ai-sdk/provider": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-4.0.2.tgz",+ "integrity": "sha512-pfPoy9J1B1xV7cqJ8MYHOsDYrMv5tR3+EMNfI249OhkD2uRakvav3Fo7XpD2luuN/YNCBY7KfEQc7vEV7KEtyw==",+ "license": "Apache-2.0",+ "dependencies": {+ "json-schema": "^0.4.0"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@ai-sdk/provider-utils": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-5.0.5.tgz",+ "integrity": "sha512-oI0t3dvCoqWNV1I8o1Rybi2DXDvHES5r/TrwtJW90tuFLVepgJlftPxrcjh8vaSvjqC2diTuA2vXyjKAyHJm4A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/provider": "4.0.2",+ "@standard-schema/spec": "^1.1.0",+ "@workflow/serde": "4.1.0",+ "eventsource-parser": "^3.0.8"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },+ "node_modules/@ai-sdk/react": {+ "version": "4.0.16",+ "resolved": "https://registry.npmjs.org/@ai-sdk/react/-/react-4.0.16.tgz",+ "integrity": "sha512-VpJhn9ob7EC9g2Wn5m/FCCu8h6Uj4tE7u8BunK0kNo5kJasEl/f3oHV7f3r4tNtq4zW5wu0EjGs5sKkShErGew==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/mcp": "2.0.7",+ "@ai-sdk/provider": "4.0.2",+ "@ai-sdk/provider-utils": "5.0.5",+ "ai": "7.0.15",+ "swr": "^2.4.1",+ "throttleit": "2.1.0"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1"+ }+ },"node_modules/@alloc/quick-lru": {"version": "5.2.0","resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz",@@ -72,6 +161,156 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/@anthropic-ai/claude-agent-sdk": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk/-/claude-agent-sdk-0.3.201.tgz",+ "integrity": "sha512-InT1XLmf2QpldWdtznKDWEoGJT4p+sXh24yxbeBQ++lMJCzMrI0W27MEmmmDWx0otpa+ubdHCF5YQ6oiNt7cmg==",+ "license": "SEE LICENSE IN README.md",+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.201",+ "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.201"+ },+ "peerDependencies": {+ "@anthropic-ai/sdk": ">=0.93.0",+ "@modelcontextprotocol/sdk": "^1.29.0",+ "zod": "^4.0.0"+ }+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-darwin-arm64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.201.tgz",+ "integrity": "sha512-8Mcb3BDyKUGfJWFFTWwt+at37lbDH3ZwVtUNPWGG1toZ75RDCJry5U4kXRvQ2xokvJQlA0E+eNp6keWe5ZH22Q==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-darwin-x64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.201.tgz",+ "integrity": "sha512-TFR2bu0+ml3RHoMrtsgD0qDK5Oknw8kYGBV7qpQHn+IWmE96gnHhogG1LpJwpHtni08XkJIjfWk1DdlsUYtRkQ==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "darwin"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.201.tgz",+ "integrity": "sha512-mShTo3MwF0gkN4dDw78wWJiB6aBDVRkl81cnApvoBofpdyUBYgm9Gw16CCjDTgelMKeBFqN6ErJpwjI3wbP00A==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-arm64-musl": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.201.tgz",+ "integrity": "sha512-EiqbpfJIpChfkn+8Uj061Qjyw0eaRcOXtdrvVuHANyj8ZErVOr8HlH6op9PSeIUa9TX0m2+tNgKPQvOGseQckA==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.201.tgz",+ "integrity": "sha512-jrJBrRWrSuoFKIgjyqxHqmfd6Pb3Bs5Bvakg0knXCTC4fbUXGnC9Q6u7gdDwgXohUNP6/DD+s8U7bivvvVv0dg==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-linux-x64-musl": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.201.tgz",+ "integrity": "sha512-IbxnzO5UCbqbm2TnzCHkSyJorAFw2isdKdIsFCTxJJjSs3ZC+v3LC1QSUiVCx0qi+CV6w3MKx6mLI11mrvhbbQ==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "linux"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-win32-arm64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.201.tgz",+ "integrity": "sha512-UsoytRJ/037uHpb3ATrIoe+AgwTf+PwKuFLGjddHAV/11wERJs0hlrnSmcnp43kf0PFxoSNinngme96YYASmQg==",+ "cpu": [+ "arm64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@anthropic-ai/claude-agent-sdk-win32-x64": {+ "version": "0.3.201",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.201.tgz",+ "integrity": "sha512-PhalN/0cWcqDfbx7iwoLNR2gurjTiqhBk1G6K+NRScxEcQjWuu5xKXCcdbX8ePVpT+nbEMmFEFpn2y+8V8hIdA==",+ "cpu": [+ "x64"+ ],+ "license": "SEE LICENSE IN LICENSE.md",+ "optional": true,+ "os": [+ "win32"+ ]+ },+ "node_modules/@anthropic-ai/sdk": {+ "version": "0.110.0",+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.110.0.tgz",+ "integrity": "sha512-hOP4bNYXDFHDxxiEgzlILXrxZIYCDnhe8sry0RDRKD/QnsEpvZcQpablCdm9X/WuD/YgOiSIkkqsL1mLLlTqJw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "json-schema-to-ts": "^3.1.1",+ "standardwebhooks": "^1.0.0"+ },+ "bin": {+ "anthropic-ai-sdk": "bin/cli"+ },+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ },+ "peerDependenciesMeta": {+ "zod": {+ "optional": true+ }+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.0","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",@@ -433,9 +672,9 @@}},"node_modules/@babel/runtime": {- "version": "7.29.2",- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",- "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==","license": "MIT","engines": {"node": ">=6.9.0"@@ -487,13 +726,13 @@}},"node_modules/@base-ui/react": {- "version": "1.4.1",- "resolved": "https://registry.npmjs.org/@base-ui/react/-/react-1.4.1.tgz",- "integrity": "sha512-Ab5/LIhcmL8BQcsBUYiOfkSDRdLpvgUBzMK30cu684JPcLclYlztharvCZyNNgzJtbAiREzI9q0pI5erHCMgCw==",+ "version": "1.6.0",+ "resolved": "https://registry.npmjs.org/@base-ui/react/-/react-1.6.0.tgz",+ "integrity": "sha512-/jzjTWJYXhRFO45Bev9lc3cHbmjzCMpUqbMZ2AgKy/z25mY9B6shGSNcXcjQar9n5doM0KYW1W8fcFv2jZBuMw==","license": "MIT","dependencies": {"@babel/runtime": "^7.29.2",- "@base-ui/utils": "0.2.8",+ "@base-ui/utils": "0.3.1","@floating-ui/react-dom": "^2.1.8","@floating-ui/utils": "^0.2.11","use-sync-external-store": "^1.6.0"@@ -525,14 +764,14 @@}},"node_modules/@base-ui/utils": {- "version": "0.2.8",- "resolved": "https://registry.npmjs.org/@base-ui/utils/-/utils-0.2.8.tgz",- "integrity": "sha512-jvOi+c+ftGlGotNcKnzPVg2IhCaDTB6/6R3JeqdjdXktuAJi3wKH9T7+svuaKh1mmfVU11UWzUZVH74JDfi/wQ==",+ "version": "0.3.1",+ "resolved": "https://registry.npmjs.org/@base-ui/utils/-/utils-0.3.1.tgz",+ "integrity": "sha512-gFFiltORVmW/N6IILTGxizP3PBpVpysqML1ALY5Vk0mH+7faVkCknOU31goYHN5Aoek2dkjxva1XOD2Ce9WuIg==","license": "MIT","dependencies": {"@babel/runtime": "^7.29.2","@floating-ui/utils": "^0.2.11",- "reselect": "^5.1.1",+ "reselect": "^5.2.0","use-sync-external-store": "^1.6.0"},"peerDependencies": {@@ -2849,6 +3088,13 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/@stablelib/base64": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",+ "license": "MIT",+ "peer": true+ },"node_modules/@standard-schema/spec": {"version": "1.1.0","resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",@@ -4066,6 +4312,21 @@"win32"]},+ "node_modules/@vercel/oidc": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.2.0.tgz",+ "integrity": "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">= 20"+ }+ },+ "node_modules/@workflow/serde": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/@workflow/serde/-/serde-4.1.0.tgz",+ "integrity": "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==",+ "license": "Apache-2.0"+ },"node_modules/@xmldom/xmldom": {"version": "0.9.10","resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",@@ -4119,6 +4380,23 @@"node": ">= 14"}},+ "node_modules/ai": {+ "version": "7.0.15",+ "resolved": "https://registry.npmjs.org/ai/-/ai-7.0.15.tgz",+ "integrity": "sha512-7406MUy9O5sIhwOgxEWuoj+td3XUGgG96SBt6pmBU4t4sQ2fpnDx5UnHaXT2HUTXl5GorbWz/MfCrSPRz0QJqw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@ai-sdk/gateway": "4.0.12",+ "@ai-sdk/provider": "4.0.2",+ "@ai-sdk/provider-utils": "5.0.5"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "zod": "^3.25.76 || ^4.1.8"+ }+ },"node_modules/ajv": {"version": "6.15.0","resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",@@ -6909,6 +7187,13 @@"dev": true,"license": "MIT"},+ "node_modules/fast-sha256": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",+ "license": "Unlicense",+ "peer": true+ },"node_modules/fast-string-truncated-width": {"version": "3.0.3","resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",@@ -7706,6 +7991,16 @@"integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==","license": "MIT"},+ "node_modules/html-url-attributes": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",+ "integrity": "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/htmlparser2": {"version": "10.1.0","resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",@@ -8615,6 +8910,26 @@"integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==","license": "MIT"},+ "node_modules/json-schema": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",+ "license": "(AFL-2.1 OR BSD-3-Clause)"+ },+ "node_modules/json-schema-to-ts": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@babel/runtime": "^7.18.3",+ "ts-algebra": "^2.0.0"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/json-schema-traverse": {"version": "0.4.1","resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",@@ -9167,9 +9482,9 @@}},"node_modules/lucide-react": {- "version": "1.16.0",- "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.16.0.tgz",- "integrity": "sha512-dYwyPzb4MEKpGUmNYk3WKWPnMrHs3FKM+q94kAnJrcDIqqn1hq2xY8scaS2ovsOCM5D51ey2gaRG3PBb1vgoYQ==",+ "version": "1.23.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.23.0.tgz",+ "integrity": "sha512-38BpJcD0JhFosxHApP/BYsBetLpQFRoTRzEzstM/XCc3jsAG7wqaY1lgVwxiUe3xqYE+lNxo2PkCmYwXWrwwIw==","license": "ISC","peerDependencies": {"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"@@ -11455,6 +11770,33 @@"dev": true,"license": "MIT"},+ "node_modules/react-markdown": {+ "version": "10.1.0",+ "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",+ "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "hast-util-to-jsx-runtime": "^2.0.0",+ "html-url-attributes": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "remark-parse": "^11.0.0",+ "remark-rehype": "^11.0.0",+ "unified": "^11.0.0",+ "unist-util-visit": "^5.0.0",+ "vfile": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ },+ "peerDependencies": {+ "@types/react": ">=18",+ "react": ">=18"+ }+ },"node_modules/readdirp": {"version": "5.0.0","resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.0.0.tgz",@@ -12371,6 +12713,17 @@"dev": true,"license": "MIT"},+ "node_modules/standardwebhooks": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",+ "integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@stablelib/base64": "^1.0.0",+ "fast-sha256": "^1.3.0"+ }+ },"node_modules/statuses": {"version": "2.0.2","resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",@@ -12719,6 +13072,19 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/swr": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.4.2.tgz",+ "integrity": "sha512-ej644Y2bvkIajfR32KGeSSdBXQW+ScjGjkybZgSE7kFpk9eGnV44XY9FJylXi+W75pavSX1PVNB57W5EbhGIYw==",+ "license": "MIT",+ "dependencies": {+ "dequal": "^2.0.3",+ "use-sync-external-store": "^1.6.0"+ },+ "peerDependencies": {+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/tagged-tag": {"version": "1.0.0","resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",@@ -12771,6 +13137,18 @@"node": ">=18.13.0"}},+ "node_modules/throttleit": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz",+ "integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/tiny-invariant": {"version": "1.3.3","resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",@@ -12902,6 +13280,13 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/ts-algebra": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",+ "license": "MIT",+ "peer": true+ },"node_modules/ts-api-utils": {"version": "2.5.0","resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",@@ -13890,6 +14275,35 @@"zod": "^3.25.0 || ^4.0.0"}},+ "node_modules/zustand": {+ "version": "5.0.14",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.14.tgz",+ "integrity": "sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==",+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ },+ "peerDependencies": {+ "@types/react": ">=18.0.0",+ "immer": ">=9.0.6",+ "react": ">=18.0.0",+ "use-sync-external-store": ">=1.2.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "use-sync-external-store": {+ "optional": true+ }+ }+ },"node_modules/zwitch": {"version": "2.0.4","resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",diff --git a/site/package.json b/site/package.jsonindex f608a65d..3381507e 100644--- a/site/package.json+++ b/site/package.json@@ -16,7 +16,9 @@"prisma:prod": "dotenv -e .env -- prisma db push"},"dependencies": {- "@base-ui/react": "^1.4.1",+ "@ai-sdk/react": "^4.0.15",+ "@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@base-ui/react": "^1.6.0","@better-auth/api-key": "1.6.11","@better-auth/core": "1.6.11","@better-auth/kysely-adapter": "1.6.11",@@ -32,23 +34,26 @@"@tailwindcss/typography": "^0.5.19","@tanstack/react-query": "^5.101.0","@types/mdx": "^2.0.13",+ "ai": "^7.0.14","better-auth": "1.6.11","browser-use-sdk": "^3.8.4","class-variance-authority": "^0.7.1","clsx": "^2.1.1","defuddle": "^0.18.1","linkedom": "^0.18.12",- "lucide-react": "^1.16.0",+ "lucide-react": "^1.23.0","next": "16.2.6","openai": "^6.39.0","pg": "^8.20.0","react": "19.2.4","react-dom": "19.2.4",+ "react-markdown": "^10.1.0","shadcn": "^4.7.0","stripe": "^22.2.0","tailwind-merge": "^3.6.0","tw-animate-css": "^1.4.0",- "zod": "^4.4.3"+ "zod": "^4.4.3",+ "zustand": "^5.0.5"},"devDependencies": {"@tailwindcss/postcss": "^4",diff --git a/site/src/app/api/ai/chat/route.ts b/site/src/app/api/ai/chat/route.tsnew file mode 100644index 00000000..1f32f9ee--- /dev/null+++ b/site/src/app/api/ai/chat/route.ts@@ -0,0 +1,277 @@+import { spawn } from "node:child_process";+import os from "node:os";+import path from "node:path";+import { query } from "@anthropic-ai/claude-agent-sdk";+import { createUIMessageStream, createUIMessageStreamResponse, type UIMessage } from "ai";++export const runtime = "nodejs";++import { callBrowserTool, registerSession, unregisterSession, type UIChunkWriter } from "@/cut/server/ai/bridge";+import { systemPrompt } from "@/cut/server/ai/catalog";++interface ChatBody {+ messages: UIMessage[];+ model: string;+ context?: unknown;+ /** Provider-native session/thread id from the previous turn, if any. */+ providerSession?: string;+}++// Cut lives under site/src/cut; the proxy is spawned by filesystem path (not+// imported/bundled), so it is resolved from the dev cwd (site/) to its source.+const proxyPath = () =>+ path.join(process.cwd(), "src", "cut", "server", "ai", "mcp-proxy.mjs");++function lastUserText(messages: UIMessage[]): string {+ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i];+ if (m.role !== "user") continue;+ return m.parts+ .map((p) => (p.type === "text" ? p.text : ""))+ .join("")+ .trim();+ }+ return "";+}++/** Asset refs the user dragged into the chat with the last message. */+function lastUserAttachments(messages: UIMessage[]): unknown[] {+ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i];+ if (m.role !== "user") continue;+ const meta = (m as { metadata?: { attachments?: unknown } }).metadata;+ return Array.isArray(meta?.attachments) ? meta.attachments : [];+ }+ return [];+}++export async function POST(req: Request) {+ const body = (await req.json()) as ChatBody;+ const base = new URL(req.url).origin;+ const sessionKey = crypto.randomUUID();+ const userText = lastUserText(body.messages);+ const attachments = lastUserAttachments(body.messages);+ const attachBlock = attachments.length+ ? `\n\n<attached_assets>\nThe user attached these project media assets to this message (ids are usable with the editor tools):\n${JSON.stringify(attachments)}\n</attached_assets>`+ : "";+ const prompt = `${userText}${attachBlock}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;++ const stream = createUIMessageStream({+ execute: async ({ writer }) => {+ const emit: UIChunkWriter["write"] = (chunk) =>+ writer.write(chunk as Parameters<typeof writer.write>[0]);+ registerSession(sessionKey, { write: emit });+ emit({ type: "start" });+ // The browser posts tool outputs back to /api/ai/tool-result with this key.+ emit({ type: "data-session", data: { sessionKey }, transient: true });+ try {+ if (body.model.startsWith("claude")) {+ await runClaude(emit, prompt, body, base, sessionKey, req.signal);+ } else if (body.model === "cut-test") {+ await runFake(emit, sessionKey, userText);+ } else {+ await runCodex(emit, prompt, body, base, sessionKey, req.signal);+ }+ } catch (err) {+ emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });+ } finally {+ unregisterSession(sessionKey);+ emit({ type: "finish" });+ }+ },+ });++ return createUIMessageStreamResponse({ stream });+}++/** Claude models through the Agent SDK — the user's Claude Code login. */+async function runClaude(+ emit: UIChunkWriter["write"],+ prompt: string,+ body: ChatBody,+ base: string,+ sessionKey: string,+ signal: AbortSignal+) {+ const q = query({+ prompt,+ options: {+ model: body.model,+ ...(body.providerSession ? { resume: body.providerSession } : {}),+ systemPrompt: systemPrompt(),+ tools: [], // no built-in tools — the editor MCP server is the whole surface+ mcpServers: {+ cut: {+ type: "stdio",+ command: process.execPath,+ args: [proxyPath(), base, sessionKey],+ alwaysLoad: true,+ },+ },+ allowedTools: ["mcp__cut"],+ permissionMode: "dontAsk",+ settingSources: [], // don't drag the user's CLAUDE.md/settings into app chats+ includePartialMessages: true,+ maxTurns: 30,+ cwd: os.tmpdir(),+ },+ });+ const onAbort = () => void q.interrupt().catch(() => {});+ signal.addEventListener("abort", onAbort);++ let textCount = 0;+ let textId: string | null = null;+ try {+ for await (const msg of q) {+ const m = msg as unknown as Record<string, unknown> & { type: string };+ if (m.type === "system" && m.subtype === "init") {+ emit({ type: "data-session", data: { providerSession: m.session_id }, transient: true });+ } else if (m.type === "stream_event") {+ const ev = m.event as {+ type: string;+ content_block?: { type: string };+ delta?: { type: string; text?: string };+ };+ if (ev.type === "content_block_start" && ev.content_block?.type === "text") {+ textId = `t${++textCount}`;+ emit({ type: "text-start", id: textId });+ } else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta" && textId) {+ emit({ type: "text-delta", id: textId, delta: ev.delta.text ?? "" });+ } else if (ev.type === "content_block_stop" && textId) {+ emit({ type: "text-end", id: textId });+ textId = null;+ }+ } else if (m.type === "result" && m.subtype !== "success") {+ const detail = typeof m.result === "string" ? m.result : String(m.subtype);+ emit({ type: "error", errorText: `Claude stopped: ${detail}` });+ }+ }+ } finally {+ signal.removeEventListener("abort", onAbort);+ if (textId) emit({ type: "text-end", id: textId });+ }+}++/** GPT models through the Codex CLI — the user's ChatGPT login. */+async function runCodex(+ emit: UIChunkWriter["write"],+ prompt: string,+ body: ChatBody,+ base: string,+ sessionKey: string,+ signal: AbortSignal+) {+ const args = ["exec"];+ if (body.providerSession) args.push("resume", body.providerSession);+ args.push(+ "--json",+ "--skip-git-repo-check",+ "--sandbox",+ "read-only",+ "-m",+ body.model,+ "-C",+ os.tmpdir(),+ "-c",+ `mcp_servers.cut.command=${JSON.stringify(process.execPath)}`,+ "-c",+ `mcp_servers.cut.args=${JSON.stringify([proxyPath(), base, sessionKey])}`,+ body.providerSession ? prompt : `${systemPrompt()}\n\n${prompt}`+ );++ await new Promise<void>((resolve, reject) => {+ // stdin must be closed: `codex exec` otherwise waits on it for EOF.+ const proc = spawn("codex", args, { env: process.env, stdio: ["ignore", "pipe", "pipe"] });+ const onAbort = () => proc.kill("SIGTERM");+ signal.addEventListener("abort", onAbort);++ let textCount = 0;+ let stdoutBuf = "";+ let stderrTail = "";+ proc.stdout.setEncoding("utf8");+ proc.stdout.on("data", (chunk: string) => {+ stdoutBuf += chunk;+ let nl;+ while ((nl = stdoutBuf.indexOf("\n")) !== -1) {+ const line = stdoutBuf.slice(0, nl).trim();+ stdoutBuf = stdoutBuf.slice(nl + 1);+ if (!line) continue;+ let ev: { type?: string; thread_id?: string; message?: string; item?: { type?: string; text?: string }; error?: { message?: string } };+ try {+ ev = JSON.parse(line);+ } catch {+ continue;+ }+ if (ev.type === "thread.started" && ev.thread_id) {+ emit({ type: "data-session", data: { providerSession: ev.thread_id }, transient: true });+ } else if (ev.type === "item.completed" && ev.item?.type === "agent_message" && ev.item.text) {+ const id = `t${++textCount}`;+ emit({ type: "text-start", id });+ emit({ type: "text-delta", id, delta: ev.item.text });+ emit({ type: "text-end", id });+ } else if (ev.type === "error" || ev.type === "turn.failed") {+ const message = ev.error?.message ?? ev.message ?? "Codex failed.";+ emit({ type: "error", errorText: message });+ }+ }+ });+ proc.stderr.on("data", (d: Buffer) => {+ stderrTail = (stderrTail + d.toString()).slice(-2000);+ });+ proc.on("error", (err) => {+ signal.removeEventListener("abort", onAbort);+ reject(+ err.message.includes("ENOENT")+ ? new Error("Codex CLI not found — install it with: npm i -g @openai/codex")+ : err+ );+ });+ proc.on("close", (code) => {+ signal.removeEventListener("abort", onAbort);+ if (code !== 0 && !signal.aborted && code !== null) {+ const tail = stderrTail.trim().split("\n").slice(-2).join(" ");+ emit({ type: "error", errorText: `Codex exited with code ${code}. ${tail}`.trim() });+ }+ resolve();+ });+ });+}++/**+ * Hermetic provider for tests: exercises the exact same bridge path+ * (context → tool round-trips through the browser → streamed reply)+ * without spending any tokens.+ */+async function runFake(emit: UIChunkWriter["write"], sessionKey: string, userText: string) {+ const say = (id: string, text: string) => {+ emit({ type: "text-start", id });+ emit({ type: "text-delta", id, delta: text });+ emit({ type: "text-end", id });+ };+ emit({ type: "data-session", data: { providerSession: "test-thread" }, transient: true });+ if (/first frame/i.test(userText)) {+ const r = await callBrowserTool(sessionKey, "freeze_frame", { duration: 1 });+ say("t1", r.errorText ? `Tool failed: ${r.errorText}` : "Done: FREEZEMARK frame pinned to the start.");+ return;+ }+ say("t1", "Let me check what's selected.");+ const st = await callBrowserTool(sessionKey, "get_state", {});+ if (st.errorText !== undefined) {+ emit({ type: "error", errorText: st.errorText });+ return;+ }+ const state = st.output as {+ selection?: { kind: string; id: string } | null;+ };+ if (state.selection?.kind === "text") {+ const r = await callBrowserTool(sessionKey, "update_title", {+ id: state.selection.id,+ text: "TESTMARK improved",+ color: "#FFD60A",+ });+ say("t2", r.errorText ? `Tool failed: ${r.errorText}` : "Done: TESTMARK applied to your title.");+ } else {+ const r = await callBrowserTool(sessionKey, "add_title", { text: "TESTMARK title" });+ say("t2", r.errorText ? `Tool failed: ${r.errorText}` : "Done: TESTMARK title added.");+ }+}diff --git a/site/src/app/api/ai/models/route.ts b/site/src/app/api/ai/models/route.tsnew file mode 100644index 00000000..f0c83b76--- /dev/null+++ b/site/src/app/api/ai/models/route.ts@@ -0,0 +1,53 @@+import { execFile } from "node:child_process";+import { NextResponse } from "next/server";++export const runtime = "nodejs";++import { AI_MODELS } from "@/cut/server/ai/models";++function probe(cmd: string, args: string[]): Promise<{ ok: boolean; note: string }> {+ return new Promise((resolve) => {+ execFile(cmd, args, { timeout: 8000 }, (err, stdout, stderr) => {+ if (err) {+ const note = err.message.includes("ENOENT")+ ? `${cmd} is not installed`+ : (stderr || err.message).trim().split("\n")[0];+ resolve({ ok: false, note });+ } else {+ // Some CLIs (codex) report status on stderr.+ resolve({ ok: true, note: (stdout.trim() || stderr.trim()).split("\n")[0] });+ }+ });+ });+}++// Providers rarely change mid-session; cache probes for a minute.+const g = globalThis as unknown as {+ __veditorAiProbe?: { at: number; value: { claude: { ok: boolean; note: string }; codex: { ok: boolean; note: string } } };+};++export async function GET() {+ const cached = g.__veditorAiProbe;+ let value = cached && Date.now() - cached.at < 60_000 ? cached.value : null;+ if (!value) {+ const [claude, codexLogin] = await Promise.all([+ probe("claude", ["--version"]),+ probe("codex", ["login", "status"]),+ ]);+ const codex = codexLogin.ok+ ? /logged in/i.test(codexLogin.note)+ ? { ok: true, note: codexLogin.note }+ : { ok: false, note: "Not signed in — run: codex login" }+ : codexLogin;+ value = { claude, codex };+ g.__veditorAiProbe = { at: Date.now(), value };+ }+ return NextResponse.json({+ models: AI_MODELS,+ providers: {+ claude: { available: value.claude.ok, note: value.claude.note },+ codex: { available: value.codex.ok, note: value.codex.note },+ test: { available: true, note: "hermetic test provider" },+ },+ });+}diff --git a/site/src/app/api/ai/proxy/route.ts b/site/src/app/api/ai/proxy/route.tsnew file mode 100644index 00000000..91bdf0cb--- /dev/null+++ b/site/src/app/api/ai/proxy/route.ts@@ -0,0 +1,59 @@+import { NextResponse } from "next/server";++export const runtime = "nodejs";++import { callBrowserTool } from "@/cut/server/ai/bridge";+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS } from "@/cut/server/ai/catalog";++/** MCP-shaped tool catalog for the stdio proxy. */+export async function GET(req: Request) {+ const type = new URL(req.url).searchParams.get("type");+ if (type !== "catalog") return NextResponse.json({ error: "Bad request." }, { status: 400 });+ return NextResponse.json({+ tools: AI_TOOLS.map((t) => ({+ name: t.name,+ description: t.description,+ inputSchema: t.inputSchema,+ })),+ });+}++const text = (value: unknown) => ({+ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }],+});++/** Execute one tool call: server-side skills directly, editor tools via the browser. */+export async function POST(req: Request) {+ const { sessionKey, name, args } = (await req.json()) as {+ sessionKey?: string;+ name?: string;+ args?: Record<string, unknown>;+ };+ const def = AI_TOOLS.find((t) => t.name === name);+ if (!name || !def) {+ return NextResponse.json({ ...text(`Unknown tool: ${name}`), isError: true });+ }++ if (def.server) {+ if (name === "list_skills") return NextResponse.json(text({ skills: AI_SKILL_INDEX }));+ if (name === "read_skill") {+ const doc = AI_SKILLS[String(args?.name ?? "")];+ return doc+ ? NextResponse.json(text(doc))+ : NextResponse.json({ ...text(`No such skill. Available: ${AI_SKILL_INDEX.join(", ")}`), isError: true });+ }+ }++ const result = await callBrowserTool(String(sessionKey ?? ""), name, args ?? {});+ if (result.errorText !== undefined) {+ return NextResponse.json({ ...text(result.errorText), isError: true });+ }+ // Screenshots come back as data URLs; hand them to the model as images.+ const out = result.output as { image?: string } | undefined;+ if (name === "capture_frame" && out?.image?.startsWith("data:image/")) {+ const [head, data] = out.image.split(",", 2);+ const mimeType = head.slice(5, head.indexOf(";"));+ return NextResponse.json({ content: [{ type: "image", data, mimeType }] });+ }+ return NextResponse.json(text(result.output ?? { ok: true }));+}diff --git a/site/src/app/api/ai/tool-result/route.ts b/site/src/app/api/ai/tool-result/route.tsnew file mode 100644index 00000000..6a33bb05--- /dev/null+++ b/site/src/app/api/ai/tool-result/route.ts@@ -0,0 +1,20 @@+import { NextResponse } from "next/server";++export const runtime = "nodejs";++import { resolveBrowserTool } from "@/cut/server/ai/bridge";++/** The browser posts tool outputs here after executing them on the store. */+export async function POST(req: Request) {+ const { sessionKey, toolCallId, output, errorText } = (await req.json()) as {+ sessionKey?: string;+ toolCallId?: string;+ output?: unknown;+ errorText?: string;+ };+ if (!sessionKey || !toolCallId) {+ return NextResponse.json({ error: "sessionKey and toolCallId required." }, { status: 400 });+ }+ const ok = resolveBrowserTool(sessionKey, toolCallId, { output, errorText });+ return NextResponse.json({ ok });+}diff --git a/site/src/app/api/export/[jobId]/file/route.ts b/site/src/app/api/export/[jobId]/file/route.tsnew file mode 100644index 00000000..aff84e0b--- /dev/null+++ b/site/src/app/api/export/[jobId]/file/route.ts@@ -0,0 +1,19 @@+import { getJob } from "@/cut/server/jobs";+import { serveFileRange } from "@/cut/server/serveFile";++export const runtime = "nodejs";++export async function GET(+ req: Request,+ { params }: { params: Promise<{ jobId: string }> }+) {+ const { jobId } = await params;+ const job = getJob(jobId);+ if (!job || job.status !== "done") {+ return new Response("Export not ready.", { status: 404 });+ }+ return serveFileRange(job.outPath, req, {+ contentType: "video/mp4",+ downloadName: job.outName,+ });+}diff --git a/site/src/app/api/export/[jobId]/route.ts b/site/src/app/api/export/[jobId]/route.tsnew file mode 100644index 00000000..b303234d--- /dev/null+++ b/site/src/app/api/export/[jobId]/route.ts@@ -0,0 +1,28 @@+import { NextResponse } from "next/server";+import { cancelJob, getJob } from "@/cut/server/jobs";++export const runtime = "nodejs";++export async function GET(+ _req: Request,+ { params }: { params: Promise<{ jobId: string }> }+) {+ const { jobId } = await params;+ const job = getJob(jobId);+ if (!job) return NextResponse.json({ error: "Unknown export." }, { status: 404 });+ return NextResponse.json({+ status: job.status,+ progress: job.progress,+ error: job.error,+ outName: job.outName,+ });+}++export async function DELETE(+ _req: Request,+ { params }: { params: Promise<{ jobId: string }> }+) {+ const { jobId } = await params;+ cancelJob(jobId);+ return NextResponse.json({ ok: true });+}diff --git a/site/src/app/api/export/route.ts b/site/src/app/api/export/route.tsnew file mode 100644index 00000000..a479e02b--- /dev/null+++ b/site/src/app/api/export/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";+import { createJob } from "@/cut/server/jobs";++export const runtime = "nodejs";+export const maxDuration = 600;++export async function POST(req: Request) {+ try {+ const form = await req.formData();+ const job = await createJob(form);+ if (job.status === "error") {+ return NextResponse.json({ error: job.error }, { status: 400 });+ }+ return NextResponse.json({ id: job.id });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Export failed to start." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/library/[id]/route.ts b/site/src/app/api/library/[id]/route.tsnew file mode 100644index 00000000..ac344138--- /dev/null+++ b/site/src/app/api/library/[id]/route.ts@@ -0,0 +1,20 @@+import { NextResponse } from "next/server";+import { removeAsset } from "@/cut/server/library";++export const runtime = "nodejs";++export async function DELETE(+ _req: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;+ try {+ await removeAsset(id);+ return NextResponse.json({ ok: true });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not delete." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/library/media/[file]/route.ts b/site/src/app/api/library/media/[file]/route.tsnew file mode 100644index 00000000..9f14237d--- /dev/null+++ b/site/src/app/api/library/media/[file]/route.ts@@ -0,0 +1,19 @@+import { libMediaPath } from "@/cut/server/library";+import { serveFileRange } from "@/cut/server/serveFile";++export const runtime = "nodejs";++/** Serve a raw library media file with Range support. */+export async function GET(+ req: Request,+ { params }: { params: Promise<{ file: string }> }+) {+ const { file } = await params;+ let p: string;+ try {+ p = libMediaPath(decodeURIComponent(file));+ } catch {+ return new Response("Bad request.", { status: 400 });+ }+ return serveFileRange(p, req);+}diff --git a/site/src/app/api/library/route.ts b/site/src/app/api/library/route.tsnew file mode 100644index 00000000..d0d4851f--- /dev/null+++ b/site/src/app/api/library/route.ts@@ -0,0 +1,25 @@+import { NextResponse } from "next/server";+import { addUpload, listLibrary } from "@/cut/server/library";++export const runtime = "nodejs";+export const maxDuration = 300;++export async function GET() {+ return NextResponse.json(await listLibrary());+}++export async function POST(req: Request) {+ try {+ const form = await req.formData();+ const file = form.get("file");+ if (!(file instanceof File)) {+ return NextResponse.json({ error: "No file in upload." }, { status: 400 });+ }+ return NextResponse.json(await addUpload(file));+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Upload failed." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/library/save/route.ts b/site/src/app/api/library/save/route.tsnew file mode 100644index 00000000..ccbe9672--- /dev/null+++ b/site/src/app/api/library/save/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";+import { addFromProject } from "@/cut/server/library";++export const runtime = "nodejs";++/** Copy a project media file into the shared library. */+export async function POST(req: Request) {+ try {+ const { projectId, fileName, name } = (await req.json()) as {+ projectId: string;+ fileName: string;+ name?: string;+ };+ return NextResponse.json(await addFromProject(projectId, fileName, name ?? fileName));+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not save to library." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/library/use/route.ts b/site/src/app/api/library/use/route.tsnew file mode 100644index 00000000..f64bac62--- /dev/null+++ b/site/src/app/api/library/use/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";+import { useInProject } from "@/cut/server/library";++export const runtime = "nodejs";++/** Copy a library asset into a project's media folder. */+export async function POST(req: Request) {+ try {+ const { assetId, projectId } = (await req.json()) as {+ assetId: string;+ projectId: string;+ };+ const fileName = await useInProject(assetId, projectId);+ return NextResponse.json({ fileName });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not add from library." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/projects/[id]/exports/[file]/route.ts b/site/src/app/api/projects/[id]/exports/[file]/route.tsnew file mode 100644index 00000000..45eb4962--- /dev/null+++ b/site/src/app/api/projects/[id]/exports/[file]/route.ts@@ -0,0 +1,20 @@+import { exportPath } from "@/cut/server/projects";+import { serveFileRange } from "@/cut/server/serveFile";++export const runtime = "nodejs";++/** Serve a rendered export from the project folder, with Range support so+ * the platform-preview player can seek. */+export async function GET(+ req: Request,+ { params }: { params: Promise<{ id: string; file: string }> }+) {+ const { id, file } = await params;+ let p: string;+ try {+ p = exportPath(id, decodeURIComponent(file));+ } catch {+ return new Response("Bad request.", { status: 400 });+ }+ return serveFileRange(p, req, { contentType: "video/mp4" });+}diff --git a/site/src/app/api/projects/[id]/exports/route.ts b/site/src/app/api/projects/[id]/exports/route.tsnew file mode 100644index 00000000..a99d1982--- /dev/null+++ b/site/src/app/api/projects/[id]/exports/route.ts@@ -0,0 +1,14 @@+import { NextResponse } from "next/server";+import { listExports } from "@/cut/server/projects";++export const runtime = "nodejs";++/** Rendered exports for a project, newest first. */+export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ try {+ return NextResponse.json(await listExports(id));+ } catch {+ return NextResponse.json({ error: "Invalid project." }, { status: 400 });+ }+}diff --git a/site/src/app/api/projects/[id]/freeze/route.ts b/site/src/app/api/projects/[id]/freeze/route.tsnew file mode 100644index 00000000..89a7ebb2--- /dev/null+++ b/site/src/app/api/projects/[id]/freeze/route.ts@@ -0,0 +1,52 @@+import { NextResponse } from "next/server";++export const runtime = "nodejs";++import { makeFreezeFrame } from "@/cut/server/frames";+import { readProject } from "@/cut/server/projects";++/** Render a freeze-frame still clip from a media file's frame. */+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ try {+ if (!(await readProject(id))) {+ return NextResponse.json({ error: "Project not found." }, { status: 404 });+ }+ const body = (await req.json()) as {+ file?: string;+ srcTime?: number;+ duration?: number;+ frame?: { w?: number; h?: number };+ framing?: { fit?: "fit" | "fill"; panX?: number; panY?: number };+ };+ if (!body.file || typeof body.srcTime !== "number") {+ return NextResponse.json({ error: "file and srcTime are required." }, { status: 400 });+ }+ const frame =+ typeof body.frame?.w === "number" && typeof body.frame?.h === "number"+ ? { w: Math.round(body.frame.w), h: Math.round(body.frame.h) }+ : undefined;+ const framing = frame+ ? {+ fit: body.framing?.fit === "fill" ? ("fill" as const) : ("fit" as const),+ panX: typeof body.framing?.panX === "number" ? body.framing.panX : 0,+ panY: typeof body.framing?.panY === "number" ? body.framing.panY : 0,+ }+ : undefined;+ const made = await makeFreezeFrame(id, body.file, body.srcTime, body.duration ?? 1, frame, framing);+ return NextResponse.json({+ id: crypto.randomUUID().slice(0, 8),+ fileName: made.fileName,+ name: made.fileName,+ type: "video",+ duration: made.duration,+ width: made.width,+ height: made.height,+ });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : String(err) },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/projects/[id]/media/[file]/route.ts b/site/src/app/api/projects/[id]/media/[file]/route.tsnew file mode 100644index 00000000..093ee6f6--- /dev/null+++ b/site/src/app/api/projects/[id]/media/[file]/route.ts@@ -0,0 +1,20 @@+import { mediaPath } from "@/cut/server/projects";+import { serveFileRange } from "@/cut/server/serveFile";++export const runtime = "nodejs";++/** Serve a raw media file from the project folder, with Range support so+ * <video>/<audio> elements can seek efficiently. */+export async function GET(+ req: Request,+ { params }: { params: Promise<{ id: string; file: string }> }+) {+ const { id, file } = await params;+ let p: string;+ try {+ p = mediaPath(id, decodeURIComponent(file));+ } catch {+ return new Response("Bad request.", { status: 400 });+ }+ return serveFileRange(p, req);+}diff --git a/site/src/app/api/projects/[id]/media/route.ts b/site/src/app/api/projects/[id]/media/route.tsnew file mode 100644index 00000000..624d0fad--- /dev/null+++ b/site/src/app/api/projects/[id]/media/route.ts@@ -0,0 +1,29 @@+import { NextResponse } from "next/server";+import { readProject, saveMedia } from "@/cut/server/projects";++export const runtime = "nodejs";+export const maxDuration = 300;++export async function POST(+ req: Request,+ { params }: { params: Promise<{ id: string }> }+) {+ const { id } = await params;+ try {+ if (!(await readProject(id))) {+ return NextResponse.json({ error: "Project not found." }, { status: 404 });+ }+ const form = await req.formData();+ const file = form.get("file");+ if (!(file instanceof File)) {+ return NextResponse.json({ error: "No file in upload." }, { status: 400 });+ }+ const fileName = await saveMedia(id, file);+ return NextResponse.json({ fileName });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Upload failed." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/projects/[id]/route.ts b/site/src/app/api/projects/[id]/route.tsnew file mode 100644index 00000000..847899ee--- /dev/null+++ b/site/src/app/api/projects/[id]/route.ts@@ -0,0 +1,64 @@+import { NextResponse } from "next/server";+import type { ProjectDoc } from "@/cut/lib/types";+import { deleteProject, readProject, writeProject } from "@/cut/server/projects";++export const runtime = "nodejs";++type Ctx = { params: Promise<{ id: string }> };++export async function GET(_req: Request, { params }: Ctx) {+ const { id } = await params;+ const doc = await readProject(id).catch(() => null);+ if (!doc) return NextResponse.json({ error: "Project not found." }, { status: 404 });+ return NextResponse.json(doc);+}++export async function PUT(req: Request, { params }: Ctx) {+ const { id } = await params;+ try {+ const existing = await readProject(id);+ if (!existing) return NextResponse.json({ error: "Project not found." }, { status: 404 });+ const body = (await req.json()) as Partial<ProjectDoc>;+ const doc: ProjectDoc = {+ ...existing,+ name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing.name,+ assets: Array.isArray(body.assets) ? body.assets : existing.assets,+ clips: Array.isArray(body.clips) ? body.clips : existing.clips,+ audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,+ overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ subtitles:+ body.subtitles && typeof body.subtitles === "object"+ ? body.subtitles+ : existing.subtitles,+ // Per-project view metadata (timeline zoom, …) — not part of the cut.+ ui:+ body.ui && typeof body.ui === "object"+ ? { ...existing.ui, ...body.ui }+ : existing.ui,+ publish:+ body.publish && typeof body.publish === "object"+ ? { ...existing.publish, ...body.publish }+ : existing.publish,+ };+ await writeProject(id, doc);+ return NextResponse.json({ ok: true, updatedAt: doc.updatedAt });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not save project." },+ { status: 500 }+ );+ }+}++export async function DELETE(_req: Request, { params }: Ctx) {+ const { id } = await params;+ try {+ await deleteProject(id);+ return NextResponse.json({ ok: true });+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not delete project." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/api/projects/[id]/transcribe/route.ts b/site/src/app/api/projects/[id]/transcribe/route.tsnew file mode 100644index 00000000..7042254e--- /dev/null+++ b/site/src/app/api/projects/[id]/transcribe/route.ts@@ -0,0 +1,41 @@+import { NextResponse } from "next/server";++export const runtime = "nodejs";++import {+ createTranscribeJob,+ getTranscribeJob,+ type TranscribeSpec,+} from "@/cut/server/transcribe";++/** Start a background transcription of the current cut. */+export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ try {+ const body = (await req.json()) as Omit<TranscribeSpec, "projectId">;+ if (!Array.isArray(body.clips) || typeof body.duration !== "number") {+ return NextResponse.json({ error: "Bad transcribe spec." }, { status: 400 });+ }+ const job = await createTranscribeJob({ ...body, projectId: id });+ return NextResponse.json({ id: job.id });+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ return NextResponse.json({ error: message }, { status: 500 });+ }+}++/** Poll a transcription job: ?job=<id> */+export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ const jobId = new URL(req.url).searchParams.get("job");+ const job = jobId ? getTranscribeJob(jobId) : undefined;+ if (!job || job.projectId !== id) {+ return NextResponse.json({ error: "Unknown transcription job." }, { status: 404 });+ }+ return NextResponse.json({+ status: job.status,+ stage: job.stage,+ error: job.error,+ cues: job.status === "done" ? job.cues : undefined,+ });+}diff --git a/site/src/app/api/projects/route.ts b/site/src/app/api/projects/route.tsnew file mode 100644index 00000000..bd162a88--- /dev/null+++ b/site/src/app/api/projects/route.ts@@ -0,0 +1,21 @@+import { NextResponse } from "next/server";+import { createProject, listProjects } from "@/cut/server/projects";++export const runtime = "nodejs";++export async function GET() {+ return NextResponse.json(await listProjects());+}++export async function POST(req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const project = await createProject(name ?? "Untitled");+ return NextResponse.json(project);+ } catch (err) {+ return NextResponse.json(+ { error: err instanceof Error ? err.message : "Could not create project." },+ { status: 500 }+ );+ }+}diff --git a/site/src/app/cut/(home)/layout.tsx b/site/src/app/cut/(home)/layout.tsxnew file mode 100644index 00000000..2c82b66d--- /dev/null+++ b/site/src/app/cut/(home)/layout.tsx@@ -0,0 +1,10 @@+import { AppSidebar } from "@/cut/components/AppSidebar";++export default function HomeLayout({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex min-h-screen bg-background">+ <AppSidebar />+ <main className="min-w-0 flex-1">{children}</main>+ </div>+ );+}diff --git a/site/src/app/cut/(home)/library/page.tsx b/site/src/app/cut/(home)/library/page.tsxnew file mode 100644index 00000000..0d2b15d5--- /dev/null+++ b/site/src/app/cut/(home)/library/page.tsx@@ -0,0 +1,5 @@+import { LibraryView } from "@/cut/components/LibraryView";++export default function LibraryPage() {+ return <LibraryView />;+}diff --git a/site/src/app/cut/(home)/page.tsx b/site/src/app/cut/(home)/page.tsxnew file mode 100644index 00000000..e9a1e51b--- /dev/null+++ b/site/src/app/cut/(home)/page.tsx@@ -0,0 +1,5 @@+import { ProjectsHome } from "@/cut/components/ProjectsHome";++export default function Home() {+ return <ProjectsHome />;+}diff --git a/site/src/app/cut/layout.tsx b/site/src/app/cut/layout.tsxnew file mode 100644index 00000000..c999be14--- /dev/null+++ b/site/src/app/cut/layout.tsx@@ -0,0 +1,16 @@+import type { ReactNode } from "react";++import { AppSurfaceBackground } from "@/app/app/_components/AppSurfaceBackground";++// Cut (the video editor) renders on the same white product surface as Donkey's+// /app, not the cream marketing background. AppSurfaceBackground paints the root+// html white so the cream landing background does not show through the overscroll+// area, and font-system matches the /app system font stack.+export default function CutLayout({ children }: { children: ReactNode }) {+ return (+ <div className="min-h-screen bg-white font-system text-foreground antialiased">+ <AppSurfaceBackground />+ {children}+ </div>+ );+}diff --git a/site/src/app/cut/p/[id]/page.tsx b/site/src/app/cut/p/[id]/page.tsxnew file mode 100644index 00000000..a1633b87--- /dev/null+++ b/site/src/app/cut/p/[id]/page.tsx@@ -0,0 +1,10 @@+import { Editor } from "@/cut/components/Editor";++export default async function ProjectPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;+ return <Editor projectId={id} />;+}diff --git a/site/src/components/ui/alert-dialog.tsx b/site/src/components/ui/alert-dialog.tsxnew file mode 100644index 00000000..0ee2c5f4--- /dev/null+++ b/site/src/components/ui/alert-dialog.tsx@@ -0,0 +1,187 @@+"use client"++import * as React from "react"+import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"++import { cn } from "@/lib/utils"+import { Button } from "@/components/ui/button"++function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {+ return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />+}++function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {+ return (+ <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />+ )+}++function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) {+ return (+ <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />+ )+}++function AlertDialogOverlay({+ className,+ ...props+}: AlertDialogPrimitive.Backdrop.Props) {+ return (+ <AlertDialogPrimitive.Backdrop+ data-slot="alert-dialog-overlay"+ className={cn(+ "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogContent({+ className,+ size = "default",+ ...props+}: AlertDialogPrimitive.Popup.Props & {+ size?: "default" | "sm"+}) {+ return (+ <AlertDialogPortal>+ <AlertDialogOverlay />+ <AlertDialogPrimitive.Popup+ data-slot="alert-dialog-content"+ data-size={size}+ className={cn(+ "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ className+ )}+ {...props}+ />+ </AlertDialogPortal>+ )+}++function AlertDialogHeader({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="alert-dialog-header"+ className={cn(+ "grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogFooter({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="alert-dialog-footer"+ className={cn(+ "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogMedia({+ className,+ ...props+}: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="alert-dialog-media"+ className={cn(+ "mb-2 inline-flex size-10 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogTitle({+ className,+ ...props+}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {+ return (+ <AlertDialogPrimitive.Title+ data-slot="alert-dialog-title"+ className={cn(+ "font-heading text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogDescription({+ className,+ ...props+}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {+ return (+ <AlertDialogPrimitive.Description+ data-slot="alert-dialog-description"+ className={cn(+ "text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",+ className+ )}+ {...props}+ />+ )+}++function AlertDialogAction({+ className,+ ...props+}: React.ComponentProps<typeof Button>) {+ return (+ <Button+ data-slot="alert-dialog-action"+ className={cn(className)}+ {...props}+ />+ )+}++function AlertDialogCancel({+ className,+ variant = "outline",+ size = "default",+ ...props+}: AlertDialogPrimitive.Close.Props &+ Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {+ return (+ <AlertDialogPrimitive.Close+ data-slot="alert-dialog-cancel"+ className={cn(className)}+ render={<Button variant={variant} size={size} />}+ {...props}+ />+ )+}++export {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogOverlay,+ AlertDialogPortal,+ AlertDialogTitle,+ AlertDialogTrigger,+}diff --git a/site/src/components/ui/dropdown-menu.tsx b/site/src/components/ui/dropdown-menu.tsxnew file mode 100644index 00000000..9d5ebbd2--- /dev/null+++ b/site/src/components/ui/dropdown-menu.tsx@@ -0,0 +1,268 @@+"use client"++import * as React from "react"+import { Menu as MenuPrimitive } from "@base-ui/react/menu"++import { cn } from "@/lib/utils"+import { ChevronRightIcon, CheckIcon } from "lucide-react"++function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {+ return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />+}++function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {+ return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />+}++function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {+ return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />+}++function DropdownMenuContent({+ align = "start",+ alignOffset = 0,+ side = "bottom",+ sideOffset = 4,+ className,+ ...props+}: MenuPrimitive.Popup.Props &+ Pick<+ MenuPrimitive.Positioner.Props,+ "align" | "alignOffset" | "side" | "sideOffset"+ >) {+ return (+ <MenuPrimitive.Portal>+ <MenuPrimitive.Positioner+ className="isolate z-50 outline-none"+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ >+ <MenuPrimitive.Popup+ data-slot="dropdown-menu-content"+ className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ {...props}+ />+ </MenuPrimitive.Positioner>+ </MenuPrimitive.Portal>+ )+}++function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {+ return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />+}++function DropdownMenuLabel({+ className,+ inset,+ ...props+}: MenuPrimitive.GroupLabel.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.GroupLabel+ data-slot="dropdown-menu-label"+ data-inset={inset}+ className={cn(+ "px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",+ className+ )}+ {...props}+ />+ )+}++function DropdownMenuItem({+ className,+ inset,+ variant = "default",+ ...props+}: MenuPrimitive.Item.Props & {+ inset?: boolean+ variant?: "default" | "destructive"+}) {+ return (+ <MenuPrimitive.Item+ data-slot="dropdown-menu-item"+ data-inset={inset}+ data-variant={variant}+ className={cn(+ "group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",+ className+ )}+ {...props}+ />+ )+}++function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {+ return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />+}++function DropdownMenuSubTrigger({+ className,+ inset,+ children,+ ...props+}: MenuPrimitive.SubmenuTrigger.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.SubmenuTrigger+ data-slot="dropdown-menu-sub-trigger"+ data-inset={inset}+ className={cn(+ "flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ {children}+ <ChevronRightIcon className="ml-auto" />+ </MenuPrimitive.SubmenuTrigger>+ )+}++function DropdownMenuSubContent({+ align = "start",+ alignOffset = -3,+ side = "right",+ sideOffset = 0,+ className,+ ...props+}: React.ComponentProps<typeof DropdownMenuContent>) {+ return (+ <DropdownMenuContent+ data-slot="dropdown-menu-sub-content"+ className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ align={align}+ alignOffset={alignOffset}+ side={side}+ sideOffset={sideOffset}+ {...props}+ />+ )+}++function DropdownMenuCheckboxItem({+ className,+ children,+ checked,+ inset,+ ...props+}: MenuPrimitive.CheckboxItem.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.CheckboxItem+ data-slot="dropdown-menu-checkbox-item"+ data-inset={inset}+ className={cn(+ "relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ checked={checked}+ {...props}+ >+ <span+ className="pointer-events-none absolute right-2 flex items-center justify-center"+ data-slot="dropdown-menu-checkbox-item-indicator"+ >+ <MenuPrimitive.CheckboxItemIndicator>+ <CheckIcon+ />+ </MenuPrimitive.CheckboxItemIndicator>+ </span>+ {children}+ </MenuPrimitive.CheckboxItem>+ )+}++function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {+ return (+ <MenuPrimitive.RadioGroup+ data-slot="dropdown-menu-radio-group"+ {...props}+ />+ )+}++function DropdownMenuRadioItem({+ className,+ children,+ inset,+ ...props+}: MenuPrimitive.RadioItem.Props & {+ inset?: boolean+}) {+ return (+ <MenuPrimitive.RadioItem+ data-slot="dropdown-menu-radio-item"+ data-inset={inset}+ className={cn(+ "relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ <span+ className="pointer-events-none absolute right-2 flex items-center justify-center"+ data-slot="dropdown-menu-radio-item-indicator"+ >+ <MenuPrimitive.RadioItemIndicator>+ <CheckIcon+ />+ </MenuPrimitive.RadioItemIndicator>+ </span>+ {children}+ </MenuPrimitive.RadioItem>+ )+}++function DropdownMenuSeparator({+ className,+ ...props+}: MenuPrimitive.Separator.Props) {+ return (+ <MenuPrimitive.Separator+ data-slot="dropdown-menu-separator"+ className={cn("-mx-1 my-1 h-px bg-border", className)}+ {...props}+ />+ )+}++function DropdownMenuShortcut({+ className,+ ...props+}: React.ComponentProps<"span">) {+ return (+ <span+ data-slot="dropdown-menu-shortcut"+ className={cn(+ "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",+ className+ )}+ {...props}+ />+ )+}++export {+ DropdownMenu,+ DropdownMenuPortal,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuItem,+ DropdownMenuCheckboxItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+}diff --git a/site/src/components/ui/select.tsx b/site/src/components/ui/select.tsxnew file mode 100644index 00000000..e8021f5f--- /dev/null+++ b/site/src/components/ui/select.tsx@@ -0,0 +1,201 @@+"use client"++import * as React from "react"+import { Select as SelectPrimitive } from "@base-ui/react/select"++import { cn } from "@/lib/utils"+import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"++const Select = SelectPrimitive.Root++function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {+ return (+ <SelectPrimitive.Group+ data-slot="select-group"+ className={cn("scroll-my-1 p-1", className)}+ {...props}+ />+ )+}++function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {+ return (+ <SelectPrimitive.Value+ data-slot="select-value"+ className={cn("flex flex-1 text-left", className)}+ {...props}+ />+ )+}++function SelectTrigger({+ className,+ size = "default",+ children,+ ...props+}: SelectPrimitive.Trigger.Props & {+ size?: "sm" | "default"+}) {+ return (+ <SelectPrimitive.Trigger+ data-slot="select-trigger"+ data-size={size}+ className={cn(+ "flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ {children}+ <SelectPrimitive.Icon+ render={+ <ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />+ }+ />+ </SelectPrimitive.Trigger>+ )+}++function SelectContent({+ className,+ children,+ side = "bottom",+ sideOffset = 4,+ align = "center",+ alignOffset = 0,+ alignItemWithTrigger = true,+ ...props+}: SelectPrimitive.Popup.Props &+ Pick<+ SelectPrimitive.Positioner.Props,+ "align" | "alignOffset" | "side" | "sideOffset" | "alignItemWithTrigger"+ >) {+ return (+ <SelectPrimitive.Portal>+ <SelectPrimitive.Positioner+ side={side}+ sideOffset={sideOffset}+ align={align}+ alignOffset={alignOffset}+ alignItemWithTrigger={alignItemWithTrigger}+ className="isolate z-50"+ >+ <SelectPrimitive.Popup+ data-slot="select-content"+ data-align-trigger={alignItemWithTrigger}+ className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}+ {...props}+ >+ <SelectScrollUpButton />+ <SelectPrimitive.List>{children}</SelectPrimitive.List>+ <SelectScrollDownButton />+ </SelectPrimitive.Popup>+ </SelectPrimitive.Positioner>+ </SelectPrimitive.Portal>+ )+}++function SelectLabel({+ className,+ ...props+}: SelectPrimitive.GroupLabel.Props) {+ return (+ <SelectPrimitive.GroupLabel+ data-slot="select-label"+ className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}+ {...props}+ />+ )+}++function SelectItem({+ className,+ children,+ ...props+}: SelectPrimitive.Item.Props) {+ return (+ <SelectPrimitive.Item+ data-slot="select-item"+ className={cn(+ "relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",+ className+ )}+ {...props}+ >+ <SelectPrimitive.ItemText className="flex flex-1 shrink-0 gap-2 whitespace-nowrap">+ {children}+ </SelectPrimitive.ItemText>+ <SelectPrimitive.ItemIndicator+ render={+ <span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />+ }+ >+ <CheckIcon className="pointer-events-none" />+ </SelectPrimitive.ItemIndicator>+ </SelectPrimitive.Item>+ )+}++function SelectSeparator({+ className,+ ...props+}: SelectPrimitive.Separator.Props) {+ return (+ <SelectPrimitive.Separator+ data-slot="select-separator"+ className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}+ {...props}+ />+ )+}++function SelectScrollUpButton({+ className,+ ...props+}: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {+ return (+ <SelectPrimitive.ScrollUpArrow+ data-slot="select-scroll-up-button"+ className={cn(+ "top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ <ChevronUpIcon+ />+ </SelectPrimitive.ScrollUpArrow>+ )+}++function SelectScrollDownButton({+ className,+ ...props+}: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {+ return (+ <SelectPrimitive.ScrollDownArrow+ data-slot="select-scroll-down-button"+ className={cn(+ "bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ >+ <ChevronDownIcon+ />+ </SelectPrimitive.ScrollDownArrow>+ )+}++export {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectScrollDownButton,+ SelectScrollUpButton,+ SelectSeparator,+ SelectTrigger,+ SelectValue,+}diff --git a/site/src/components/ui/slider.tsx b/site/src/components/ui/slider.tsxnew file mode 100644index 00000000..691fff38--- /dev/null+++ b/site/src/components/ui/slider.tsx@@ -0,0 +1,52 @@+import { Slider as SliderPrimitive } from "@base-ui/react/slider"++import { cn } from "@/lib/utils"++function Slider({+ className,+ defaultValue,+ value,+ min = 0,+ max = 100,+ ...props+}: SliderPrimitive.Root.Props) {+ const _values = Array.isArray(value)+ ? value+ : Array.isArray(defaultValue)+ ? defaultValue+ : [min, max]++ return (+ <SliderPrimitive.Root+ className={cn("data-horizontal:w-full data-vertical:h-full", className)}+ data-slot="slider"+ defaultValue={defaultValue}+ value={value}+ min={min}+ max={max}+ thumbAlignment="edge"+ {...props}+ >+ <SliderPrimitive.Control className="relative flex w-full touch-none items-center select-none data-disabled:opacity-50 data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-col">+ <SliderPrimitive.Track+ data-slot="slider-track"+ className="relative grow overflow-hidden rounded-full bg-muted select-none data-horizontal:h-1 data-horizontal:w-full data-vertical:h-full data-vertical:w-1"+ >+ <SliderPrimitive.Indicator+ data-slot="slider-range"+ className="bg-primary select-none data-horizontal:h-full data-vertical:w-full"+ />+ </SliderPrimitive.Track>+ {Array.from({ length: _values.length }, (_, index) => (+ <SliderPrimitive.Thumb+ data-slot="slider-thumb"+ key={index}+ className="relative block size-3 shrink-0 rounded-full border border-ring bg-white ring-ring/50 transition-[color,box-shadow] select-none after:absolute after:-inset-2 hover:ring-3 focus-visible:ring-3 focus-visible:outline-hidden active:ring-3 disabled:pointer-events-none disabled:opacity-50"+ />+ ))}+ </SliderPrimitive.Control>+ </SliderPrimitive.Root>+ )+}++export { Slider }diff --git a/site/src/components/ui/switch.tsx b/site/src/components/ui/switch.tsxnew file mode 100644index 00000000..9b8b44b1--- /dev/null+++ b/site/src/components/ui/switch.tsx@@ -0,0 +1,32 @@+"use client"++import { Switch as SwitchPrimitive } from "@base-ui/react/switch"++import { cn } from "@/lib/utils"++function Switch({+ className,+ size = "default",+ ...props+}: SwitchPrimitive.Root.Props & {+ size?: "sm" | "default"+}) {+ return (+ <SwitchPrimitive.Root+ data-slot="switch"+ data-size={size}+ className={cn(+ "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50",+ className+ )}+ {...props}+ >+ <SwitchPrimitive.Thumb+ data-slot="switch-thumb"+ className="pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-checked:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-checked:translate-x-[calc(100%-2px)] dark:data-checked:bg-primary-foreground group-data-[size=default]/switch:data-unchecked:translate-x-0 group-data-[size=sm]/switch:data-unchecked:translate-x-0 dark:data-unchecked:bg-foreground"+ />+ </SwitchPrimitive.Root>+ )+}++export { Switch }diff --git a/site/src/components/ui/textarea.tsx b/site/src/components/ui/textarea.tsxnew file mode 100644index 00000000..04d27f7d--- /dev/null+++ b/site/src/components/ui/textarea.tsx@@ -0,0 +1,18 @@+import * as React from "react"++import { cn } from "@/lib/utils"++function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {+ return (+ <textarea+ data-slot="textarea"+ className={cn(+ "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",+ className+ )}+ {...props}+ />+ )+}++export { Textarea }diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxnew file mode 100644index 00000000..6bb95117--- /dev/null+++ b/site/src/cut/components/AiPanel.tsx@@ -0,0 +1,864 @@+"use client";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useChat } from "@ai-sdk/react";+import { DefaultChatTransport, type UIMessage } from "ai";+import {+ ArrowUp,+ Check,+ ChevronDown,+ CircleDashed,+ Ellipsis,+ FolderPlus,+ History,+ Music,+ Plus,+ Sparkles,+ Square,+ Star,+ Trash2,+ TriangleAlert,+ Wrench,+ X,+} from "lucide-react";+import Markdown from "react-markdown";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { buildAiContext } from "@/cut/lib/aiContext";+import { runAiTool } from "@/cut/lib/aiTools";+import { draggedAssetId, hasAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";+import { saveAssetToLibrary } from "@/cut/lib/library";+import { useEditor } from "@/cut/lib/store";+import { formatTime } from "@/cut/lib/time";+import type { AssetType } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++/** Asset reference attached to a chat message — enough to render a card and+ * for the model to act on the asset via its editor tools. */+export interface ChatAsset {+ id: string;+ name: string;+ type: AssetType;+ duration: number;+ url: string;+}++interface AiModel {+ id: string;+ label: string;+ provider: "claude" | "codex" | "test";+ hidden?: boolean;+}++interface ModelsInfo {+ models: AiModel[];+ providers: Record<string, { available: boolean; note: string }>;+}++/** A saved chat thread, persisted per project in localStorage. */+interface ChatThread {+ id: string;+ title: string;+ updatedAt: number;+ messages: UIMessage[];+ /** Provider-native session ids so a resumed thread keeps its context. */+ sessions: Record<string, string>;+}++const THREAD_LIMIT = 30;+const threadsKey = () => `cut-ai-threads-${useEditor.getState().projectId ?? "global"}`;++function readThreads(): ChatThread[] {+ try {+ const v = JSON.parse(localStorage.getItem(threadsKey()) ?? "[]") as unknown;+ return Array.isArray(v) ? (v as ChatThread[]) : [];+ } catch {+ return [];+ }+}++function writeThreads(list: ChatThread[]) {+ try {+ localStorage.setItem(threadsKey(), JSON.stringify(list.slice(0, THREAD_LIMIT)));+ } catch {+ // Storage full/blocked — history just won't persist.+ }+}++const MODEL_KEY = "cut-ai-model";+const FAVS_KEY = "cut-ai-favs";+const PROVIDER_LABEL: Record<string, string> = {+ claude: "Claude Code",+ codex: "Codex",+ test: "Testing",+};++const SUGGESTIONS = [+ "What's in this video?",+ "Make my title punchier",+ "Add subtitles",+ "Write a TikTok caption",+];++/** Chat provider bucket for a model id. */+const provider = (id: string): string =>+ id.startsWith("claude") ? "claude" : id === "cut-test" ? "test" : "codex";++export function AiPanel({ onClose }: { onClose: () => void }) {+ const [info, setInfo] = useState<ModelsInfo | null>(null);+ const [model, setModel] = useState<string>(() =>+ typeof window === "undefined" ? "claude-fable-5" : localStorage.getItem(MODEL_KEY) ?? "claude-fable-5"+ );+ // Concurrent chat sessions: every open chat stays mounted (hidden when not+ // active) so a busy chat keeps streaming while you talk in another one.+ const [openChats, setOpenChats] = useState<string[]>(() => [crypto.randomUUID()]);+ const [active, setActive] = useState<string>(() => openChats[0]);+ const [titles, setTitles] = useState<Record<string, string>>({});+ const [busyMap, setBusyMap] = useState<Record<string, boolean>>({});+ const [historyOpen, setHistoryOpen] = useState(false);+ const [threads, setThreads] = useState<ChatThread[]>([]);++ useEffect(() => {+ let alive = true;+ void fetch("/api/ai/models")+ .then((r) => r.json())+ .then((d: ModelsInfo) => alive && setInfo(d))+ .catch(() => {});+ return () => {+ alive = false;+ };+ }, []);++ const onTitle = useCallback((id: string, title: string) => {+ setTitles((p) => (p[id] === title ? p : { ...p, [id]: title }));+ }, []);+ const onBusy = useCallback((id: string, b: boolean) => {+ setBusyMap((p) => (!!p[id] === b ? p : { ...p, [id]: b }));+ }, []);++ const newChat = () => {+ const id = crypto.randomUUID();+ setOpenChats((p) => [...p, id]);+ setActive(id);+ setHistoryOpen(false);+ };++ const closeChat = (id: string) => {+ const idx = openChats.indexOf(id);+ const next = openChats.filter((x) => x !== id);+ if (next.length === 0) {+ const fresh = crypto.randomUUID();+ setOpenChats([fresh]);+ setActive(fresh);+ return;+ }+ setOpenChats(next);+ if (active === id) setActive(next[Math.min(Math.max(idx - 1, 0), next.length - 1)]);+ };++ const openThreadTab = (t: ChatThread) => {+ if (!openChats.includes(t.id)) setOpenChats((p) => [...p, t.id]);+ setActive(t.id);+ setHistoryOpen(false);+ };++ const toggleHistory = () => {+ if (!historyOpen) setThreads(readThreads());+ setHistoryOpen((v) => !v);+ };++ const deleteThread = (id: string) => {+ writeThreads(readThreads().filter((t) => t.id !== id));+ setThreads((p) => p.filter((t) => t.id !== id));+ // Close its tab too — a still-open chat would re-save itself on the next+ // message and resurrect the thread.+ if (openChats.includes(id)) closeChat(id);+ };++ const selectModel = (id: string) => {+ setModel(id);+ localStorage.setItem(MODEL_KEY, id);+ };++ return (+ <aside className="ai-panel relative flex min-h-0 w-[340px] shrink-0 animate-in flex-col border-l border-border bg-card duration-300 ease-out slide-in-from-right-full">+ <div className="flex h-[46px] shrink-0 items-center gap-1.5 border-b border-border pr-2 pl-3.5">+ <Sparkles className="size-4 text-[#0a84ff]" />+ <div className="flex-1" />+ <Button+ variant="ghost"+ size="sm"+ className="ai-threads"+ title="Past threads"+ aria-pressed={historyOpen}+ onClick={toggleHistory}+ >+ <History />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ className="ai-new-thread"+ title="New chat"+ onClick={newChat}+ >+ <Plus />+ </Button>+ <Button variant="ghost" size="sm" title="Close (⌘J)" onClick={onClose}>+ <X />+ </Button>+ </div>++ {openChats.length > 1 && (+ <div className="ai-chat-tabs flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border px-2 py-1.5">+ {openChats.map((id, i) => (+ <div+ key={id}+ role="tab"+ aria-selected={active === id}+ className={cn(+ "group flex max-w-36 shrink-0 cursor-pointer items-center gap-1 rounded-md px-2 py-1 text-[11px] transition-colors",+ active === id+ ? "bg-muted font-medium text-foreground"+ : "text-muted-foreground hover:bg-muted/60"+ )}+ onClick={() => setActive(id)}+ >+ {busyMap[id] && (+ <CircleDashed className="size-2.5 shrink-0 animate-spin text-[#0a84ff]" />+ )}+ <span className="truncate">{titles[id] ?? `Chat ${i + 1}`}</span>+ <button+ aria-label="Close chat"+ title="Close chat"+ className="rounded p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/10"+ onClick={(e) => {+ e.stopPropagation();+ closeChat(id);+ }}+ >+ <X className="size-3" />+ </button>+ </div>+ ))}+ </div>+ )}++ {historyOpen && (+ <>+ <div className="fixed inset-0 z-30" onClick={() => setHistoryOpen(false)} />+ <div className="ai-thread-list absolute top-0 right-full bottom-0 z-40 flex w-[280px] animate-in flex-col border-x border-border bg-card shadow-[-16px_0_40px_rgba(0,0,0,0.14)] duration-200 ease-out fade-in-0 slide-in-from-right-6">+ <div className="flex h-[46px] shrink-0 items-center justify-between border-b border-border pr-2 pl-3.5">+ <span className="text-sm font-semibold tracking-tight">Threads</span>+ <Button variant="ghost" size="sm" title="Close" onClick={() => setHistoryOpen(false)}>+ <X />+ </Button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-2">+ {threads.length === 0 ? (+ <p className="px-2 py-3 text-[11.5px] leading-relaxed text-muted-foreground">+ No past threads yet.+ </p>+ ) : (+ threads.map((t) => (+ <button+ key={t.id}+ className={cn(+ "group relative flex w-full flex-col gap-0.5 rounded-lg px-2.5 py-2 text-left transition-colors hover:bg-muted",+ openChats.includes(t.id) && "bg-muted/70"+ )}+ onClick={() => openThreadTab(t)}+ >+ <span className="w-full truncate pr-6 text-[12px] font-medium">{t.title}</span>+ <span className="text-[10.5px] text-muted-foreground">+ {new Date(t.updatedAt).toLocaleString([], {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ })}+ </span>+ <span+ role="button"+ aria-label="Delete thread"+ title="Delete thread"+ className="absolute top-1/2 right-1.5 grid size-6 -translate-y-1/2 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/10 hover:text-red-600"+ onClick={(e) => {+ e.stopPropagation();+ deleteThread(t.id);+ }}+ >+ <Trash2 className="size-3.5" />+ </span>+ </button>+ ))+ )}+ </div>+ </div>+ </>+ )}++ {openChats.map((id) => (+ <ChatSession+ key={id}+ threadId={id}+ visible={id === active}+ info={info}+ model={model}+ onModelChange={selectModel}+ onTitle={onTitle}+ onBusy={onBusy}+ />+ ))}+ </aside>+ );+}++/** One chat with the agent. Stays mounted while hidden so its stream, tool+ * calls, and provider session survive tab switches. */+function ChatSession({+ threadId,+ visible,+ info,+ model,+ onModelChange,+ onTitle,+ onBusy,+}: {+ threadId: string;+ visible: boolean;+ info: ModelsInfo | null;+ model: string;+ onModelChange: (id: string) => void;+ onTitle: (id: string, title: string) => void;+ onBusy: (id: string, busy: boolean) => void;+}) {+ const [input, setInput] = useState("");+ const [attachments, setAttachments] = useState<ChatAsset[]>([]);+ const [dragDepth, setDragDepth] = useState(0);+ const sessionKeyRef = useRef<string | null>(null);+ // Resume from the saved thread when this id exists in history.+ const [initialThread] = useState<ChatThread | undefined>(() =>+ typeof window === "undefined" ? undefined : readThreads().find((t) => t.id === threadId)+ );+ const providerSessions = useRef<Record<string, string>>({ ...(initialThread?.sessions ?? {}) });+ const modelRef = useRef(model);+ modelRef.current = model;++ const transport = useMemo(+ () =>+ new DefaultChatTransport({+ api: "/api/ai/chat",+ prepareSendMessagesRequest: ({ messages }) => ({+ body: {+ messages,+ model: modelRef.current,+ context: buildAiContext(),+ providerSession: providerSessions.current[provider(modelRef.current)],+ },+ }),+ }),+ []+ );++ const { messages, sendMessage, stop, status, error, clearError } = useChat({+ id: threadId,+ messages: initialThread?.messages,+ transport,+ onData: (part) => {+ if (part.type === "data-session") {+ const d = part.data as { sessionKey?: string; providerSession?: string };+ if (d.sessionKey) sessionKeyRef.current = d.sessionKey;+ if (d.providerSession) providerSessions.current[provider(modelRef.current)] = d.providerSession;+ }+ },+ onToolCall: ({ toolCall }) => {+ // Execute on the editor store, then hand the result back to the+ // server-side bridge (which is holding the provider's tool call open).+ void (async () => {+ const post = (payload: Record<string, unknown>) =>+ fetch("/api/ai/tool-result", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ sessionKey: sessionKeyRef.current,+ toolCallId: toolCall.toolCallId,+ ...payload,+ }),+ });+ try {+ const output = await runAiTool(+ toolCall.toolName,+ (toolCall.input ?? {}) as Record<string, unknown>+ );+ await post({ output });+ } catch (err) {+ await post({ errorText: err instanceof Error ? err.message : String(err) });+ }+ })();+ },+ });++ const busy = status === "submitted" || status === "streaming";++ useEffect(() => {+ onBusy(threadId, busy);+ return () => onBusy(threadId, false);+ }, [busy, threadId, onBusy]);++ // Keep the thread saved (and its tab title fresh) as it grows.+ useEffect(() => {+ if (messages.length === 0) return;+ const firstUser = messages.find((m) => m.role === "user");+ const title =+ firstUser?.parts+ .map((p) => (p.type === "text" ? p.text : ""))+ .join("")+ .trim()+ .slice(0, 80) || "New chat";+ onTitle(threadId, title);+ const rest = readThreads().filter((t) => t.id !== threadId);+ writeThreads([+ {+ id: threadId,+ title,+ updatedAt: Date.now(),+ messages,+ sessions: { ...providerSessions.current },+ },+ ...rest,+ ]);+ }, [messages, threadId, onTitle]);++ const scrollRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const el = scrollRef.current;+ if (el) el.scrollTop = el.scrollHeight;+ }, [messages, busy, visible]);++ const send = (text: string) => {+ const t = text.trim();+ if ((!t && attachments.length === 0) || busy) return;+ clearError();+ void sendMessage({+ text: t,+ ...(attachments.length > 0 && { metadata: { attachments } }),+ });+ setInput("");+ setAttachments([]);+ };++ const attachAsset = (id: string) => {+ const a = useEditor.getState().assets.find((x) => x.id === id);+ if (!a) return;+ setAttachments((prev) =>+ prev.some((x) => x.id === a.id)+ ? prev+ : [...prev, { id: a.id, name: a.name, type: a.type, duration: a.duration, url: a.url }]+ );+ };++ const current = info?.models.find((m) => m.id === model);+ const currentAvailable = info ? info.providers[provider(model)]?.available !== false : true;++ return (+ <div+ className={cn("relative flex min-h-0 flex-1 flex-col", !visible && "hidden")}+ onDragEnter={(e) => {+ if (hasAssetDrag(e)) {+ e.preventDefault();+ setDragDepth((n) => n + 1);+ }+ }}+ onDragOver={(e) => {+ if (hasAssetDrag(e)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }+ }}+ onDragLeave={(e) => {+ if (hasAssetDrag(e)) setDragDepth((n) => Math.max(0, n - 1));+ }}+ onDrop={(e) => {+ setDragDepth(0);+ const id = draggedAssetId(e);+ if (!id) return;+ e.preventDefault();+ attachAsset(id);+ }}+ >+ {dragDepth > 0 && (+ <div className="pointer-events-none absolute inset-1.5 z-10 grid place-items-center rounded-xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/8">+ <span className="rounded-full bg-card px-3 py-1 text-[11.5px] font-medium text-[#0a84ff] shadow-sm">+ Drop to attach+ </span>+ </div>+ )}++ <div ref={scrollRef} className="ai-messages min-h-0 flex-1 overflow-y-auto px-3.5 py-3">+ {messages.length === 0 && (+ <div className="flex flex-col gap-3 pt-6">+ <p className="text-[12.5px] leading-relaxed text-muted-foreground">+ I can see your whole project — clips, titles, subtitles, publish+ metadata — and edit it for you. Select something and tell me what+ to change, or ask anything about the cut.+ </p>+ <div className="flex flex-wrap gap-1.5">+ {SUGGESTIONS.map((sug) => (+ <button+ key={sug}+ className="ai-suggestion rounded-full border border-border px-2.5 py-1 text-[11.5px] text-muted-foreground transition-colors hover:border-input hover:text-foreground"+ onClick={() => send(sug)}+ >+ {sug}+ </button>+ ))}+ </div>+ </div>+ )}+ {messages.map((m) => (+ <MessageView key={m.id} message={m} />+ ))}+ {busy && (+ <div className="ai-busy mt-1 flex items-center gap-1.5 text-[11.5px] text-muted-foreground">+ <CircleDashed className="size-3 animate-spin" /> Working…+ </div>+ )}+ {error && (+ <div className="ai-error mt-2 flex items-start gap-2 rounded-lg bg-red-50 px-2.5 py-2 text-[11.5px] leading-relaxed text-red-700">+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />+ {error.message}+ </div>+ )}+ </div>++ <div className="shrink-0 border-t border-border p-2.5">+ <div className="rounded-xl border border-input bg-background focus-within:border-ring">+ {attachments.length > 0 && (+ <div className="flex flex-wrap gap-2 px-2.5 pt-2.5">+ {attachments.map((a) => (+ <div key={a.id} className="ai-attachment relative">+ <AssetThumb asset={a} className="size-14" />+ <button+ aria-label={`Remove ${a.name}`}+ title="Remove"+ className="absolute -top-1.5 -right-1.5 grid size-4.5 place-items-center rounded-full bg-neutral-900 text-white shadow-sm transition-colors hover:bg-neutral-700"+ onClick={() => setAttachments((p) => p.filter((x) => x.id !== a.id))}+ >+ <X className="size-3" />+ </button>+ </div>+ ))}+ </div>+ )}+ <textarea+ className="ai-input max-h-40 min-h-[38px] w-full resize-none bg-transparent px-3 pt-2 text-[12.5px] leading-relaxed outline-none placeholder:text-muted-foreground/70"+ rows={2}+ placeholder="Ask about your video, or tell me what to change…"+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ send(input);+ }+ }}+ />+ <div className="flex items-center gap-1 px-1.5 pb-1.5">+ <ModelSelector info={info} model={model} onSelect={onModelChange} />+ <div className="flex-1" />+ {busy ? (+ <Button variant="outline" size="sm" className="ai-stop" title="Stop" onClick={() => void stop()}>+ <Square className="size-3" />+ </Button>+ ) : (+ <Button+ size="sm"+ className="ai-send"+ title="Send (Enter)"+ disabled={(!input.trim() && attachments.length === 0) || !currentAvailable}+ onClick={() => send(input)}+ >+ <ArrowUp className="size-3.5" />+ </Button>+ )}+ </div>+ </div>+ {info && !currentAvailable && (+ <p className="ai-provider-note mt-1.5 px-1 text-[10.5px] leading-relaxed text-amber-700">+ {PROVIDER_LABEL[provider(model)]}: {info.providers[provider(model)]?.note}+ </p>+ )}+ <p className="mt-1.5 px-1 text-[10px] leading-relaxed text-muted-foreground/70">+ Runs locally through your {current?.provider === "codex" ? "Codex" : "Claude Code"} sign-in.+ Every edit is undoable.+ </p>+ </div>+ </div>+ );+}++/** Square media preview used by attachment chips and in-chat asset cards. */+function AssetThumb({ asset, className }: { asset: ChatAsset; className?: string }) {+ return (+ <div+ className={cn(+ "relative overflow-hidden rounded-lg border border-border bg-muted",+ className+ )}+ >+ {asset.type === "video" ? (+ <video+ src={`${asset.url}#t=0.1`}+ preload="metadata"+ muted+ playsInline+ className="size-full object-cover"+ />+ ) : (+ <div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600">+ <Music className="size-4.5" />+ </div>+ )}+ <span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[8.5px] text-white tabular-nums">+ {formatTime(asset.duration)}+ </span>+ </div>+ );+}++/** Asset card inside a sent message — click to open, drag onto the timeline,+ * "…" menu for more actions. */+function MessageAssetCard({ asset }: { asset: ChatAsset }) {+ return (+ <div className="ai-msg-asset group relative w-16">+ <button+ className="flex w-full flex-col gap-1 text-left"+ title="Click to open · drag to the timeline"+ draggable+ onDragStart={(e) => setAssetDragData(e, asset.id)}+ onClick={() => window.open(asset.url, "_blank", "noopener")}+ >+ <AssetThumb asset={asset} className="size-16 transition-colors group-hover:border-input" />+ <span className="w-full truncate text-[10px] text-muted-foreground">{asset.name}</span>+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Asset options"+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-md bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"+ />+ }+ >+ <Ellipsis className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-40">+ <DropdownMenuItem+ onClick={() => {+ const s = useEditor.getState();+ const full = s.assets.find((a) => a.id === asset.id);+ if (!full || !s.projectId) return;+ void saveAssetToLibrary(s.projectId, full).catch(() => {+ // Library write failed; nothing to roll back.+ });+ }}+ >+ <FolderPlus /> Add to library+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++function MessageView({ message }: { message: UIMessage }) {+ if (message.role === "user") {+ const text = message.parts.map((p) => (p.type === "text" ? p.text : "")).join("");+ const attachments = (message.metadata as { attachments?: ChatAsset[] } | undefined)+ ?.attachments;+ return (+ <div className="ai-msg-user mb-3 flex flex-col items-end gap-1.5">+ {attachments && attachments.length > 0 && (+ <div className="flex max-w-[85%] flex-wrap justify-end gap-1.5">+ {attachments.map((a) => (+ <MessageAssetCard key={a.id} asset={a} />+ ))}+ </div>+ )}+ {text && (+ <div className="max-w-[85%] rounded-2xl rounded-br-md bg-neutral-900 px-3 py-2 text-[12.5px] leading-relaxed whitespace-pre-wrap text-white">+ {text}+ </div>+ )}+ </div>+ );+ }+ return (+ <div className="ai-msg-assistant mb-3 flex flex-col gap-1.5">+ {message.parts.map((part, i) => {+ if (part.type === "text") {+ return (+ <div key={i} className="ai-md max-w-full text-[12.5px] leading-relaxed">+ <Markdown+ components={{+ p: (p) => <p className="mb-1.5 last:mb-0" {...p} />,+ ul: (p) => <ul className="mb-1.5 list-disc pl-4 last:mb-0" {...p} />,+ ol: (p) => <ol className="mb-1.5 list-decimal pl-4 last:mb-0" {...p} />,+ li: (p) => <li className="mb-0.5" {...p} />,+ code: (p) => (+ <code className="rounded bg-muted px-1 py-px font-mono text-[11px]" {...p} />+ ),+ a: (p) => <a className="text-[#0a84ff] underline" target="_blank" {...p} />,+ }}+ >+ {part.text}+ </Markdown>+ </div>+ );+ }+ if (part.type.startsWith("tool-") || part.type === "dynamic-tool") {+ const p = part as unknown as {+ type: string;+ toolName?: string;+ state: string;+ input?: unknown;+ output?: unknown;+ errorText?: string;+ };+ const name = p.toolName ?? part.type.slice(5);+ const failed = p.state === "output-error";+ const done = p.state === "output-available";+ return (+ <details key={i} className="ai-tool group max-w-full">+ <summary+ className={cn(+ "flex cursor-pointer list-none items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[11px] text-muted-foreground transition-colors select-none hover:bg-muted/60 [&::-webkit-details-marker]:hidden",+ failed && "border-red-200 text-red-700"+ )}+ >+ <Wrench className="size-3 shrink-0" />+ <span className="font-mono">{name}</span>+ {done && <Check className="size-3 text-emerald-600" />}+ {failed && <TriangleAlert className="size-3" />}+ {!done && !failed && <CircleDashed className="size-3 animate-spin" />}+ </summary>+ <pre className="mt-1 max-h-40 overflow-auto rounded-md bg-muted/70 p-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap">+ {JSON.stringify({ input: p.input, output: p.output, error: p.errorText }, null, 2)}+ </pre>+ </details>+ );+ }+ return null;+ })}+ </div>+ );+}++function ModelSelector({+ info,+ model,+ onSelect,+}: {+ info: ModelsInfo | null;+ model: string;+ onSelect: (id: string) => void;+}) {+ const [favs, setFavs] = useState<string[]>(() => {+ if (typeof window === "undefined") return [];+ try {+ return JSON.parse(localStorage.getItem(FAVS_KEY) ?? "[]") as string[];+ } catch {+ return [];+ }+ });+ const showTest = typeof window !== "undefined" && localStorage.getItem("cut-ai-test") === "1";+ const models = (info?.models ?? []).filter((m) => !m.hidden || showTest);+ const groups = ["claude", "codex", ...(showTest ? ["test"] : [])].map((p) => ({+ provider: p,+ models: models.filter((m) => m.provider === p),+ available: info?.providers[p]?.available ?? true,+ note: info?.providers[p]?.note ?? "",+ }));+ const flat = groups.flatMap((group) => group.models);+ const currentLabel = models.find((m) => m.id === model)?.label ?? model;++ const toggleFav = (id: string) => {+ const next = favs.includes(id) ? favs.filter((f) => f !== id) : [...favs, id];+ setFavs(next);+ localStorage.setItem(FAVS_KEY, JSON.stringify(next));+ };++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ className="ai-model-trigger flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <Sparkles className="size-3" />+ {currentLabel}+ <ChevronDown className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="ai-model-menu w-60"+ onKeyDown={(e) => {+ const n = Number(e.key);+ if (n >= 1 && n <= flat.length) onSelect(flat[n - 1].id);+ }}+ >+ {groups.map((group, gi) =>+ group.models.length === 0 ? null : (+ <DropdownMenuGroup key={group.provider}>+ {gi > 0 && <DropdownMenuSeparator />}+ <DropdownMenuLabel className="flex items-center gap-1.5 text-[10.5px] tracking-wider text-muted-foreground uppercase">+ <Sparkles className="size-3" /> {PROVIDER_LABEL[group.provider]}+ {!group.available && (+ <span className="ml-1 font-normal normal-case text-amber-700">· {group.note}</span>+ )}+ </DropdownMenuLabel>+ {group.models.map((m) => (+ <DropdownMenuItem+ key={m.id}+ disabled={!group.available}+ className="ai-model-item gap-2"+ onClick={() => onSelect(m.id)}+ >+ <span className="flex-1 text-[12px]">{m.label}</span>+ {model === m.id && <Check className="size-3.5 text-[#0a84ff]" />}+ <button+ className="rounded p-0.5 hover:bg-muted"+ title={favs.includes(m.id) ? "Unfavorite" : "Favorite"}+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ toggleFav(m.id);+ }}+ >+ <Star+ className={cn(+ "size-3",+ favs.includes(m.id) ? "fill-amber-400 text-amber-400" : "text-muted-foreground/50"+ )}+ />+ </button>+ <span className="w-3 text-right font-mono text-[10px] text-muted-foreground/60">+ {flat.indexOf(m) + 1}+ </span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuGroup>+ )+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsxnew file mode 100644index 00000000..d49d85f6--- /dev/null+++ b/site/src/cut/components/AppSidebar.tsx@@ -0,0 +1,121 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { usePathname, useRouter } from "next/navigation";+import { Clapperboard, FolderOpen, Loader2, Plus } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import type { ProjectSummary } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++const NAV = [+ { href: "/", label: "Projects", icon: Clapperboard },+ { href: "/library", label: "Library", icon: FolderOpen },+];++export function AppSidebar() {+ const pathname = usePathname();+ const router = useRouter();+ const [createOpen, setCreateOpen] = useState(false);+ const [name, setName] = useState("");+ const [busy, setBusy] = useState(false);++ const create = async () => {+ setBusy(true);+ try {+ const res = await fetch("/api/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: name.trim() || "Untitled" }),+ });+ const project = (await res.json()) as ProjectSummary;+ router.push(`/p/${project.id}`);+ } finally {+ setBusy(false);+ }+ };++ return (+ <aside className="flex w-60 shrink-0 flex-col border-r border-border bg-card px-3 py-4">+ <div className="mb-5 flex items-center gap-2.5 px-2">+ <span className="grid size-8 place-items-center overflow-hidden rounded-xl">+ <img+ src="/donkey-logo.svg"+ alt="Donkey"+ width={32}+ height={32}+ className="block h-full w-full object-contain"+ />+ </span>+ <span className="text-[17px] font-semibold tracking-tight">Cut</span>+ </div>++ <Button+ className="mb-5 w-full"+ onClick={() => {+ setName("");+ setCreateOpen(true);+ }}+ >+ <Plus data-icon="inline-start" /> New project+ </Button>++ <nav className="flex flex-col gap-0.5">+ {NAV.map(({ href, label, icon: Icon }) => {+ const active = pathname === href;+ return (+ <Link+ key={href}+ href={href}+ className={cn(+ "flex items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",+ active && "bg-muted text-foreground"+ )}+ >+ <Icon className="size-4" />+ {label}+ </Link>+ );+ })}+ </nav>+ <div className="mt-auto px-2.5 text-[11px] leading-relaxed text-muted-foreground/70">+ Everything stays on this Mac.+ </div>++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>New project</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ void create();+ }}+ >+ <Input+ autoFocus+ placeholder="Project name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ <DialogFooter className="mt-4">+ <Button type="submit" disabled={busy} className="w-full">+ {busy && <Loader2 className="animate-spin" data-icon="inline-start" />}+ Create project+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </aside>+ );+}diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxnew file mode 100644index 00000000..d7caac03--- /dev/null+++ b/site/src/cut/components/Editor.tsx@@ -0,0 +1,261 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import Link from "next/link";+import { Clapperboard, Loader2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { enrichAsset, importFileToProject } from "@/cut/lib/media";+import { serializeDoc, totalDuration, useEditor } from "@/cut/lib/store";+import { AiPanel } from "./AiPanel";+import { ExportDialog } from "./ExportDialog";+import { Inspector } from "./Inspector";+import { Preview } from "./Preview";+import { SidePanel } from "./SidePanel";+import { Timeline } from "./Timeline";+import { TopBar } from "./TopBar";++export function Editor({ projectId }: { projectId: string }) {+ const loaded = useEditor((s) => s.loaded);+ const loadError = useEditor((s) => s.loadError);+ const dropActive = useEditor((s) => s.dropActive);+ const exportOpen = useEditor((s) => s.exportOpen);+ const aiOpen = useEditor((s) => s.aiOpen);+ const [importing, setImporting] = useState(0);+ const dragDepth = useRef(0);++ // Load the project document, then enrich assets (thumbs/waveforms) lazily.+ useEffect(() => {+ void useEditor+ .getState()+ .loadProject(projectId)+ .then(() => {+ for (const asset of useEditor.getState().assets) void enrichAsset(asset);+ });+ }, [projectId]);++ // Autosave: debounce document changes into PUT /api/projects/<id>.+ useEffect(() => {+ let timer: ReturnType<typeof setTimeout> | null = null;+ let last = serializeDoc(useEditor.getState());+ let lastName = useEditor.getState().projectName;++ const save = async () => {+ const s = useEditor.getState();+ if (!s.loaded || s.projectId !== projectId) return;+ s.setSaveState("saving");+ try {+ const res = await fetch(`/api/projects/${projectId}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(serializeDoc(s)),+ });+ if (!res.ok) throw new Error();+ useEditor.getState().setSaveState("saved");+ } catch {+ useEditor.getState().setSaveState("error");+ }+ };++ let primed = false;+ const unsub = useEditor.subscribe((s) => {+ if (!s.loaded || s.projectId !== projectId) return;+ if (!primed) {+ // First tick after load: snapshot the freshly loaded doc so opening+ // a project never counts as an edit.+ primed = true;+ last = serializeDoc(s);+ lastName = s.projectName;+ return;+ }+ const changed =+ s.clips !== (last.clips as unknown) ||+ s.audioClips !== (last.audioClips as unknown) ||+ s.overlays !== (last.overlays as unknown) ||+ s.subtitles !== (last.subtitles as unknown) ||+ s.aspect !== last.aspect ||+ s.assets.length !== last.assets?.length ||+ s.publish.caption !== last.publish?.caption ||+ s.publish.tags !== last.publish?.tags ||+ s.publish.soundTitle !== last.publish?.soundTitle ||+ s.publish.handle !== last.publish?.handle ||+ s.projectName !== lastName;+ if (!changed) return;+ last = serializeDoc(s);+ lastName = s.projectName;+ if (s.saveState !== "saving") s.setSaveState("dirty");+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => void save(), 800);+ });+ return () => {+ unsub();+ if (timer) clearTimeout(timer);+ };+ }, [projectId]);++ const importFiles = useCallback(+ async (files: FileList | File[]) => {+ const list = Array.from(files);+ setImporting((n) => n + list.length);+ for (const file of list) {+ try {+ const asset = await importFileToProject(projectId, file);+ if (!asset) continue;+ const s = useEditor.getState();+ s.addAsset(asset);+ if (asset.type === "video") s.addClipFromAsset(asset.id);+ else s.addAudioFromAsset(asset.id, 0);+ void enrichAsset(asset);+ } catch (err) {+ console.error(`Import failed for ${file.name}:`, err);+ } finally {+ setImporting((n) => n - 1);+ }+ }+ },+ [projectId]+ );++ // Whole-window drag & drop.+ useEffect(() => {+ const enter = (e: DragEvent) => {+ if (!e.dataTransfer?.types.includes("Files")) return;+ e.preventDefault();+ dragDepth.current++;+ useEditor.getState().setDropActive(true);+ };+ const over = (e: DragEvent) => {+ if (e.dataTransfer?.types.includes("Files")) e.preventDefault();+ };+ const leave = (e: DragEvent) => {+ if (!e.dataTransfer?.types.includes("Files")) return;+ dragDepth.current = Math.max(0, dragDepth.current - 1);+ if (dragDepth.current === 0) useEditor.getState().setDropActive(false);+ };+ const drop = (e: DragEvent) => {+ if (!e.dataTransfer?.files.length) return;+ e.preventDefault();+ dragDepth.current = 0;+ useEditor.getState().setDropActive(false);+ void importFiles(e.dataTransfer.files);+ };+ window.addEventListener("dragenter", enter);+ window.addEventListener("dragover", over);+ window.addEventListener("dragleave", leave);+ window.addEventListener("drop", drop);+ return () => {+ window.removeEventListener("dragenter", enter);+ window.removeEventListener("dragover", over);+ window.removeEventListener("dragleave", leave);+ window.removeEventListener("drop", drop);+ };+ }, [importFiles]);++ // Keyboard shortcuts.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const target = e.target as HTMLElement;+ const inputType = (target as HTMLInputElement).type;+ const textEntry =+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT" ||+ target.isContentEditable ||+ (target.tagName === "INPUT" &&+ !["checkbox", "radio", "range", "button"].includes(inputType));+ if (textEntry) return;+ // Let native toggle/slider behavior win for focused controls.+ const controlFocused =+ target.tagName === "INPUT" || target.closest('[role="switch"],[role="slider"]') !== null;+ const s = useEditor.getState();+ if (s.exportOpen || document.querySelector('[data-slot="dialog-content"]')) return;++ if (e.code === "Space" && !controlFocused) {+ e.preventDefault();+ if (!s.playing && s.currentTime >= totalDuration(s.clips) - 0.01) s.seek(0);+ s.setPlaying(!s.playing);+ } else if (e.key === "Backspace" || e.key === "Delete") {+ e.preventDefault();+ s.deleteSelection();+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "z") {+ e.preventDefault();+ if (e.shiftKey) s.redo();+ else s.undo();+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "c") {+ if (s.copySelection()) e.preventDefault();+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "v") {+ if (s.paste()) e.preventDefault();+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "j") {+ e.preventDefault();+ s.setAiOpen(!s.aiOpen);+ } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") {+ e.preventDefault();+ // iMovie: cut at the skimmer when the mouse is over the timeline.+ s.splitAtPlayhead(s.skimTime ?? undefined);+ } else if (e.key.toLowerCase() === "s" && !e.metaKey && !e.ctrlKey) {+ s.splitAtPlayhead(s.skimTime ?? undefined);+ } else if (e.key.toLowerCase() === "t" && !e.metaKey && !e.ctrlKey) {+ s.addOverlay();+ } else if ((e.key === "ArrowLeft" || e.key === "ArrowRight") && !controlFocused) {+ e.preventDefault();+ const step = e.shiftKey ? 1 : 1 / 30;+ s.seek(s.currentTime + (e.key === "ArrowLeft" ? -step : step));+ } else if (e.key === "Escape") {+ s.select(null);+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);++ if (loadError) {+ return (+ <div className="grid h-screen place-items-center">+ <div className="flex flex-col items-center gap-3 text-center">+ <Clapperboard className="size-7 text-muted-foreground" />+ <p className="text-sm text-muted-foreground">{loadError}</p>+ <Button+ variant="outline"+ nativeButton={false}+ render={<Link href="/">Back to projects</Link>}+ />+ </div>+ </div>+ );+ }++ if (!loaded) {+ return (+ <div className="grid h-screen place-items-center text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ );+ }++ return (+ <div className="flex h-screen min-w-[900px] select-none overflow-hidden">+ <div className="grid min-w-0 flex-1 grid-rows-[46px_minmax(0,1fr)_auto]">+ <TopBar />+ <div className="grid min-h-0 grid-cols-[auto_minmax(0,1fr)_272px]">+ <SidePanel projectId={projectId} onImport={importFiles} importing={importing > 0} />+ <Preview />+ <Inspector />+ </div>+ <Timeline />+ </div>+ {aiOpen && <AiPanel onClose={() => useEditor.getState().setAiOpen(false)} />}+ {exportOpen && <ExportDialog />}+ {dropActive && (+ <div className="fixed inset-0 z-60 grid place-items-center bg-background/70 backdrop-blur-md">+ <div className="pointer-events-none flex flex-col items-center gap-2 rounded-2xl border-2 border-dashed border-[#0a84ff] bg-[#0a84ff]/10 px-12 py-9 text-[#0a84ff]">+ <Clapperboard className="size-7" />+ <div className="text-[15px] font-semibold text-foreground">+ Drop to add to your project+ </div>+ <div className="text-xs text-muted-foreground">+ Videos land on the timeline · music on the soundtrack+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsxnew file mode 100644index 00000000..4a3ea897--- /dev/null+++ b/site/src/cut/components/ExportDialog.tsx@@ -0,0 +1,157 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Check, FolderCheck } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { EXPORT_PRESETS, presetSettings, startExport, type ExportHandle } from "@/cut/lib/exportClient";+import { useEditor } from "@/cut/lib/store";+import { cn } from "@/lib/utils";++type Phase =+ | { kind: "idle" }+ | { kind: "running"; stage: string; ratio: number }+ | { kind: "done"; outName: string }+ | { kind: "error"; message: string };++export function ExportDialog() {+ const setExportOpen = useEditor((s) => s.setExportOpen);+ const aspect = useEditor((s) => s.aspect);+ const [presetId, setPresetId] = useState<string>(EXPORT_PRESETS[0].id);+ const [phase, setPhase] = useState<Phase>({ kind: "idle" });+ const handleRef = useRef<ExportHandle | null>(null);++ useEffect(() => () => handleRef.current?.cancel(), []);++ const close = () => {+ handleRef.current?.cancel();+ setExportOpen(false);+ };++ const run = () => {+ const preset = EXPORT_PRESETS.find((p) => p.id === presetId) ?? EXPORT_PRESETS[0];+ const s = useEditor.getState();+ if (!s.projectId) return;+ const handle = startExport(+ s.projectId,+ {+ assets: s.assets,+ clips: s.clips,+ audioClips: s.audioClips,+ overlays: s.overlays,+ subtitles: s.subtitles,+ },+ presetSettings(preset, s.aspect),+ (stage, ratio) => setPhase({ kind: "running", stage, ratio })+ );+ handleRef.current = handle;+ handle.done+ .then(({ outName }) => setPhase({ kind: "done", outName }))+ .catch((err: unknown) =>+ setPhase({ kind: "error", message: err instanceof Error ? err.message : String(err) })+ );+ };++ return (+ <Dialog open onOpenChange={(o) => !o && close()}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Export</DialogTitle>+ </DialogHeader>++ {phase.kind === "idle" && (+ <>+ <div className="flex flex-col gap-2" role="radiogroup" aria-label="Export preset">+ {EXPORT_PRESETS.map((p) => {+ const dims = presetSettings(p, aspect);+ return (+ <button+ key={p.id}+ role="radio"+ aria-checked={presetId === p.id}+ className={cn(+ "flex flex-col items-start rounded-lg border border-border bg-background px-3 py-2.5 text-left transition-colors hover:border-input",+ presetId === p.id && "border-primary bg-primary/10"+ )}+ onClick={() => setPresetId(p.id)}+ >+ <span className="text-sm font-medium">{p.label}</span>+ <span className="text-xs text-muted-foreground">+ {dims.width} × {dims.height} · {p.detail}+ </span>+ </button>+ );+ })}+ </div>+ <DialogFooter>+ <Button className="w-full" onClick={run}>+ Export video+ </Button>+ </DialogFooter>+ </>+ )}++ {phase.kind === "running" && (+ <div className="pt-1">+ <div className="h-1.5 overflow-hidden rounded-full bg-secondary">+ <div+ className="h-full rounded-full bg-primary transition-[width] duration-300"+ style={{ width: `${Math.round(phase.ratio * 100)}%` }}+ />+ </div>+ <div className="mt-2.5 flex justify-between text-xs text-muted-foreground">+ <span>{phase.stage}</span>+ <span className="font-mono tabular-nums">{Math.round(phase.ratio * 100)}%</span>+ </div>+ <DialogFooter className="mt-4">+ <Button variant="ghost" onClick={close}>+ Cancel+ </Button>+ </DialogFooter>+ </div>+ )}++ {phase.kind === "done" && (+ <div className="flex flex-col items-center pt-2 text-center">+ <span className="mb-3 grid size-11 place-items-center rounded-full bg-[#30d158] text-[#04180b]">+ <Check className="size-5" />+ </span>+ <div className="text-[15px] font-semibold">Exported</div>+ <div className="mt-1 flex items-center gap-1.5 text-sm text-muted-foreground">+ <FolderCheck className="size-3.5" />+ Saved into the project’s exports folder and downloaded.+ </div>+ <DialogFooter className="mt-4 w-full">+ <Button className="w-full" onClick={() => setExportOpen(false)}>+ Done+ </Button>+ </DialogFooter>+ </div>+ )}++ {phase.kind === "error" && (+ <div>+ <div className="mb-2 text-sm font-medium text-destructive">+ Export didn’t finish+ </div>+ <pre className="max-h-36 overflow-auto rounded-lg border border-border bg-background p-2.5 font-mono text-[10.5px] leading-relaxed break-words whitespace-pre-wrap text-muted-foreground select-text">+ {phase.message}+ </pre>+ <DialogFooter className="mt-4">+ <Button variant="ghost" onClick={close}>+ Close+ </Button>+ <Button onClick={() => setPhase({ kind: "idle" })}>Try again</Button>+ </DialogFooter>+ </div>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxnew file mode 100644index 00000000..bd9b57f8--- /dev/null+++ b/site/src/cut/components/Inspector.tsx@@ -0,0 +1,380 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Bold } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Slider } from "@/components/ui/slider";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { useEditor } from "@/cut/lib/store";+import { PLATE_RADIUS } from "@/cut/lib/textRender";+import { formatTime } from "@/cut/lib/time";+import { FONTS, type AudioClip, type TextOverlay, type VideoClip } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++const SWATCHES = ["#FFFFFF", "#111114", "#FFD60A", "#FF375F", "#0A84FF", "#30D158"];++/** Last three custom colors picked with the eyedropper, newest first. */+const RECENT_COLORS_KEY = "cut-recent-colors";++/**+ * One undo checkpoint per slider drag: capture the pre-drag state on the first+ * change, then feed live changes through the transient updater so the whole+ * drag collapses to a single ⌘Z. Reset when the interaction commits.+ */+function useSliderCheckpoint() {+ const active = useRef(false);+ return {+ begin() {+ if (active.current) return;+ active.current = true;+ useEditor.getState().pushHistory();+ },+ end() {+ active.current = false;+ },+ };+}++function readRecentColors(): string[] {+ try {+ const v = JSON.parse(localStorage.getItem(RECENT_COLORS_KEY) ?? "[]") as unknown;+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string").slice(0, 3) : [];+ } catch {+ return [];+ }+}++export function Inspector() {+ const selection = useEditor((s) => s.selection);+ const clip = useEditor((s) =>+ selection?.kind === "clip" ? s.clips.find((c) => c.id === selection.id) : undefined+ );+ const audio = useEditor((s) =>+ selection?.kind === "audio" ? s.audioClips.find((c) => c.id === selection.id) : undefined+ );+ const overlay = useEditor((s) =>+ selection?.kind === "text" ? s.overlays.find((o) => o.id === selection.id) : undefined+ );++ return (+ <aside className="flex min-h-0 flex-col overflow-y-auto border-l border-border bg-card">+ {clip ? (+ <ClipPanel clip={clip} />+ ) : audio ? (+ <AudioPanel clip={audio} />+ ) : overlay ? (+ <TextPanel overlay={overlay} />+ ) : (+ <ProjectPanel />+ )}+ </aside>+ );+}++function PanelTitle({ children }: { children: React.ReactNode }) {+ return (+ <div className="flex h-10 shrink-0 items-center px-3.5 text-[11px] font-semibold tracking-widest text-muted-foreground uppercase">+ {children}+ </div>+ );+}++function Row({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex min-h-9 items-center justify-between gap-2.5">+ <span className="shrink-0 text-[13px] text-muted-foreground">{label}</span>+ <div className="flex min-w-0 items-center gap-2">{children}</div>+ </div>+ );+}++const Value = ({ children, className }: { children: React.ReactNode; className?: string }) => (+ <span className={cn("font-mono text-[11.5px] tabular-nums", className)}>{children}</span>+);++function ProjectPanel() {+ return (+ <>+ <PanelTitle>Project</PanelTitle>+ </>+ );+}++function ClipPanel({ clip }: { clip: VideoClip }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));+ const updateClip = useEditor((s) => s.updateClip);+ return (+ <>+ <PanelTitle>Video clip</PanelTitle>+ <div className="flex flex-col gap-1 px-3.5 pb-4">+ <div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>+ {asset?.name}+ </div>+ <Row label="Length"><Value>{formatTime(clip.out - clip.in)}</Value></Row>+ <Row label="Trim">+ <Value>{formatTime(clip.in)} – {formatTime(clip.out)}</Value>+ </Row>+ <Row label="Mute audio">+ <Switch+ checked={clip.muted}+ onCheckedChange={(v) => updateClip(clip.id, { muted: v })}+ />+ </Row>+ <Row label="Framing">+ <div className="clip-framing flex rounded-lg border border-input p-0.5">+ {(["fit", "fill"] as const).map((mode) => (+ <button+ key={mode}+ className={cn(+ "rounded-md px-2.5 py-1 text-[11.5px] font-medium transition-colors",+ (clip.fit ?? "fit") === mode+ ? "bg-neutral-900 text-white"+ : "text-muted-foreground hover:text-foreground"+ )}+ aria-pressed={(clip.fit ?? "fit") === mode}+ onClick={() => updateClip(clip.id, { fit: mode, panX: 0, panY: 0 })}+ >+ {mode === "fit" ? "Fit" : "Fill"}+ </button>+ ))}+ </div>+ </Row>+ {clip.fit === "fill" && ((clip.panX ?? 0) !== 0 || (clip.panY ?? 0) !== 0) && (+ <Row label="Position">+ <button+ className="clip-recenter rounded-md border border-input px-2 py-0.5 text-[11.5px] text-muted-foreground transition-colors hover:text-foreground"+ onClick={() => updateClip(clip.id, { panX: 0, panY: 0 })}+ >+ Center+ </button>+ </Row>+ )}+ <p className="mt-2.5 text-[11.5px] leading-relaxed text-muted-foreground">+ {clip.fit === "fill"+ ? "Fill crops the video to cover the frame — drag it in the preview to choose what stays visible."+ : "Drag the clip edges on the timeline to trim it. Fit letterboxes the whole picture; Fill crops it to cover the frame."}+ </p>+ </div>+ </>+ );+}++function AudioPanel({ clip }: { clip: AudioClip }) {+ const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));+ const updateAudioTransient = useEditor((s) => s.updateAudioTransient);+ const ck = useSliderCheckpoint();+ const setAudio = (patch: Partial<AudioClip>) => {+ ck.begin();+ updateAudioTransient(clip.id, patch);+ };+ // A fade can take at most half the clip so in+out never overlap.+ const maxFade = Math.max(0.1, Math.round(((clip.out - clip.in) / 2) * 10) / 10);+ return (+ <>+ <PanelTitle>Soundtrack</PanelTitle>+ <div className="flex flex-col gap-1 px-3.5 pb-4">+ <div className="mb-1.5 truncate border-b border-border pb-2.5 text-xs font-medium" title={asset?.name}>+ {asset?.name}+ </div>+ <Row label="Length"><Value>{formatTime(clip.out - clip.in)}</Value></Row>+ <Row label="Starts at"><Value>{formatTime(clip.start)}</Value></Row>+ <Row label="Volume">+ <Slider+ className="data-horizontal:w-24"+ min={0}+ max={1.5}+ step={0.05}+ value={clip.volume}+ onValueChange={(v) => setAudio({ volume: Number(v) })}+ onValueCommitted={ck.end}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {Math.round(clip.volume * 100)}%+ </Value>+ </Row>+ <Row label="Fade in">+ <Slider+ className="fade-in-slider data-horizontal:w-24"+ min={0}+ max={maxFade}+ step={0.1}+ value={clip.fadeIn ?? 0}+ onValueChange={(v) => setAudio({ fadeIn: Number(v) })}+ onValueCommitted={ck.end}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {(clip.fadeIn ?? 0).toFixed(1)}s+ </Value>+ </Row>+ <Row label="Fade out">+ <Slider+ className="fade-out-slider data-horizontal:w-24"+ min={0}+ max={maxFade}+ step={0.1}+ value={clip.fadeOut ?? 0}+ onValueChange={(v) => setAudio({ fadeOut: Number(v) })}+ onValueCommitted={ck.end}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {(clip.fadeOut ?? 0).toFixed(1)}s+ </Value>+ </Row>+ </div>+ </>+ );+}++function TextPanel({ overlay: o }: { overlay: TextOverlay }) {+ const update = useEditor((s) => s.updateOverlay);+ const sizeCk = useSliderCheckpoint();+ const radiusCk = useSliderCheckpoint();+ const [recents, setRecents] = useState<string[]>([]);+ useEffect(() => setRecents(readRecentColors()), []);++ const recordRecent = (c: string) => {+ if (SWATCHES.some((s) => s.toUpperCase() === c.toUpperCase())) return;+ const next = [c, ...recents.filter((r) => r.toUpperCase() !== c.toUpperCase())].slice(0, 3);+ setRecents(next);+ try {+ localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(next));+ } catch {+ // Storage full/blocked — recents just won't persist.+ }+ };+ return (+ <>+ <PanelTitle>Title</PanelTitle>+ <div className="flex flex-col gap-1 px-3.5 pb-4">+ <Textarea+ className="mb-2 min-h-16 select-text"+ rows={3}+ value={o.text}+ onChange={(e) =>+ useEditor.getState().updateOverlayTransient(o.id, { text: e.target.value })+ }+ onFocus={() => useEditor.getState().pushHistory()}+ />+ <Row label="Font">+ <Select+ value={o.font}+ items={Object.fromEntries(FONTS.map((f) => [f.id, f.label]))}+ onValueChange={(v) => update(o.id, { font: v as TextOverlay["font"] })}+ >+ <SelectTrigger size="sm" className="w-28">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FONTS.map((f) => (+ <SelectItem key={f.id} value={f.id}>+ {f.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ variant="outline"+ size="icon-sm"+ aria-label="Bold"+ aria-pressed={o.weight === 700}+ className={cn(o.weight === 700 && "border-primary bg-primary/15 text-primary")}+ onClick={() => update(o.id, { weight: o.weight === 700 ? 400 : 700 })}+ >+ <Bold />+ </Button>+ </Row>+ <Row label="Size">+ <Slider+ className="data-horizontal:w-24"+ min={24}+ max={240}+ value={o.size}+ onValueChange={(v) => {+ sizeCk.begin();+ useEditor.getState().updateOverlayTransient(o.id, { size: Number(v) });+ }}+ onValueCommitted={sizeCk.end}+ />+ <Value className="w-9 text-right text-muted-foreground">{o.size}</Value>+ </Row>+ <Row label="Color">+ <div className="flex max-w-44 flex-wrap items-center justify-end gap-1.5">+ {[...SWATCHES, ...recents].map((c) => (+ <button+ key={c}+ title={c}+ aria-label={`Color ${c}`}+ className={cn(+ "size-5 rounded-full border border-black/15 transition-transform hover:scale-110",+ o.color.toUpperCase() === c.toUpperCase() &&+ "ring-2 ring-primary ring-offset-2 ring-offset-card"+ )}+ style={{ background: c }}+ onClick={() => update(o.id, { color: c })}+ />+ ))}+ <label+ title="Custom color"+ className="color-picker-well relative size-5 cursor-pointer rounded-full border border-black/15 bg-[conic-gradient(from_0deg,#f43f5e,#f59e0b,#84cc16,#06b6d4,#6366f1,#d946ef,#f43f5e)] transition-transform hover:scale-110"+ >+ <span className="absolute inset-1 rounded-full bg-card" />+ <span className="absolute inset-[5px] rounded-full" style={{ background: o.color }} />+ <input+ type="color"+ aria-label="Pick a custom color"+ className="absolute inset-0 size-full cursor-pointer opacity-0"+ value={/^#[0-9a-fA-F]{6}$/.test(o.color) ? o.color : "#ffffff"}+ onFocus={() => useEditor.getState().pushHistory()}+ onChange={(e) =>+ useEditor.getState().updateOverlayTransient(o.id, { color: e.target.value })+ }+ onBlur={() => {+ const c = useEditor+ .getState()+ .overlays.find((x) => x.id === o.id)?.color;+ if (c) recordRecent(c);+ }}+ />+ </label>+ </div>+ </Row>+ <Row label="Shadow">+ <Switch checked={o.shadow} onCheckedChange={(v) => update(o.id, { shadow: v })} />+ </Row>+ <Row label="Backdrop">+ <Switch checked={o.plate} onCheckedChange={(v) => update(o.id, { plate: v })} />+ </Row>+ {o.plate && (+ <Row label="Radius">+ <Slider+ className="data-horizontal:w-24"+ min={0}+ max={1}+ step={0.01}+ value={o.plateRadius ?? PLATE_RADIUS}+ onValueChange={(v) => {+ radiusCk.begin();+ useEditor.getState().updateOverlayTransient(o.id, { plateRadius: Number(v) });+ }}+ onValueCommitted={radiusCk.end}+ />+ <Value className="w-9 text-right text-muted-foreground">+ {Math.round((o.plateRadius ?? PLATE_RADIUS) * 100)}+ </Value>+ </Row>+ )}+ <p className="mt-2.5 text-[11.5px] leading-relaxed text-muted-foreground">+ Drag the title in the preview to place it; use the corner handle to resize.+ </p>+ </div>+ </>+ );+}diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxnew file mode 100644index 00000000..be85b48e--- /dev/null+++ b/site/src/cut/components/LibraryView.tsx@@ -0,0 +1,222 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Film, FolderOpen, Loader2, Music, Plus, Trash2, Upload } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import {+ deleteFromLibrary,+ fetchLibrary,+ libraryMediaUrl,+ uploadToLibrary,+ type LibraryAsset,+} from "@/cut/lib/library";+import { formatTime } from "@/cut/lib/time";++export function LibraryView() {+ const [assets, setAssets] = useState<LibraryAsset[] | null>(null);+ const [uploading, setUploading] = useState(0);+ const [deleting, setDeleting] = useState<LibraryAsset | null>(null);+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ void fetchLibrary().then(setAssets).catch(() => setAssets([]));+ }, []);++ const upload = async (files: FileList) => {+ const list = Array.from(files);+ setUploading((n) => n + list.length);+ for (const file of list) {+ try {+ const asset = await uploadToLibrary(file);+ setAssets((prev) => [asset, ...(prev ?? [])]);+ } catch {+ // Skip unreadable files; the rest of the batch still uploads.+ } finally {+ setUploading((n) => n - 1);+ }+ }+ };++ const remove = async () => {+ if (!deleting) return;+ await deleteFromLibrary(deleting.id);+ setAssets((prev) => (prev ?? []).filter((a) => a.id !== deleting.id));+ setDeleting(null);+ };++ return (+ <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div className="mb-6 flex items-center justify-between">+ <div>+ <h1 className="text-lg font-semibold tracking-tight">Library</h1>+ <p className="mt-0.5 text-sm text-muted-foreground">+ Clips and music you can drop into any project.+ </p>+ </div>+ <Button onClick={() => inputRef.current?.click()}>+ <Upload data-icon="inline-start" /> Add media+ </Button>+ <input+ ref={inputRef}+ type="file"+ accept="video/*,audio/*"+ multiple+ hidden+ onChange={(e) => {+ if (e.target.files?.length) void upload(e.target.files);+ e.target.value = "";+ }}+ />+ </div>++ {assets === null ? (+ <div className="grid place-items-center py-24 text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ ) : assets.length === 0 && uploading === 0 ? (+ <button+ className="grid w-full cursor-pointer place-items-center rounded-2xl border-2 border-dashed border-border py-24 transition-colors hover:border-primary/40"+ onClick={() => inputRef.current?.click()}+ >+ <div className="flex flex-col items-center gap-3 text-center">+ <FolderOpen className="size-8 text-muted-foreground" />+ <div className="text-base font-medium">Your library is empty</div>+ <p className="max-w-xs text-sm text-muted-foreground">+ Add intros, outros, logo stings, and music once — reuse them in+ every cut.+ </p>+ </div>+ </button>+ ) : (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-4">+ {assets.map((a) => (+ <LibraryCard key={a.id} asset={a} onDelete={() => setDeleting(a)} />+ ))}+ {uploading > 0 && (+ <div className="flex aspect-square flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-input text-xs text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ Uploading…+ </div>+ )}+ </div>+ )}++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Remove “{deleting?.name}” from the library?</AlertDialogTitle>+ <AlertDialogDescription>+ Projects that already use it keep their own copy.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ void remove();+ }}+ >+ Remove+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++export function LibraryCard({+ asset: a,+ onDelete,+ onUse,+}: {+ asset: LibraryAsset;+ onDelete?: () => void;+ onUse?: () => void;+}) {+ const videoRef = useRef<HTMLVideoElement>(null);+ const [hovering, setHovering] = useState(false);++ return (+ <div+ className="group flex cursor-pointer flex-col gap-1.5"+ onMouseEnter={() => {+ if (a.type === "video") setHovering(true);+ }}+ onMouseLeave={() => {+ videoRef.current?.pause();+ setHovering(false);+ }}+ onClick={onUse}+ >+ <div className="relative aspect-square overflow-hidden rounded-xl border border-border bg-muted transition-shadow group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.1)]">+ {a.type === "video" ? (+ <>+ <video+ src={`${libraryMediaUrl(a.fileName)}#t=0.1`}+ muted+ playsInline+ preload="metadata"+ className="size-full object-cover"+ />+ {hovering && (+ <video+ ref={videoRef}+ src={libraryMediaUrl(a.fileName)}+ autoPlay+ muted+ loop+ playsInline+ className="absolute inset-0 size-full object-cover"+ />+ )}+ </>+ ) : (+ <div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600">+ <Music className="size-5" />+ </div>+ )}+ <span className="absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">+ {formatTime(a.duration)}+ </span>+ {onUse && (+ <span className="absolute top-1.5 left-1.5 grid size-5 scale-75 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-all group-hover:scale-100 group-hover:opacity-100">+ <Plus className="size-3" />+ </span>+ )}+ {onDelete && (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Remove from library"+ className="absolute top-1.5 right-1.5 bg-black/40 text-white opacity-0 group-hover:opacity-100 hover:bg-black/60 hover:text-white"+ onClick={(e) => {+ e.stopPropagation();+ onDelete();+ }}+ >+ <Trash2 />+ </Button>+ )}+ {a.type === "video" && !hovering && (+ <span className="absolute bottom-1.5 left-1.5 text-white/90">+ <Film className="size-3.5 drop-shadow" />+ </span>+ )}+ </div>+ <div className="truncate px-0.5 text-xs text-muted-foreground">{a.name}</div>+ </div>+ );+}diff --git a/site/src/cut/components/OverlayLayer.tsx b/site/src/cut/components/OverlayLayer.tsxnew file mode 100644index 00000000..55720dca--- /dev/null+++ b/site/src/cut/components/OverlayLayer.tsx@@ -0,0 +1,216 @@+"use client";++import { useEffect, useRef, useState, type CSSProperties } from "react";+import { startDrag } from "@/cut/lib/drag";+import { useEditor } from "@/cut/lib/store";+import { cueAt, SUB_STYLE, wrapCaption } from "@/cut/lib/subtitles";+import {+ LINE_HEIGHT,+ PLATE_FILL,+ PLATE_PAD_X,+ PLATE_PAD_Y,+ PLATE_RADIUS,+ SHADOW,+} from "@/cut/lib/textRender";+import { FRAME, fontStack, type TextOverlay } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++// Plate geometry as CSS, kept in lockstep with the export burn-in metrics.+const PLATE_PADDING = `${PLATE_PAD_Y}em ${PLATE_PAD_X}em`;+const PLATE_RADIUS_EM = `${PLATE_RADIUS}em`;++export function OverlayLayer({ stageWidth }: { stageWidth: number }) {+ const overlays = useEditor((s) => s.overlays);+ const currentTime = useEditor((s) => s.currentTime);+ const skimTime = useEditor((s) => s.skimTime);+ const playing = useEditor((s) => s.playing);+ const selection = useEditor((s) => s.selection);+ // Titles preview under the skimmer too (paused only), matching the canvas.+ const t = !playing && skimTime !== null ? skimTime : currentTime;++ return (+ <div className="pointer-events-none absolute inset-0">+ {overlays.map((o) => {+ const selected = selection?.kind === "text" && selection.id === o.id;+ const inRange = t >= o.start && t <= o.end;+ if (!inRange && !selected) return null;+ return (+ <OverlayItem+ key={o.id}+ overlay={o}+ selected={selected}+ ghost={!inRange}+ stageWidth={stageWidth}+ />+ );+ })}+ </div>+ );+}++/** The active subtitle cue, rendered exactly like the export burn-in.+ * Nothing renders when subtitles are hidden or there is no cue (no speech). */+export function SubtitleLayer({ stageWidth }: { stageWidth: number }) {+ const subtitles = useEditor((s) => s.subtitles);+ const currentTime = useEditor((s) => s.currentTime);+ const skimTime = useEditor((s) => s.skimTime);+ const playing = useEditor((s) => s.playing);+ const aspect = useEditor((s) => s.aspect);+ const t = !playing && skimTime !== null ? skimTime : currentTime;++ if (!subtitles.showOnVideo) return null;+ const cue = cueAt(subtitles.cues, t);+ if (!cue || !cue.text.trim()) return null;++ const scale = stageWidth / FRAME[aspect].w;+ return (+ <div className="pointer-events-none absolute inset-0">+ <div+ className="sub-caption absolute -translate-x-1/2 -translate-y-1/2 text-center whitespace-pre"+ style={{+ left: `${SUB_STYLE.x * 100}%`,+ top: `${SUB_STYLE.y * 100}%`,+ fontSize: SUB_STYLE.size * scale,+ fontFamily: fontStack(SUB_STYLE.font),+ fontWeight: SUB_STYLE.weight,+ lineHeight: LINE_HEIGHT,+ color: SUB_STYLE.color,+ textShadow: `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`,+ background: PLATE_FILL,+ padding: PLATE_PADDING,+ borderRadius: PLATE_RADIUS_EM,+ }}+ >+ {wrapCaption(cue.text)}+ </div>+ </div>+ );+}++function OverlayItem({+ overlay: o,+ selected,+ ghost,+ stageWidth,+}: {+ overlay: TextOverlay;+ selected: boolean;+ ghost: boolean;+ stageWidth: number;+}) {+ const [editing, setEditing] = useState(false);+ const editRef = useRef<HTMLDivElement>(null);+ const boxRef = useRef<HTMLDivElement>(null);+ const frame = useEditor((s) => FRAME[s.aspect]);+ const scale = stageWidth / frame.w;+ const stageHeight = (stageWidth * frame.h) / frame.w;++ useEffect(() => {+ if (editing && editRef.current) {+ editRef.current.focus();+ const range = document.createRange();+ range.selectNodeContents(editRef.current);+ const sel = window.getSelection();+ sel?.removeAllRanges();+ sel?.addRange(range);+ }+ }, [editing]);++ const style: CSSProperties = {+ left: `${o.x * 100}%`,+ top: `${o.y * 100}%`,+ fontSize: o.size * scale,+ fontFamily: fontStack(o.font),+ fontWeight: o.weight,+ lineHeight: LINE_HEIGHT,+ color: o.color,+ textShadow: o.shadow+ ? `0 ${SHADOW.offsetY * scale}px ${SHADOW.blur * scale}px ${SHADOW.color}`+ : undefined,+ background: o.plate ? PLATE_FILL : undefined,+ padding: o.plate ? PLATE_PADDING : undefined,+ borderRadius: o.plate ? `${o.plateRadius ?? PLATE_RADIUS}em` : undefined,+ opacity: ghost ? 0.35 : 1,+ };++ const commitText = () => {+ const text = (editRef.current?.innerText ?? "").replace(/\n+$/, "");+ setEditing(false);+ if (text !== o.text) {+ const s = useEditor.getState();+ s.pushHistory();+ s.updateOverlayTransient(o.id, { text: text || "Your text" });+ }+ };++ return (+ <div+ ref={boxRef}+ className={cn(+ "overlay-item pointer-events-auto absolute -translate-x-1/2 -translate-y-1/2 cursor-grab rounded-xs text-center whitespace-pre active:cursor-grabbing",+ selected && "outline-[1.5px] outline-offset-[3px] outline-[#0a84ff]",+ editing && "cursor-text"+ )}+ style={style}+ onPointerDown={(e) => {+ if (editing) return;+ const s = useEditor.getState();+ s.select({ kind: "text", id: o.id });+ s.pushHistory();+ const { x, y } = o;+ startDrag(e, {+ onMove: (dx, dy) => {+ s.updateOverlayTransient(o.id, {+ x: Math.min(0.98, Math.max(0.02, x + dx / stageWidth)),+ y: Math.min(0.98, Math.max(0.02, y + dy / stageHeight)),+ });+ },+ });+ }}+ onDoubleClick={() => setEditing(true)}+ >+ {editing ? (+ <div+ ref={editRef}+ className="min-w-2 outline-none select-text"+ contentEditable+ suppressContentEditableWarning+ onBlur={commitText}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ commitText();+ }+ e.stopPropagation();+ }}+ >+ {o.text}+ </div>+ ) : (+ <span>{o.text}</span>+ )}+ {selected && !editing && (+ <span+ title="Drag to resize"+ className="overlay-resize absolute -right-2 -bottom-2 size-[13px] cursor-nwse-resize rounded-full border-[2.5px] border-[#0a84ff] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.4)]"+ onPointerDown={(e) => {+ const s = useEditor.getState();+ s.pushHistory();+ const box = boxRef.current!.getBoundingClientRect();+ const cx = box.left + box.width / 2;+ const cy = box.top + box.height / 2;+ const d0 = Math.max(8, Math.hypot(e.clientX - cx, e.clientY - cy));+ const size0 = o.size;+ startDrag(e, {+ onMove: (_dx, _dy, ev) => {+ const d = Math.hypot(ev.clientX - cx, ev.clientY - cy);+ const size = Math.round(Math.min(320, Math.max(16, (size0 * d) / d0)));+ s.updateOverlayTransient(o.id, { size });+ },+ });+ }}+ />+ )}+ </div>+ );+}diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsxnew file mode 100644index 00000000..d3f6ed79--- /dev/null+++ b/site/src/cut/components/PlatformPreview.tsx@@ -0,0 +1,429 @@+"use client";++import { useEffect, useRef, useState } from "react";+import {+ Bookmark,+ Camera,+ Check,+ Copy,+ Heart,+ MessageCircle,+ MoreHorizontal,+ Music2,+ Search,+ Send,+ Share2,+ ThumbsDown,+ ThumbsUp,+ Volume2,+ VolumeX,+ X,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";+import { useEditor } from "@/cut/lib/store";+import { cn } from "@/lib/utils";++export interface ExportItem {+ file: string;+ size: number;+ mtime: number;+}++type Platform = "tiktok" | "instagram" | "youtube";++const PLATFORMS: { id: Platform; label: string }[] = [+ { id: "tiktok", label: "TikTok" },+ { id: "instagram", label: "Instagram" },+ { id: "youtube", label: "YouTube" },+];++const shadow = "[text-shadow:0_1px_3px_rgba(0,0,0,0.6)]";++/** Full post preview: the export playing inside a phone, dressed in each+ * platform's overlay chrome, with the publish metadata rendered in place. */+export function PlatformPreviewDialog({+ projectId,+ item,+ onClose,+}: {+ projectId: string;+ item: ExportItem;+ onClose: () => void;+}) {+ const publish = useEditor((s) => s.publish);+ const setPublish = useEditor((s) => s.setPublish);+ const [platform, setPlatform] = useState<Platform>("tiktok");+ const [muted, setMuted] = useState(true);+ const [copied, setCopied] = useState(false);+ const videoRef = useRef<HTMLVideoElement>(null);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ const url = `/api/projects/${projectId}/exports/${encodeURIComponent(item.file)}`;+ const handle = publish.handle.trim().replace(/^@+/, "") || "you";+ const caption = publish.caption.trim();+ const tagsLine = normalizeTags(publish.tags);+ const sound = publish.soundTitle.trim() || `original sound - ${handle}`;+ const combined = [caption, tagsLine].filter(Boolean).join("\n\n");++ const field = "text-[11px] font-semibold tracking-wider text-muted-foreground uppercase";+ const box =+ "w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring";++ return (+ <div+ data-slot="dialog-content"+ className="platform-preview fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-6 backdrop-blur-sm"+ onPointerDown={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ >+ <div className="flex max-h-full overflow-hidden rounded-2xl bg-card shadow-2xl">+ {/* Metadata editor — the original, editable in place. */}+ <div className="flex w-[300px] shrink-0 flex-col gap-3.5 overflow-y-auto border-r border-border p-4">+ <div>+ <div className="text-sm font-semibold tracking-tight">Post preview</div>+ <div className="mt-0.5 truncate font-mono text-[10.5px] text-muted-foreground">+ {item.file}+ </div>+ </div>++ <div className="flex flex-col gap-1.5">+ <span className={field}>Handle</span>+ <div className="relative">+ <span className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-[12.5px] text-muted-foreground">+ @+ </span>+ <input+ className={cn(box, "publish-handle pl-6")}+ placeholder="you"+ value={publish.handle}+ onChange={(e) => setPublish({ handle: e.target.value.replace(/^@+/, "") })}+ />+ </div>+ </div>++ <div className="flex flex-col gap-1.5">+ <span className={field}>Caption</span>+ <textarea+ className={cn(box, "min-h-[96px] resize-y leading-relaxed")}+ placeholder="What's happening in this video?"+ value={publish.caption}+ onChange={(e) => setPublish({ caption: e.target.value })}+ />+ </div>++ <div className="flex flex-col gap-1.5">+ <span className={field}>Tags</span>+ <input+ className={box}+ placeholder="fyp howto cut"+ value={publish.tags}+ onChange={(e) => setPublish({ tags: e.target.value })}+ />+ </div>++ <div className="flex flex-col gap-1.5">+ <span className={field}>Sound title</span>+ <input+ className={box}+ placeholder={`original sound - ${handle}`}+ value={publish.soundTitle}+ onChange={(e) => setPublish({ soundTitle: e.target.value })}+ />+ </div>++ <div className="mt-auto flex flex-col gap-2 pt-1">+ <Button+ className="w-full"+ disabled={!combined}+ onClick={() => {+ void navigator.clipboard.writeText(combined).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });+ }}+ >+ {copied ? (+ <>+ <Check data-icon="inline-start" /> Copied+ </>+ ) : (+ <>+ <Copy data-icon="inline-start" /> Copy caption + tags+ </>+ )}+ </Button>+ <p+ className={cn(+ "text-right font-mono text-[11px] tabular-nums",+ combined.length > CAPTION_LIMIT+ ? "font-semibold text-red-600"+ : "text-muted-foreground"+ )}+ >+ {combined.length.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}+ </p>+ </div>+ </div>++ {/* Phone stage */}+ <div className="relative flex flex-col items-center gap-4 bg-muted/40 px-10 py-5">+ <button+ className="absolute top-3 right-3 grid size-7 place-items-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ aria-label="Close preview"+ onClick={onClose}+ >+ <X className="size-4" />+ </button>++ <div className="flex gap-1 rounded-full border border-border bg-card p-1 shadow-xs">+ {PLATFORMS.map((p) => (+ <button+ key={p.id}+ className={cn(+ "rounded-full px-3.5 py-1 text-xs font-medium transition-colors",+ platform === p.id+ ? "bg-foreground text-background"+ : "text-muted-foreground hover:text-foreground"+ )}+ aria-pressed={platform === p.id}+ onClick={() => setPlatform(p.id)}+ >+ {p.label}+ </button>+ ))}+ </div>++ <div className="phone relative h-[600px] w-[290px] overflow-hidden rounded-[38px] border-[9px] border-neutral-950 bg-black shadow-[0_24px_60px_rgba(0,0,0,0.45)]">+ <video+ ref={videoRef}+ src={url}+ className="absolute inset-0 size-full object-cover"+ autoPlay+ loop+ muted={muted}+ playsInline+ onClick={() => setMuted((m) => !m)}+ />+ {/* legibility gradients */}+ <div className="pointer-events-none absolute inset-x-0 top-0 h-20 bg-gradient-to-b from-black/50 to-transparent" />+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-44 bg-gradient-to-t from-black/70 via-black/25 to-transparent" />++ <button+ className="absolute top-3.5 left-3.5 z-20 grid size-7 place-items-center rounded-full bg-black/40 text-white"+ aria-label={muted ? "Unmute" : "Mute"}+ onClick={() => setMuted((m) => !m)}+ >+ {muted ? <VolumeX className="size-3.5" /> : <Volume2 className="size-3.5" />}+ </button>++ {platform === "tiktok" && (+ <TikTokChrome handle={handle} caption={caption} tags={tagsLine} sound={sound} />+ )}+ {platform === "instagram" && (+ <ReelsChrome handle={handle} caption={caption} tags={tagsLine} sound={sound} />+ )}+ {platform === "youtube" && (+ <ShortsChrome handle={handle} caption={caption} tags={tagsLine} sound={sound} />+ )}+ </div>+ </div>+ </div>+ </div>+ );+}++interface ChromeProps {+ handle: string;+ caption: string;+ tags: string;+ sound: string;+}++function Avatar({ className }: { className?: string }) {+ return (+ <span+ className={cn(+ "block rounded-full bg-gradient-to-br from-[#3d9bff] to-[#0a5fd4] ring-2 ring-white",+ className+ )}+ />+ );+}++function RailItem({+ icon,+ label,+}: {+ icon: React.ReactNode;+ label?: string;+}) {+ return (+ <div className="flex flex-col items-center gap-1">+ {icon}+ {label && (+ <span className={cn("text-[10px] font-semibold text-white", shadow)}>{label}</span>+ )}+ </div>+ );+}++function TikTokChrome({ handle, caption, tags, sound }: ChromeProps) {+ return (+ <div className="preview-tiktok pointer-events-none absolute inset-0 z-10">+ <div+ className={cn(+ "absolute top-4 inset-x-0 flex items-center justify-center gap-4 text-[13px] text-white",+ shadow+ )}+ >+ <span className="opacity-75">Following</span>+ <span className="relative font-semibold">+ For You+ <span className="absolute -bottom-1.5 left-1/2 h-0.5 w-5 -translate-x-1/2 rounded bg-white" />+ </span>+ <Search className="absolute right-4 size-4.5 text-white" />+ </div>++ <div className="absolute right-2.5 bottom-20 flex flex-col items-center gap-3.5">+ <div className="relative">+ <Avatar className="size-10" />+ <span className="absolute -bottom-1.5 left-1/2 grid size-4 -translate-x-1/2 place-items-center rounded-full bg-[#fe2c55] text-[10px] font-bold text-white">+ ++ </span>+ </div>+ <RailItem icon={<Heart className="size-7 fill-white text-white" />} label="328.7K" />+ <RailItem+ icon={<MessageCircle className="size-7 fill-white text-white" />}+ label="1,842"+ />+ <RailItem icon={<Bookmark className="size-6.5 fill-white text-white" />} label="12.3K" />+ <RailItem icon={<Share2 className="size-6.5 fill-white text-white" />} label="Share" />+ <span className="mt-0.5 grid size-9 animate-[spin_5s_linear_infinite] place-items-center rounded-full bg-neutral-900 ring-4 ring-neutral-800">+ <Music2 className="size-3.5 text-white" />+ </span>+ </div>++ <div className="absolute bottom-5 left-3 flex w-[72%] flex-col gap-1.5">+ <span className={cn("preview-handle text-[14px] font-semibold text-white", shadow)}>+ @{handle}+ </span>+ {(caption || tags) && (+ <p className={cn("preview-caption line-clamp-3 text-[12.5px] leading-snug text-white", shadow)}>+ {caption}+ {caption && tags ? " " : ""}+ {tags && <span className="font-semibold">{tags}</span>}+ </p>+ )}+ <div className={cn("flex items-center gap-1.5 text-[12px] text-white", shadow)}>+ <Music2 className="size-3.5 shrink-0" />+ <span className="preview-sound truncate">{sound}</span>+ </div>+ </div>+ </div>+ );+}++function ReelsChrome({ handle, caption, tags, sound }: ChromeProps) {+ return (+ <div className="preview-instagram pointer-events-none absolute inset-0 z-10">+ <div className="absolute top-4 inset-x-0 flex items-center justify-between px-4">+ <span className={cn("text-[17px] font-semibold text-white", shadow)}>Reels</span>+ <Camera className="size-5 text-white" />+ </div>++ <div className="absolute right-2.5 bottom-16 flex flex-col items-center gap-4">+ <RailItem icon={<Heart className="size-6.5 text-white" />} label="44.2K" />+ <RailItem icon={<MessageCircle className="size-6.5 -scale-x-100 text-white" />} label="512" />+ <RailItem icon={<Send className="size-6 text-white" />} />+ <RailItem icon={<Bookmark className="size-6 text-white" />} />+ <RailItem icon={<MoreHorizontal className="size-5.5 text-white" />} />+ <span className="grid size-6.5 place-items-center rounded-md border-2 border-white/85 bg-gradient-to-br from-fuchsia-500 to-amber-400">+ <Music2 className="size-3 text-white" />+ </span>+ </div>++ <div className="absolute bottom-4 left-3 flex w-[74%] flex-col gap-2">+ <div className="flex items-center gap-2">+ <Avatar className="size-7.5 ring-1" />+ <span className={cn("preview-handle text-[13px] font-semibold text-white", shadow)}>+ {handle}+ </span>+ <span className="rounded-md border border-white/80 px-1.5 py-0.5 text-[11px] font-medium text-white">+ Follow+ </span>+ </div>+ {(caption || tags) && (+ <p className={cn("preview-caption line-clamp-2 text-[12px] leading-snug text-white", shadow)}>+ {caption}+ {caption && tags ? " " : ""}+ {tags}+ <span className="text-white/60"> … more</span>+ </p>+ )}+ <div className="flex max-w-full items-center gap-1.5 self-start rounded-full border border-white/25 bg-black/35 px-2.5 py-1 backdrop-blur-sm">+ <Music2 className="size-3 shrink-0 text-white" />+ <span className={cn("preview-sound max-w-44 truncate text-[11px] text-white", shadow)}>+ {handle} · {sound}+ </span>+ </div>+ </div>+ </div>+ );+}++function ShortsChrome({ handle, caption, tags, sound }: ChromeProps) {+ return (+ <div className="preview-youtube pointer-events-none absolute inset-0 z-10">+ <div className="absolute top-4 inset-x-0 flex items-center justify-between px-4">+ <span className={cn("text-[17px] font-semibold text-white", shadow)}>Shorts</span>+ <div className="flex items-center gap-4">+ <Camera className="size-5 text-white" />+ <Search className="size-5 text-white" />+ <MoreHorizontal className="size-5 rotate-90 text-white" />+ </div>+ </div>++ <div className="absolute right-2.5 bottom-14 flex flex-col items-center gap-4">+ <RailItem icon={<ThumbsUp className="size-6 text-white" />} label="Like" />+ <RailItem icon={<ThumbsDown className="size-6 text-white" />} label="Dislike" />+ <RailItem icon={<MessageCircle className="size-6 -scale-x-100 text-white" />} label="1.2K" />+ <RailItem icon={<Share2 className="size-6 text-white" />} label="Share" />+ <span className="grid size-9 animate-[spin_6s_linear_infinite] place-items-center rounded-lg bg-neutral-900 ring-2 ring-white/20">+ <Music2 className="size-3.5 text-white" />+ </span>+ </div>++ <div className="absolute bottom-5 left-3 flex w-[74%] flex-col gap-2">+ <div className="flex items-center gap-2">+ <Avatar className="size-7.5 ring-1" />+ <span className={cn("preview-handle text-[13px] font-semibold text-white", shadow)}>+ @{handle}+ </span>+ <span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-semibold text-black">+ Subscribe+ </span>+ </div>+ {(caption || tags) && (+ <p className={cn("preview-caption line-clamp-2 text-[12.5px] leading-snug text-white", shadow)}>+ {caption}+ {caption && tags ? " " : ""}+ {tags}+ </p>+ )}+ <div className={cn("flex items-center gap-1.5 text-[11.5px] text-white", shadow)}>+ <Music2 className="size-3.5 shrink-0" />+ <span className="preview-sound truncate">{sound}</span>+ </div>+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/Preview.tsx b/site/src/cut/components/Preview.tsxnew file mode 100644index 00000000..641f6b8c--- /dev/null+++ b/site/src/cut/components/Preview.tsx@@ -0,0 +1,113 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { usePlayback } from "@/cut/hooks/usePlayback";+import { startDrag } from "@/cut/lib/drag";+import { getClipSpans, useEditor } from "@/cut/lib/store";+import { FRAME, type Aspect, type ClipSpan, type MediaAsset, type VideoClip } from "@/cut/lib/types";+import { cn } from "@/lib/utils";+import { OverlayLayer, SubtitleLayer } from "./OverlayLayer";++/** The clip under the playhead, when it overflows the frame in fill mode. */+function pannableSpan(s: {+ clips: VideoClip[];+ assets: MediaAsset[];+ currentTime: number;+ aspect: Aspect;+}): ClipSpan | null {+ const spans = getClipSpans(s.clips, s.assets);+ const span =+ spans.find((sp) => s.currentTime >= sp.start && sp.start + sp.len > s.currentTime) ??+ spans[spans.length - 1];+ if (!span || span.clip.fit !== "fill") return null;+ const { width, height } = span.asset;+ if (!width || !height) return null;+ const frame = FRAME[s.aspect];+ const scale = Math.max(frame.w / width, frame.h / height);+ const ox = width * scale - frame.w;+ const oy = height * scale - frame.h;+ return ox > 1 || oy > 1 ? span : null;+}++export function Preview() {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const wrapRef = useRef<HTMLDivElement>(null);+ const [stage, setStage] = useState({ w: 270, h: 480 });+ const pannable = useEditor((s) => pannableSpan(s) !== null);+ const aspect = useEditor((s) => s.aspect);+ const frame = FRAME[aspect];++ usePlayback(canvasRef);++ useEffect(() => {+ const wrap = wrapRef.current;+ if (!wrap) return;+ const [rw, rh] = aspect === "9:16" ? [9, 16] : [16, 9];+ const fit = () => {+ const r = wrap.getBoundingClientRect();+ const pad = 28;+ const availW = Math.max(120, r.width - pad);+ const availH = Math.max(120, r.height - pad);+ const scale = Math.min(availW / rw, availH / rh);+ setStage({ w: Math.floor(scale * rw), h: Math.floor(scale * rh) });+ };+ fit();+ const ro = new ResizeObserver(fit);+ ro.observe(wrap);+ return () => ro.disconnect();+ }, [aspect]);++ // Drag a fill-mode clip inside the frame to choose the visible crop.+ const panDrag = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ const span = pannableSpan(s);+ if (!span) return false;+ const fr = FRAME[s.aspect];+ const { width = 1, height = 1 } = span.asset;+ const scale = Math.max(fr.w / width, fr.h / height);+ const ox = width * scale - fr.w;+ const oy = height * scale - fr.h;+ const clipId = span.clip.id;+ const panX0 = span.clip.panX ?? 0;+ const panY0 = span.clip.panY ?? 0;+ const toFrame = fr.w / stage.w; // screen px → frame px+ s.select({ kind: "clip", id: clipId });+ s.pushHistory();+ startDrag(e, {+ onMove: (dx, dy) => {+ // Content follows the pointer; pan is the crop-window position.+ useEditor.getState().updateClipTransient(clipId, {+ panX: ox > 1 ? Math.max(-1, Math.min(1, panX0 - (dx * toFrame) / (ox / 2))) : 0,+ panY: oy > 1 ? Math.max(-1, Math.min(1, panY0 - (dy * toFrame) / (oy / 2))) : 0,+ });+ },+ });+ return true;+ };++ return (+ <section className="flex min-h-0 min-w-0 flex-col bg-muted/40">+ <div ref={wrapRef} className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-3">+ <div+ className={cn(+ "stage relative overflow-hidden rounded-xl bg-black shadow-[0_0_0_1px_rgba(0,0,0,0.08),0_12px_36px_rgba(0,0,0,0.18)]",+ pannable && "cursor-grab active:cursor-grabbing"+ )}+ style={{ width: stage.w, height: stage.h }}+ onPointerDown={(e) => {+ if (+ e.target === e.currentTarget ||+ (e.target as HTMLElement).tagName === "CANVAS"+ ) {+ if (!panDrag(e)) useEditor.getState().select(null);+ }+ }}+ >+ <canvas ref={canvasRef} width={frame.w} height={frame.h} className="block size-full" />+ <SubtitleLayer stageWidth={stage.w} />+ <OverlayLayer stageWidth={stage.w} />+ </div>+ </div>+ </section>+ );+}diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxnew file mode 100644index 00000000..0277498c--- /dev/null+++ b/site/src/cut/components/ProjectsHome.tsx@@ -0,0 +1,402 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import {+ Film,+ LayoutGrid,+ List,+ Loader2,+ MoreHorizontal,+ Pencil,+ Trash2,+} from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { formatTime } from "@/cut/lib/time";+import { mediaUrl, type ProjectSummary } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++type View = "gallery" | "list";++function formatDate(ts: number) {+ const d = new Date(ts);+ const now = Date.now();+ const mins = Math.floor((now - ts) / 60000);+ if (mins < 1) return "just now";+ if (mins < 60) return `${mins}m ago`;+ if (mins < 60 * 24) return `${Math.floor(mins / 60)}h ago`;+ return d.toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ ...(d.getFullYear() !== new Date().getFullYear() ? { year: "numeric" } : {}),+ });+}++export function ProjectsHome() {+ const router = useRouter();+ const [projects, setProjects] = useState<ProjectSummary[] | null>(null);+ const [view, setView] = useState<View>("gallery");+ const [createOpen, setCreateOpen] = useState(false);+ const [renaming, setRenaming] = useState<ProjectSummary | null>(null);+ const [deleting, setDeleting] = useState<ProjectSummary | null>(null);+ const [name, setName] = useState("");+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ const saved = localStorage.getItem("cut-projects-view");+ if (saved === "list" || saved === "gallery") setView(saved);+ }, []);++ const switchView = (v: View) => {+ setView(v);+ localStorage.setItem("cut-projects-view", v);+ };++ const refresh = useCallback(async () => {+ const res = await fetch("/api/projects");+ setProjects((await res.json()) as ProjectSummary[]);+ }, []);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ const create = async () => {+ setBusy(true);+ try {+ const res = await fetch("/api/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: name.trim() || "Untitled" }),+ });+ const project = (await res.json()) as ProjectSummary;+ router.push(`/p/${project.id}`);+ } finally {+ setBusy(false);+ }+ };++ const rename = async () => {+ if (!renaming) return;+ setBusy(true);+ try {+ await fetch(`/api/projects/${renaming.id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: name.trim() || renaming.name }),+ });+ setRenaming(null);+ await refresh();+ } finally {+ setBusy(false);+ }+ };++ const remove = async () => {+ if (!deleting) return;+ setBusy(true);+ try {+ await fetch(`/api/projects/${deleting.id}`, { method: "DELETE" });+ setDeleting(null);+ await refresh();+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div className="mb-5 flex items-center justify-between">+ <h1 className="text-lg font-semibold tracking-tight">Recent videos</h1>+ <div className="flex rounded-lg border border-border bg-card p-0.5">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Gallery view"+ aria-pressed={view === "gallery"}+ className={cn(view === "gallery" && "bg-muted text-foreground")}+ onClick={() => switchView("gallery")}+ >+ <LayoutGrid />+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="List view"+ aria-pressed={view === "list"}+ className={cn(view === "list" && "bg-muted text-foreground")}+ onClick={() => switchView("list")}+ >+ <List />+ </Button>+ </div>+ </div>++ {projects === null ? (+ <div className="grid place-items-center py-24 text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ ) : projects.length === 0 ? (+ <button+ className="grid w-full cursor-pointer place-items-center rounded-2xl border-2 border-dashed border-border py-24 transition-colors hover:border-primary/40"+ onClick={() => {+ setName("");+ setCreateOpen(true);+ }}+ >+ <div className="flex flex-col items-center gap-3 text-center">+ <Film className="size-8 text-muted-foreground" />+ <div className="text-base font-medium">No videos yet</div>+ <p className="max-w-xs text-sm text-muted-foreground">+ Create your first project, then drop in videos and music to start+ cutting.+ </p>+ </div>+ </button>+ ) : view === "gallery" ? (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(190px,1fr))] gap-5">+ {projects.map((p) => (+ <div+ key={p.id}+ className="group cursor-pointer"+ onClick={() => router.push(`/p/${p.id}`)}+ >+ {/* Vertical 9:16 tile — the project is mobile video, show it that way. */}+ <div className="relative grid aspect-[9/16] place-items-center overflow-hidden rounded-2xl border border-border bg-muted transition-shadow group-hover:shadow-[0_6px_28px_rgba(0,0,0,0.12)]">+ <CardPreview project={p} />+ <span className="absolute top-2 left-2 max-w-[70%] truncate rounded-lg bg-black/55 px-2 py-1 text-[11px] font-medium text-white backdrop-blur-sm">+ {p.name}+ </span>+ <span className="absolute right-2 bottom-2 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">+ {formatTime(p.duration)}+ </span>+ <ProjectMenu+ project={p}+ className="absolute top-1.5 right-1.5 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"+ onRename={() => {+ setName(p.name);+ setRenaming(p);+ }}+ onDelete={() => setDeleting(p)}+ />+ </div>+ <div className="mt-2 px-0.5 text-xs text-muted-foreground">+ {p.clipCount} {p.clipCount === 1 ? "clip" : "clips"} · edited{" "}+ {formatDate(p.updatedAt)}+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div className="overflow-hidden rounded-xl border border-border bg-card">+ <div className="grid grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border bg-muted/50 px-4 py-2 text-xs font-medium tracking-wide text-muted-foreground uppercase">+ <span>Name</span>+ <span>Length</span>+ <span>Clips</span>+ <span>Edited</span>+ <span />+ </div>+ {projects.map((p) => (+ <div+ key={p.id}+ className="group grid cursor-pointer grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border px-4 py-2.5 text-sm last:border-b-0 hover:bg-muted/50"+ onClick={() => router.push(`/p/${p.id}`)}+ >+ <span className="flex min-w-0 items-center gap-2.5">+ <Film className="size-4 shrink-0 text-muted-foreground" />+ <span className="truncate font-medium">{p.name}</span>+ </span>+ <span className="font-mono text-xs text-muted-foreground tabular-nums">+ {formatTime(p.duration)}+ </span>+ <span className="text-xs text-muted-foreground">{p.clipCount}</span>+ <span className="text-xs text-muted-foreground">+ {formatDate(p.updatedAt)}+ </span>+ <ProjectMenu+ project={p}+ onRename={() => {+ setName(p.name);+ setRenaming(p);+ }}+ onDelete={() => setDeleting(p)}+ />+ </div>+ ))}+ </div>+ )}++ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>New project</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ void create();+ }}+ >+ <Input+ autoFocus+ placeholder="Project name"+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ <DialogFooter className="mt-4">+ <Button type="submit" disabled={busy} className="w-full">+ {busy && <Loader2 className="animate-spin" data-icon="inline-start" />}+ Create project+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Rename project</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ void rename();+ }}+ >+ <Input autoFocus value={name} onChange={(e) => setName(e.target.value)} />+ <DialogFooter className="mt-4">+ <Button type="submit" disabled={busy} className="w-full">+ Rename+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ This deletes the whole project folder, including its media files+ and exports. This can’t be undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={busy}>Cancel</AlertDialogCancel>+ <AlertDialogAction+ disabled={busy}+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ void remove();+ }}+ >+ Delete project+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++/** Card art: a real frame from the project's first video, playing on hover. */+function CardPreview({ project: p }: { project: ProjectSummary }) {+ const videoRef = useRef<HTMLVideoElement>(null);++ if (!p.previewFile) {+ return (+ <Film className="size-7 text-muted-foreground/50 transition-transform group-hover:scale-110" />+ );+ }++ return (+ <div+ className="absolute inset-0"+ onMouseEnter={() => void videoRef.current?.play().catch(() => {})}+ onMouseLeave={() => {+ const v = videoRef.current;+ if (v) {+ v.pause();+ v.currentTime = 0.1;+ }+ }}+ >+ <video+ ref={videoRef}+ src={`${mediaUrl(p.id, p.previewFile)}#t=0.1`}+ muted+ loop+ playsInline+ preload="metadata"+ className="size-full object-cover"+ />+ </div>+ );+}++function ProjectMenu({+ project: _p,+ className,+ onRename,+ onDelete,+}: {+ project: ProjectSummary;+ className?: string;+ onRename: () => void;+ onDelete: () => void;+}) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Project actions"+ className={cn("bg-black/40 text-white hover:bg-black/60 hover:text-white", className)}+ onClick={(e) => e.stopPropagation()}+ />+ }+ >+ <MoreHorizontal />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>+ <DropdownMenuItem onClick={onRename}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/site/src/cut/components/RecordDialog.tsx b/site/src/cut/components/RecordDialog.tsxnew file mode 100644index 00000000..699506df--- /dev/null+++ b/site/src/cut/components/RecordDialog.tsx@@ -0,0 +1,209 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Mic, Square } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { formatTimecode } from "@/cut/lib/time";+import { cn } from "@/lib/utils";++export type RecordMode = "camera" | "audio";++function pickMime(mode: RecordMode) {+ // mp4 first: this Chrome produces empty webm video recordings.+ const candidates =+ mode === "camera"+ ? ["video/mp4", "video/webm;codecs=vp9,opus", "video/webm"]+ : ["audio/mp4", "audio/webm;codecs=opus", "audio/webm"];+ return candidates.find((c) => MediaRecorder.isTypeSupported(c)) ?? "";+}++function stamp() {+ const d = new Date();+ const p = (n: number) => String(n).padStart(2, "0");+ return `${p(d.getHours())}.${p(d.getMinutes())}.${p(d.getSeconds())}`;+}++export function RecordDialog({+ mode,+ onClose,+ onUse,+}: {+ mode: RecordMode;+ onClose: () => void;+ onUse: (file: File) => void;+}) {+ const [stream, setStream] = useState<MediaStream | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [recording, setRecording] = useState(false);+ const [elapsed, setElapsed] = useState(0);+ const videoRef = useRef<HTMLVideoElement>(null);+ const recorderRef = useRef<MediaRecorder | null>(null);+ const chunksRef = useRef<Blob[]>([]);+ const streamRef = useRef<MediaStream | null>(null);++ useEffect(() => {+ let canceled = false;+ navigator.mediaDevices+ .getUserMedia(+ mode === "camera"+ ? { video: { width: { ideal: 1920 }, height: { ideal: 1080 } }, audio: true }+ : { audio: true }+ )+ .then((s) => {+ if (canceled) {+ s.getTracks().forEach((t) => t.stop());+ return;+ }+ streamRef.current = s;+ setStream(s);+ })+ .catch(() =>+ setError(+ mode === "camera"+ ? "Camera access was blocked. Allow camera and microphone for this site in Chrome, then try again."+ : "Microphone access was blocked. Allow the microphone for this site in Chrome, then try again."+ )+ );+ return () => {+ canceled = true;+ recorderRef.current?.state === "recording" && recorderRef.current.stop();+ streamRef.current?.getTracks().forEach((t) => t.stop());+ };+ }, [mode]);++ useEffect(() => {+ if (stream && videoRef.current) {+ videoRef.current.srcObject = stream;+ void videoRef.current.play().catch(() => {});+ }+ }, [stream]);++ useEffect(() => {+ if (!recording) return;+ const start = Date.now();+ const t = setInterval(() => setElapsed((Date.now() - start) / 1000), 100);+ return () => clearInterval(t);+ }, [recording]);++ const startRecording = () => {+ if (!stream) return;+ const mimeType = pickMime(mode);+ const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);+ recorderRef.current = recorder;+ chunksRef.current = [];+ recorder.ondataavailable = (e) => {+ if (e.data.size > 0) chunksRef.current.push(e.data);+ };+ recorder.onstop = () => {+ const type = recorder.mimeType || (mode === "camera" ? "video/webm" : "audio/webm");+ const ext = type.includes("mp4") ? (mode === "camera" ? ".mp4" : ".m4a") : ".webm";+ const label = mode === "camera" ? "Camera" : "Voice";+ const file = new File(chunksRef.current, `${label} recording ${stamp()}${ext}`, { type });+ if (file.size === 0) {+ setRecording(false);+ setError("The recording came back empty. Check that no other app is using the camera, then try again.");+ return;+ }+ onUse(file);+ onClose();+ };+ recorder.start(250);+ setElapsed(0);+ setRecording(true);+ };++ const stopRecording = () => {+ setRecording(false);+ recorderRef.current?.stop();+ };++ return (+ <Dialog open onOpenChange={(o) => !o && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{mode === "camera" ? "Record camera" : "Record audio"}</DialogTitle>+ </DialogHeader>++ {error ? (+ <p className="text-sm text-muted-foreground">{error}</p>+ ) : (+ <>+ {mode === "camera" ? (+ <div className="relative overflow-hidden rounded-xl bg-black">+ {/* Mirrored preview; the recording itself is not mirrored. */}+ <video+ ref={videoRef}+ muted+ playsInline+ className="aspect-video w-full -scale-x-100 object-cover"+ />+ {recording && <RecTimer elapsed={elapsed} />}+ </div>+ ) : (+ <div className="relative grid h-36 place-items-center rounded-xl bg-muted">+ <span+ className={cn(+ "grid size-16 place-items-center rounded-full bg-card text-foreground shadow-sm",+ recording && "animate-pulse text-red-500"+ )}+ >+ <Mic className="size-7" />+ </span>+ {recording && <RecTimer elapsed={elapsed} />}+ </div>+ )}++ <div className="mt-1 flex justify-center">+ {!recording ? (+ <button+ className="grid size-12 place-items-center rounded-full border-[3px] border-foreground/20 transition-transform hover:scale-105 disabled:opacity-40"+ title="Start recording"+ disabled={!stream}+ onClick={startRecording}+ >+ <span className="size-8 rounded-full bg-red-500" />+ </button>+ ) : (+ <button+ className="grid size-12 place-items-center rounded-full border-[3px] border-red-500/40 transition-transform hover:scale-105"+ title="Stop and use recording"+ onClick={stopRecording}+ >+ <Square className="size-5 fill-red-500 stroke-none" />+ </button>+ )}+ </div>+ <p className="text-center text-xs text-muted-foreground">+ {recording+ ? "Recording — click stop to drop it on the timeline."+ : stream+ ? "Click the red button to start."+ : "Waiting for permission…"}+ </p>+ </>+ )}++ <div className="flex justify-end">+ <Button variant="ghost" onClick={onClose}>+ Cancel+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ );+}++function RecTimer({ elapsed }: { elapsed: number }) {+ return (+ <span className="absolute top-2 left-2 flex items-center gap-1.5 rounded-md bg-black/60 px-2 py-1 font-mono text-xs text-white tabular-nums">+ <span className="size-2 animate-pulse rounded-full bg-red-500" />+ {formatTimecode(elapsed)}+ </span>+ );+}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxnew file mode 100644index 00000000..371efe81--- /dev/null+++ b/site/src/cut/components/SidePanel.tsx@@ -0,0 +1,515 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { Captions, Check, Circle, Copy, Film, FolderOpen, FolderPlus, Loader2, Mic, Music, Play, Plus, Send, Type, Upload, Video } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { setAssetDragData } from "@/cut/lib/assetDrag";+import {+ addLibraryAssetToProject,+ fetchLibrary,+ saveAssetToLibrary,+ type LibraryAsset,+} from "@/cut/lib/library";+import { CAPTION_LIMIT, normalizeTags } from "@/cut/lib/publish";+import { useEditor } from "@/cut/lib/store";+import { formatTime } from "@/cut/lib/time";+import type { MediaAsset } from "@/cut/lib/types";+import { cn } from "@/lib/utils";+import { LibraryCard } from "./LibraryView";+import { PlatformPreviewDialog, type ExportItem } from "./PlatformPreview";+import { RecordDialog, type RecordMode } from "./RecordDialog";+import { SubtitlesPanel } from "./SubtitlesPanel";++type Tab = "media" | "library" | "record" | "text" | "subtitles" | "publish";++const TABS: { id: Tab; label: string; icon: typeof Film }[] = [+ { id: "media", label: "Media", icon: Film },+ { id: "library", label: "Library", icon: FolderOpen },+ { id: "record", label: "Record", icon: Circle },+ { id: "text", label: "Text", icon: Type },+ { id: "subtitles", label: "Subtitles", icon: Captions },+ { id: "publish", label: "Publish", icon: Send },+];++export function SidePanel({+ projectId,+ onImport,+ importing,+}: {+ projectId: string;+ onImport: (files: FileList | File[]) => void;+ importing: boolean;+}) {+ const [tab, setTab] = useState<Tab>("media");+ const [recordMode, setRecordMode] = useState<RecordMode | null>(null);++ return (+ <div className="flex min-h-0 border-r border-border bg-card">+ {/* Icon rail */}+ <div className="flex w-[68px] shrink-0 flex-col items-center gap-1 border-r border-border py-3">+ {TABS.map(({ id, label, icon: Icon }) => {+ const tileClass =+ "flex flex-col items-center gap-1 rounded-lg px-2 py-1.5 text-muted-foreground transition-colors hover:text-foreground";+ const inner = (+ <>+ <span+ className={cn(+ "grid size-9 place-items-center rounded-lg transition-colors",+ tab === id ? "bg-muted text-foreground" : "hover:bg-muted/60"+ )}+ >+ <Icon className="size-4.5" />+ </span>+ <span className={cn("text-[10px] font-medium", tab === id && "text-foreground")}>+ {label}+ </span>+ </>+ );++ if (id === "record") {+ return (+ <DropdownMenu key={id}>+ <DropdownMenuTrigger render={<button className={tileClass} />}>+ {inner}+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ side="right"+ style={{ width: "12rem" }}+ >+ <DropdownMenuItem onClick={() => setRecordMode("camera")}>+ <Video /> Record camera+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setRecordMode("audio")}>+ <Mic /> Record audio+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );+ }++ return (+ <button+ key={id}+ className={tileClass}+ aria-pressed={tab === id}+ onClick={() => setTab(id)}+ >+ {inner}+ </button>+ );+ })}+ </div>++ <div className="flex w-[264px] min-h-0 shrink-0 flex-col">+ {tab === "media" && (+ <MediaPanel projectId={projectId} onImport={onImport} importing={importing} />+ )}+ {tab === "library" && <LibraryPanel projectId={projectId} />}+ {tab === "text" && <TextPanel />}+ {tab === "subtitles" && <SubtitlesPanel />}+ {tab === "publish" && <PublishPanel />}+ </div>+ {recordMode && (+ <RecordDialog+ mode={recordMode}+ onClose={() => setRecordMode(null)}+ onUse={(file) => onImport([file])}+ />+ )}+ </div>+ );+}++function PanelHead({ title, action }: { title: string; action?: React.ReactNode }) {+ return (+ <div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">+ <span className="text-sm font-semibold tracking-tight">{title}</span>+ {action}+ </div>+ );+}++function MediaPanel({+ projectId,+ onImport,+ importing,+}: {+ projectId: string;+ onImport: (files: FileList) => void;+ importing: boolean;+}) {+ const assets = useEditor((s) => s.assets);+ const exportOpen = useEditor((s) => s.exportOpen);+ const inputRef = useRef<HTMLInputElement>(null);+ const [exports, setExports] = useState<ExportItem[]>([]);+ const [preview, setPreview] = useState<ExportItem | null>(null);++ // Refresh the list on open and every time the export dialog closes.+ useEffect(() => {+ if (exportOpen) return;+ let alive = true;+ void fetch(`/api/projects/${projectId}/exports`)+ .then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : []))+ .then((list) => alive && setExports(list))+ .catch(() => {});+ return () => {+ alive = false;+ };+ }, [projectId, exportOpen]);++ return (+ <>+ <PanelHead title="Media" />+ <div className="px-3.5 pb-3">+ <Button variant="outline" className="w-full" onClick={() => inputRef.current?.click()}>+ <Upload data-icon="inline-start" /> Upload+ </Button>+ <input+ ref={inputRef}+ type="file"+ accept="video/*,audio/*"+ multiple+ hidden+ onChange={(e) => {+ if (e.target.files?.length) onImport(e.target.files);+ e.target.value = "";+ }}+ />+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto pb-3.5">+ {assets.length === 0 && !importing ? (+ <div className="mx-3.5 rounded-xl border-[1.5px] border-dashed border-input px-4 py-7 text-center text-xs leading-relaxed text-muted-foreground">+ <div className="mb-3 flex justify-center gap-3.5">+ <Film className="size-5" />+ <Music className="size-5" />+ </div>+ Drop videos and music anywhere, or upload to this project.+ </div>+ ) : (+ <div className="grid grid-cols-2 content-start gap-2.5 px-3.5">+ {assets.map((a) => (+ <AssetCard key={a.id} asset={a} projectId={projectId} />+ ))}+ {importing && (+ <div className="flex aspect-square flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-input text-[11px] text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ Importing…+ </div>+ )}+ </div>+ )}++ {exports.length > 0 && (+ <div className="mt-5 px-3.5">+ <div className="mb-2 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">+ Exports+ </div>+ <div className="flex flex-col gap-1.5">+ {exports.map((it) => (+ <button+ key={it.file}+ className="export-row flex w-full items-center gap-2.5 rounded-lg border border-border p-1.5 text-left transition-colors hover:border-input hover:bg-muted/50"+ title="Preview as a post"+ onClick={() => setPreview(it)}+ >+ <video+ muted+ playsInline+ preload="metadata"+ src={`/api/projects/${projectId}/exports/${encodeURIComponent(it.file)}#t=0.1`}+ className="h-11 w-[25px] shrink-0 rounded-[4px] bg-black object-cover"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[11.5px] font-medium">+ {new Date(it.mtime).toLocaleString([], {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ })}+ </span>+ <span className="block text-[10.5px] text-muted-foreground">+ {(it.size / (1024 * 1024)).toFixed(1)} MB · MP4+ </span>+ </span>+ <span className="mr-1 flex items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">+ <Play className="size-2.5" /> Play+ </span>+ </button>+ ))}+ </div>+ </div>+ )}+ </div>+ {preview && (+ <PlatformPreviewDialog+ projectId={projectId}+ item={preview}+ onClose={() => setPreview(null)}+ />+ )}+ </>+ );+}++function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string }) {+ const [saved, setSaved] = useState(false);+ const videoRef = useRef<HTMLVideoElement>(null);++ const add = () => {+ const s = useEditor.getState();+ if (asset.type === "video") s.addClipFromAsset(asset.id);+ else s.addAudioFromAsset(asset.id);+ };++ const saveToLibrary = async (e: React.MouseEvent) => {+ e.stopPropagation();+ try {+ await saveAssetToLibrary(projectId, asset);+ setSaved(true);+ setTimeout(() => setSaved(false), 1800);+ } catch {+ // Library write failed; nothing to roll back.+ }+ };++ return (+ <button+ className="asset-card group flex flex-col gap-1.5 text-left"+ title="Add to timeline"+ draggable+ onDragStart={(e) => setAssetDragData(e, asset.id)}+ onClick={add}+ onMouseEnter={() => {+ void videoRef.current?.play().catch(() => {});+ }}+ onMouseLeave={() => {+ const v = videoRef.current;+ if (v) {+ v.pause();+ v.currentTime = 0.1;+ }+ }}+ >+ <div className="relative aspect-square overflow-hidden rounded-lg border border-border bg-muted transition-colors group-hover:border-input">+ {asset.type === "video" ? (+ // Native first frame as the poster — full-resolution, no blurry thumb.+ <video+ ref={videoRef}+ src={`${asset.url}#t=0.1`}+ preload="metadata"+ muted+ loop+ playsInline+ className="size-full object-cover"+ />+ ) : (+ <div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600">+ <Music className="size-4.5" />+ </div>+ )}+ <span className="absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">+ {formatTime(asset.duration)}+ </span>+ <span className="absolute top-1 left-1 grid size-5 scale-75 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-all group-hover:scale-100 group-hover:opacity-100">+ <Plus className="size-3" />+ </span>+ <span+ role="button"+ title="Save to library for reuse"+ className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-black/45 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/65"+ onClick={saveToLibrary}+ >+ {saved ? <Check className="size-3" /> : <FolderPlus className="size-3" />}+ </span>+ </div>+ <div className="truncate text-[11px] text-muted-foreground">{asset.name}</div>+ </button>+ );+}++function LibraryPanel({ projectId }: { projectId: string }) {+ const [assets, setAssets] = useState<LibraryAsset[] | null>(null);++ useEffect(() => {+ void fetchLibrary().then(setAssets).catch(() => setAssets([]));+ }, []);++ return (+ <>+ <PanelHead title="Library" />+ <p className="px-4 pb-3 text-[11.5px] leading-relaxed text-muted-foreground">+ Reusable clips & music. Click to add a copy to this project.+ </p>+ {assets === null ? (+ <div className="grid flex-1 place-items-center text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ </div>+ ) : assets.length === 0 ? null : (+ <div className="grid grid-cols-2 content-start gap-2.5 overflow-y-auto px-3.5 pb-3.5">+ {assets.map((a) => (+ <LibraryCard+ key={a.id}+ asset={a}+ onUse={() => void addLibraryAssetToProject(projectId, a)}+ />+ ))}+ </div>+ )}+ </>+ );+}++function TextPanel() {+ return (+ <>+ <PanelHead title="Text" />+ <div className="px-3.5">+ <Button+ variant="outline"+ className="w-full"+ onClick={() => useEditor.getState().addOverlay()}+ >+ <Type data-icon="inline-start" /> Add a title+ </Button>+ <p className="mt-3 text-[11.5px] leading-relaxed text-muted-foreground">+ Titles land at the playhead. Drag them around the preview, resize with+ the corner handle, and double-click to edit in place. Font, color,+ shadow, and backdrop are in the inspector.+ </p>+ </div>+ </>+ );+}++function CopyChip({ text, label }: { text: string; label: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <button+ className="copy-chip inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"+ disabled={!text}+ title={`Copy ${label}`}+ onClick={() => {+ void navigator.clipboard.writeText(text).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ });+ }}+ >+ {copied ? <Check className="size-3 text-emerald-600" /> : <Copy className="size-3" />}+ {copied ? "Copied" : "Copy"}+ </button>+ );+}++function PublishPanel() {+ const publish = useEditor((s) => s.publish);+ const setPublish = useEditor((s) => s.setPublish);+ const tagsLine = normalizeTags(publish.tags);+ const combined = [publish.caption.trim(), tagsLine].filter(Boolean).join("\n\n");+ const count = combined.length;+ const [copiedAll, setCopiedAll] = useState(false);++ const field = "text-[11px] font-semibold tracking-wider text-muted-foreground uppercase";++ return (+ <>+ <PanelHead title="Publish" />+ <div className="flex min-h-0 flex-col gap-4 overflow-y-auto px-3.5 pb-4">+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <span className={field}>Caption</span>+ <CopyChip text={publish.caption.trim()} label="caption" />+ </div>+ <textarea+ className="publish-caption min-h-[110px] w-full resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"+ placeholder={"What's happening in this video?\n\nHooks read best in the first line."}+ value={publish.caption}+ onChange={(e) => setPublish({ caption: e.target.value })}+ />+ </div>++ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <span className={field}>Tags</span>+ <CopyChip text={tagsLine} label="tags" />+ </div>+ <input+ className="publish-tags w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"+ placeholder="fyp howto cut"+ value={publish.tags}+ onChange={(e) => setPublish({ tags: e.target.value })}+ />+ {tagsLine && (+ <div className="publish-tag-preview flex flex-wrap gap-1">+ {tagsLine.split(" ").map((t) => (+ <span key={t} className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10.5px]">+ {t}+ </span>+ ))}+ </div>+ )}+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ 3–5 focused tags work best. Tags count toward the caption limit.+ </p>+ </div>++ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <span className={field}>Sound title</span>+ <CopyChip text={publish.soundTitle.trim()} label="sound title" />+ </div>+ <input+ className="publish-sound w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] outline-none focus:border-ring"+ placeholder="My track — artist"+ value={publish.soundTitle}+ onChange={(e) => setPublish({ soundTitle: e.target.value })}+ />+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ TikTok names uploads “original sound – you”. You can rename the+ sound once after posting — paste this then.+ </p>+ </div>++ <div className="mt-1 flex flex-col gap-2">+ <Button+ className="w-full"+ disabled={!combined}+ onClick={() => {+ void navigator.clipboard.writeText(combined).then(() => {+ setCopiedAll(true);+ setTimeout(() => setCopiedAll(false), 1500);+ });+ }}+ >+ {copiedAll ? (+ <>+ <Check data-icon="inline-start" /> Copied+ </>+ ) : (+ <>+ <Copy data-icon="inline-start" /> Copy caption + tags+ </>+ )}+ </Button>+ <p+ className={cn(+ "publish-count text-right font-mono text-[11px] tabular-nums",+ count > CAPTION_LIMIT ? "font-semibold text-red-600" : "text-muted-foreground"+ )}+ >+ {count.toLocaleString()} / {CAPTION_LIMIT.toLocaleString()}+ </p>+ </div>+ </div>+ </>+ );+}diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxnew file mode 100644index 00000000..9ce02981--- /dev/null+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -0,0 +1,300 @@+"use client";++import { memo, useEffect, useRef, useState } from "react";+import { AlertCircle, Captions, ChevronDown, Loader2, MicOff, RefreshCw } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { fmtCueTime } from "@/cut/lib/subtitles";+import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";+import type { SubtitleCue } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++const LOCALES = [+ ["en-US", "English (US)"],+ ["en-GB", "English (UK)"],+ ["es-ES", "Español"],+ ["fr-FR", "Français"],+ ["de-DE", "Deutsch"],+ ["it-IT", "Italiano"],+ ["pt-BR", "Português (BR)"],+ ["ja-JP", "日本語"],+ ["ko-KR", "한국어"],+ ["zh-CN", "中文"],+ ["vi-VN", "Tiếng Việt"],+] as const;++/** Give the cue track room when it appears. */+const TIMELINE_H_WITH_SUBS = Math.max(TIMELINE_H_MIN, 276);++export function SubtitlesPanel() {+ const subtitles = useEditor((s) => s.subtitles);+ const status = useEditor((s) => s.subtitleStatus);+ const error = useEditor((s) => s.subtitleError);+ const hasCues = subtitles.cues.length > 0;++ const generate = () => {+ const s = useEditor.getState();+ void s.generateSubtitles().then(() => {+ const cur = useEditor.getState();+ if (cur.subtitles.cues.length > 0 && cur.timelineH < TIMELINE_H_WITH_SUBS)+ cur.setTimelineH(TIMELINE_H_WITH_SUBS);+ });+ };++ return (+ <>+ <div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">+ <span className="text-sm font-semibold tracking-tight">Subtitles</span>+ {hasCues && (+ <Button+ variant="ghost"+ size="sm"+ className="sub-regenerate"+ title="Transcribe the cut again (replaces these captions — undoable)"+ disabled={status === "running"}+ onClick={generate}+ >+ {status === "running" ? (+ <Loader2 className="animate-spin" />+ ) : (+ <RefreshCw />+ )}+ Regenerate+ </Button>+ )}+ </div>++ {!hasCues ? (+ <EmptyState status={status} error={error} onGenerate={generate} />+ ) : (+ <>+ <div className="flex shrink-0 flex-col gap-2 border-b border-border px-4 pb-3">+ <label className="flex items-center justify-between text-xs font-medium">+ Show on video+ <Switch+ className="sub-show-video"+ checked={subtitles.showOnVideo}+ onCheckedChange={(v) => useEditor.getState().setSubtitlesView({ showOnVideo: v })}+ />+ </label>+ <label className="flex items-center justify-between text-xs font-medium">+ Show on timeline+ <Switch+ className="sub-show-timeline"+ checked={subtitles.showOnTimeline}+ onCheckedChange={(v) => {+ const s = useEditor.getState();+ s.setSubtitlesView({ showOnTimeline: v });+ if (v && s.timelineH < TIMELINE_H_WITH_SUBS) s.setTimelineH(TIMELINE_H_WITH_SUBS);+ }}+ />+ </label>+ {status === "running" && (+ <p className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Loader2 className="size-3 animate-spin" /> Re-transcribing on this Mac…+ </p>+ )}+ {status === "error" && error && (+ <p className="sub-error text-[11px] leading-relaxed text-red-600">{error}</p>+ )}+ </div>+ <Transcript cues={subtitles.cues} />+ <p className="shrink-0 border-t border-border px-4 py-2 text-[10.5px] leading-relaxed text-muted-foreground">+ Click a timestamp to jump there. Return splits a caption at the+ cursor (new timestamp) · ⌫ at the start merges it into the one+ before · delete all its text to remove it.+ </p>+ </>+ )}+ </>+ );+}++function EmptyState({+ status,+ error,+ onGenerate,+}: {+ status: string;+ error: string | null;+ onGenerate: () => void;+}) {+ const locale = useEditor((s) => s.subtitles.locale ?? "en-US");++ if (status === "running") {+ return (+ <div className="sub-generating flex flex-col items-center gap-3 px-6 pt-10 text-center">+ <Loader2 className="size-5 animate-spin text-muted-foreground" />+ <p className="text-[13px] font-medium">Transcribing on this Mac…</p>+ <p className="text-[11.5px] leading-relaxed text-muted-foreground">+ Runs in the background — keep editing. Captions appear here when+ it finishes.+ </p>+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-3 px-3.5">+ {status === "empty" && (+ <div className="sub-empty flex items-start gap-2 rounded-lg bg-muted/70 px-3 py-2.5 text-[11.5px] leading-relaxed text-muted-foreground">+ <MicOff className="mt-0.5 size-3.5 shrink-0" />+ No speech was found in this cut, so no subtitles were added to the+ video.+ </div>+ )}+ {status === "error" && error && (+ <div className="sub-error flex items-start gap-2 rounded-lg bg-red-50 px-3 py-2.5 text-[11.5px] leading-relaxed text-red-700">+ <AlertCircle className="mt-0.5 size-3.5 shrink-0" />+ {error}+ </div>+ )}+ <div className="flex flex-col items-center gap-1 pt-4 pb-1 text-center">+ <Captions className="mb-1 size-6 text-muted-foreground" />+ <p className="text-[13px] font-semibold">Subtitles from your audio</p>+ <p className="text-[11.5px] leading-relaxed text-muted-foreground">+ Transcribed with Apple speech recognition, entirely on this Mac —+ your audio never leaves it.+ </p>+ </div>+ <div className="relative">+ <select+ className="sub-locale w-full appearance-none rounded-lg border border-input bg-transparent py-2 pr-9 pl-2.5 text-[12.5px] outline-none focus:border-ring"+ value={locale}+ onChange={(e) => useEditor.getState().setSubtitlesView({ locale: e.target.value })}+ >+ {LOCALES.map(([id, label]) => (+ <option key={id} value={id}>+ {label}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute top-1/2 right-3 size-4 -translate-y-1/2 text-muted-foreground" />+ </div>+ <Button className="sub-generate w-full" onClick={onGenerate}>+ <Captions data-icon="inline-start" />+ {status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}+ </Button>+ </div>+ );+}++/** Opus-style flowing transcript: paragraphs of editable captions with+ * timestamp chips, plus pause chips where the speech leaves a gap. */+function Transcript({ cues }: { cues: SubtitleCue[] }) {+ // A pause over 2s starts a new paragraph; over 0.5s shows a pause chip.+ const paragraphs: { cue: SubtitleCue; gap: number }[][] = [];+ cues.forEach((cue, i) => {+ const gap = i === 0 ? 0 : cue.start - cues[i - 1].end;+ if (i === 0 || gap > 2) paragraphs.push([]);+ paragraphs[paragraphs.length - 1].push({ cue, gap });+ });++ return (+ <div className="sub-transcript min-h-0 flex-1 select-text overflow-y-auto px-4 py-3">+ {paragraphs.map((para) => (+ <p key={para[0].cue.id} className="mb-4 text-[12.5px] leading-[1.9]">+ {para.map(({ cue, gap }) => (+ <CueSpan key={cue.id} cue={cue} gap={gap} />+ ))}+ </p>+ ))}+ </div>+ );+}++function caretOffset(el: HTMLElement): number {+ const sel = window.getSelection();+ if (!sel || sel.rangeCount === 0) return 0;+ const range = sel.getRangeAt(0).cloneRange();+ range.selectNodeContents(el);+ range.setEnd(sel.getRangeAt(0).endContainer, sel.getRangeAt(0).endOffset);+ return range.toString().length;+}++const CueSpan = memo(function CueSpan({ cue, gap }: { cue: SubtitleCue; gap: number }) {+ const active = useEditor((s) => {+ const t = !s.playing && s.skimTime !== null ? s.skimTime : s.currentTime;+ return t >= cue.start && t < cue.end;+ });+ const ref = useRef<HTMLSpanElement>(null);+ const [focused, setFocused] = useState(false);++ // The span is uncontrolled while focused (so the caret survives typing);+ // outside edits (undo, regenerate) sync the DOM here.+ useEffect(() => {+ const el = ref.current;+ if (el && document.activeElement !== el && el.textContent !== cue.text)+ el.textContent = cue.text;+ }, [cue.text]);++ // Follow along during playback.+ useEffect(() => {+ if (active && useEditor.getState().playing)+ ref.current?.scrollIntoView({ block: "nearest", behavior: "smooth" });+ }, [active]);++ const commit = () => {+ setFocused(false);+ const el = ref.current;+ if (el) useEditor.getState().setCueText(cue.id, el.textContent ?? "");+ };++ return (+ <span className="sub-cue">+ {gap > 0.5 && (+ <span+ className="sub-gap mx-0.5 inline-block rounded-md bg-muted px-1.5 py-px align-baseline font-mono text-[10px] text-muted-foreground/80"+ title={`${gap.toFixed(1)}s pause`}+ >+ · {gap.toFixed(1)}s ·+ </span>+ )}+ <button+ className={cn(+ "sub-time mr-1 inline-block cursor-pointer rounded-md bg-muted px-1.5 py-px align-baseline font-mono text-[10px] tabular-nums text-muted-foreground transition-colors hover:bg-[#0a84ff]/15 hover:text-[#0a84ff]",+ active && "bg-[#0a84ff] text-white hover:bg-[#0a84ff] hover:text-white"+ )}+ title="Jump here"+ tabIndex={-1}+ onClick={() => useEditor.getState().seek(cue.start + 0.001)}+ >+ {fmtCueTime(cue.start)}+ </button>+ <span+ ref={ref}+ className={cn(+ "sub-text rounded-sm px-0.5 outline-none",+ active && "bg-[#0a84ff]/10",+ focused && "ring-1 ring-[#0a84ff]/40"+ )}+ contentEditable+ suppressContentEditableWarning+ spellCheck={false}+ data-cue={cue.id}+ onFocus={() => setFocused(true)}+ onBlur={commit}+ onKeyDown={(e) => {+ e.stopPropagation();+ const el = ref.current;+ if (!el) return;+ if (e.key === "Escape") {+ e.preventDefault();+ el.blur();+ } else if (e.key === "Enter") {+ e.preventDefault();+ const off = caretOffset(el);+ // Blur first: it commits any typing (dropping stale word+ // timings), then the split uses whatever timing survives.+ el.blur();+ useEditor.getState().splitCue(cue.id, off);+ } else if (e.key === "Backspace" && caretOffset(el) === 0 && window.getSelection()?.isCollapsed) {+ e.preventDefault();+ el.blur(); // commit typing (or delete the cue if emptied)+ useEditor.getState().mergeCueIntoPrev(cue.id);+ }+ }}+ />{" "}+ </span>+ );+});diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxnew file mode 100644index 00000000..db207631--- /dev/null+++ b/site/src/cut/components/Timeline.tsx@@ -0,0 +1,1011 @@+"use client";++import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { AudioLines, EllipsisVertical, Music, Pause, Play, Plus, Scissors, SkipBack, Trash2, Type, VolumeX } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Slider } from "@/components/ui/slider";+import { draggedAssetId, hasAssetDrag } from "@/cut/lib/assetDrag";+import { startDrag } from "@/cut/lib/drag";+import { ensurePeaks } from "@/cut/lib/media";+import { clipLen, getClipSpans, TIMELINE_H_MAX, totalDuration, useEditor } from "@/cut/lib/store";+import { formatTime, formatTimecode } from "@/cut/lib/time";+import type { AudioClip, ClipSpan, MediaAsset, SubtitleCue, TextOverlay } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++const VIDEO_H = 64;+const AUDIO_H = 44;+const TEXT_H = 28;+const SUB_H = 22;+const PAD_END = 320;+/** Breathing room on both sides so the playhead cap is never clipped. */+const PAD_SIDE = 20;+/** Visual gutter between adjacent clips (iMovie); time math stays exact. */+const CLIP_GAP = 4;++const SELECTED_SHADOW =+ "shadow-[inset_0_0_0_2px_#0a84ff,0_0_12px_rgba(10,132,255,0.25)]";++const trimHandle =+ "tl-trim absolute top-0 bottom-0 z-3 w-[10px] cursor-ew-resize after:absolute after:top-1/2 after:left-[3px] after:h-[calc(100%-10px)] after:w-1 after:-translate-y-1/2 after:rounded-full after:bg-white after:opacity-0 after:shadow-[0_0_0_1px_rgba(0,0,0,0.35)] after:transition-opacity group-hover:after:opacity-90 hover:after:opacity-100";++/** Live reorder-drag on the video track: ghost offset plus the open slot. */+interface ClipDrag {+ id: string;+ dx: number; // ghost offset in px (mouse + auto-scroll)+ dy: number; // vertical lift in px, clamped — iMovie's picked-up feel+ from: number; // original index in spans+ to: number; // insertion index while dragging+ len: number; // dragged clip length, seconds+ gapStart: number; // open slot position, seconds+}++/**+ * Insertion index for a dragged clip (iMovie): the edge leading the drag+ * direction opens a slot once it crosses a neighbor's midpoint.+ */+function dropIndex(spans: ClipSpan[], from: number, dxSec: number): number {+ const d = spans[from];+ let to = from;+ if (dxSec > 0) {+ const edge = d.start + d.len + dxSec; // right edge leads+ for (let k = from + 1; k < spans.length; k++)+ if (edge > spans[k].start + spans[k].len / 2) to = k;+ } else if (dxSec < 0) {+ const edge = d.start + dxSec; // left edge leads+ for (let k = from - 1; k >= 0; k--)+ if (edge < spans[k].start + spans[k].len / 2) to = k;+ }+ return to;+}++export function Timeline() {+ const clips = useEditor((s) => s.clips);+ const audioClips = useEditor((s) => s.audioClips);+ const overlays = useEditor((s) => s.overlays);+ const assets = useEditor((s) => s.assets);+ const pps = useEditor((s) => s.pxPerSec);+ const timelineH = useEditor((s) => s.timelineH);+ const selection = useEditor((s) => s.selection);+ const subtitles = useEditor((s) => s.subtitles);+ const scrollRef = useRef<HTMLDivElement>(null);+ const innerRef = useRef<HTMLDivElement>(null);++ const spans = useMemo(() => getClipSpans(clips, assets), [clips, assets]);+ const total = totalDuration(clips);+ const contentW = Math.max(total * pps + PAD_END, 900);++ // Reorder drag on the video track: neighbors part to open a highlighted+ // slot at the insertion point; releasing drops the clip into it.+ const [clipDrag, setClipDrag] = useState<{ id: string; dx: number; dy: number } | null>(null);+ const dragInfo = useMemo<ClipDrag | null>(() => {+ if (!clipDrag) return null;+ const from = spans.findIndex((sp) => sp.clip.id === clipDrag.id);+ if (from < 0) return null;+ const to = dropIndex(spans, from, clipDrag.dx / pps);+ const len = spans[from].len;+ const gapStart = to <= from ? spans[to].start : spans[to].start + spans[to].len - len;+ return { id: clipDrag.id, dx: clipDrag.dx, dy: clipDrag.dy, from, to, len, gapStart };+ }, [clipDrag, spans, pps]);++ const onClipDrag = useCallback(+ (id: string, dx: number, dy: number) => setClipDrag({ id, dx, dy }),+ []+ );+ const onClipDrop = useCallback((id: string, dx: number | null) => {+ setClipDrag(null);+ if (dx === null) return;+ const s = useEditor.getState();+ const sp = getClipSpans(s.clips, s.assets);+ const from = sp.findIndex((x) => x.clip.id === id);+ if (from >= 0) s.moveClip(id, dropIndex(sp, from, dx / s.pxPerSec));+ }, []);++ const timeAt = (clientX: number) => {+ const rect = innerRef.current!.getBoundingClientRect();+ return (clientX - rect.left) / pps;+ };++ // Scrub with auto-scroll when the pointer nears the viewport edges.+ const scrub = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.seek(timeAt(e.clientX));+ const el = scrollRef.current;+ startDrag(e, {+ onMove: (_dx, _dy, ev) => {+ if (el) {+ const r = el.getBoundingClientRect();+ if (ev.clientX > r.right - 36) el.scrollLeft += 14;+ else if (ev.clientX < r.left + 36) el.scrollLeft -= 14;+ }+ useEditor.getState().seek(timeAt(ev.clientX));+ },+ });+ };++ // Clicking empty track space deselects AND moves the playhead (iMovie).+ const deselectIfSelf = (e: React.PointerEvent) => {+ if (e.target === e.currentTarget) {+ useEditor.getState().select(null);+ scrub(e);+ }+ };++ // Zoom that keeps a chosen time pinned under a chosen viewport x.+ const pendingAnchor = useRef<{ t: number; px: number } | null>(null);+ useLayoutEffect(() => {+ const el = scrollRef.current;+ const a = pendingAnchor.current;+ if (el && a) {+ el.scrollLeft = Math.max(0, PAD_SIDE + a.t * pps - a.px);+ pendingAnchor.current = null;+ }+ }, [pps]);++ const zoomTo = useCallback((next: number, anchorT?: number, anchorPx?: number) => {+ const el = scrollRef.current;+ const cur = useEditor.getState();+ const clamped = Math.max(12, Math.min(800, next));+ if (Math.abs(clamped - cur.pxPerSec) < 0.01) return;+ if (el) {+ const t = anchorT ?? cur.currentTime;+ const px = anchorPx ?? PAD_SIDE + t * cur.pxPerSec - el.scrollLeft;+ pendingAnchor.current = { t, px };+ }+ cur.setPxPerSec(clamped);+ }, []);++ const fit = useCallback(() => {+ const el = scrollRef.current;+ const dur = totalDuration(useEditor.getState().clips);+ if (!el || dur <= 0) return;+ zoomTo((el.clientWidth - 60) / dur, 0, PAD_SIDE);+ }, [zoomTo]);++ // Trackpad pinch / cmd+wheel zooms at the cursor; vertical wheel pans.+ useEffect(() => {+ const el = scrollRef.current;+ if (!el) return;+ const onWheel = (e: WheelEvent) => {+ if (e.ctrlKey || e.metaKey) {+ e.preventDefault();+ const rect = el.getBoundingClientRect();+ const px = e.clientX - rect.left;+ const cur = useEditor.getState().pxPerSec;+ const t = (el.scrollLeft + px - PAD_SIDE) / cur;+ zoomTo(cur * Math.exp(-e.deltaY * 0.012), t, px);+ } else if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {+ e.preventDefault();+ el.scrollLeft += e.deltaY;+ }+ };+ el.addEventListener("wheel", onWheel, { passive: false });+ return () => el.removeEventListener("wheel", onWheel);+ }, [zoomTo]);++ // Timeline-scoped keys: = / - zoom around the playhead, Home/End jump.+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const target = e.target as HTMLElement;+ if (+ target.tagName === "INPUT" ||+ target.tagName === "TEXTAREA" ||+ target.tagName === "SELECT" ||+ target.isContentEditable ||+ document.querySelector('[data-slot="dialog-content"]')+ )+ return;+ const s = useEditor.getState();+ if (e.key === "=" || e.key === "+") {+ e.preventDefault();+ zoomTo(s.pxPerSec * 1.3);+ } else if (e.key === "-" || e.key === "_") {+ e.preventDefault();+ zoomTo(s.pxPerSec / 1.3);+ } else if (e.key === "Home") {+ e.preventDefault();+ s.seek(0);+ } else if (e.key === "End") {+ e.preventDefault();+ s.seek(totalDuration(s.clips));+ }+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [zoomTo]);++ // Drag the panel's top border to resize; the border itself stays as-is,+ // only an invisible grab strip sits on top of it.+ const resize = (e: React.PointerEvent) => {+ const h0 = useEditor.getState().timelineH;+ startDrag(e, {+ onMove: (_dx, dy) => {+ const max = Math.min(TIMELINE_H_MAX, window.innerHeight - 220);+ useEditor.getState().setTimelineH(Math.min(max, h0 - dy));+ },+ });+ };++ return (+ <footer+ className="relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border bg-card"+ style={{ height: timelineH }}+ onDragOver={(e) => {+ if (hasAssetDrag(e)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ }+ }}+ onDrop={(e) => {+ const id = draggedAssetId(e);+ if (!id) return;+ e.preventDefault();+ const s = useEditor.getState();+ const asset = s.assets.find((a) => a.id === id);+ if (!asset) return;+ if (asset.type === "video") s.addClipFromAsset(id);+ else s.addAudioFromAsset(id);+ }}+ >+ <div+ className="tl-resize absolute inset-x-0 top-0 z-30 h-1.5 cursor-row-resize"+ title="Drag to resize the timeline"+ onPointerDown={resize}+ />+ <div className="relative flex h-11 shrink-0 items-center gap-0.5 border-b border-border px-2.5">+ <Button+ variant="ghost"+ size="sm"+ title="Split at pointer, or at playhead (⌘B or S)"+ onClick={() => {+ const s = useEditor.getState();+ s.splitAtPlayhead(s.skimTime ?? undefined);+ }}+ >+ <Scissors /> Split+ </Button>+ <Button variant="ghost" size="sm" title="Title (T)" onClick={() => useEditor.getState().addOverlay()}>+ <Type /> Title+ </Button>+ <Button+ variant="ghost"+ size="sm"+ title="Delete (⌫)"+ disabled={!selection}+ onClick={() => useEditor.getState().deleteSelection()}+ >+ <Trash2 /> Delete+ </Button>++ <Transport total={total} />++ <div className="flex-1" />+ <Slider+ className="data-horizontal:w-28"+ min={12}+ max={800}+ value={pps}+ aria-label="Zoom"+ onValueChange={(v) => zoomTo(Number(v))}+ />+ <Button variant="ghost" size="sm" title="Fit timeline to window" onClick={fit}>+ Fit+ </Button>+ </div>++ <div ref={scrollRef} className="tl-scroll min-h-0 flex-1 overflow-x-auto overflow-y-hidden">+ <div className="h-full" style={{ width: contentW + PAD_SIDE * 2 }}>+ <div+ ref={innerRef}+ className="tl-content relative h-full pb-2"+ style={{ width: contentW, marginLeft: PAD_SIDE }}+ >+ <Ruler pps={pps} width={contentW} onScrub={scrub} />++ <div className="relative mt-1.5" style={{ height: VIDEO_H }} onPointerDown={deselectIfSelf}>+ {spans.length === 0 && (+ <div className="pointer-events-none sticky left-0 flex h-full w-[calc(100vw-40px)] max-w-[900px] items-center justify-center gap-1.5 rounded-xl border-[1.5px] border-dashed border-input text-xs font-medium text-muted-foreground">+ <Plus className="size-3.5" /> Add media to this project+ </div>+ )}+ {dragInfo && (+ <div+ className="tl-drop-slot pointer-events-none absolute top-0.5 rounded-lg bg-[#0a84ff]/10 shadow-[inset_0_0_0_1.5px_rgba(10,132,255,0.4),inset_0_2px_10px_rgba(10,60,140,0.08)] transition-[left] duration-150 ease-out"+ style={{+ left: dragInfo.gapStart * pps,+ width: Math.max(10, dragInfo.len * pps - CLIP_GAP),+ height: VIDEO_H - 4,+ }}+ />+ )}+ {spans.map((span, i) => (+ <ClipView+ key={span.clip.id}+ span={span}+ index={i}+ pps={pps}+ selected={selection?.kind === "clip" && selection.id === span.clip.id}+ drag={dragInfo}+ scrollRef={scrollRef}+ onDrag={onClipDrag}+ onDrop={onClipDrop}+ />+ ))}+ </div>++ <div className="relative mt-1.5" style={{ height: AUDIO_H }} onPointerDown={deselectIfSelf}>+ {audioClips.length === 0 && (+ <TrackHint icon={<Music className="size-3" />} label="Soundtrack" />+ )}+ {audioClips.map((a) => (+ <AudioView+ key={a.id}+ clip={a}+ asset={assets.find((x) => x.id === a.assetId)}+ pps={pps}+ selected={selection?.kind === "audio" && selection.id === a.id}+ />+ ))}+ </div>++ <div className="relative mt-1.5" style={{ height: TEXT_H }} onPointerDown={deselectIfSelf}>+ {overlays.length === 0 && (+ <TrackHint icon={<Type className="size-3" />} label="Titles" />+ )}+ {overlays.map((o) => (+ <TextBar+ key={o.id}+ overlay={o}+ pps={pps}+ selected={selection?.kind === "text" && selection.id === o.id}+ />+ ))}+ </div>++ {subtitles.showOnTimeline && subtitles.cues.length > 0 && (+ <div+ className="tl-sub-track relative mt-1.5"+ style={{ height: SUB_H }}+ onPointerDown={deselectIfSelf}+ >+ {subtitles.cues.map((c) => (+ <SubBar key={c.id} cue={c} pps={pps} />+ ))}+ </div>+ )}++ <HoverLine scrollRef={scrollRef} innerRef={innerRef} pps={pps} />+ <Playhead pps={pps} scrollRef={scrollRef} onScrub={scrub} />+ </div>+ </div>+ </div>+ </footer>+ );+}++/**+ * iMovie skimmer: a line that follows the mouse over the timeline. It marks+ * where Split (⌘B / S) will cut; clicking still moves the playhead itself.+ */+function HoverLine({+ scrollRef,+ innerRef,+ pps,+}: {+ scrollRef: React.RefObject<HTMLDivElement | null>;+ innerRef: React.RefObject<HTMLDivElement | null>;+ pps: number;+}) {+ const skimTime = useEditor((s) => s.skimTime);+ useEffect(() => {+ const el = scrollRef.current;+ if (!el) return;+ const move = (e: PointerEvent) => {+ const inner = innerRef.current;+ const s = useEditor.getState();+ if (!inner || e.buttons) return s.setSkimTime(null);+ const t = (e.clientX - inner.getBoundingClientRect().left) / s.pxPerSec;+ s.setSkimTime(Math.max(0, t));+ };+ const leave = () => useEditor.getState().setSkimTime(null);+ el.addEventListener("pointermove", move);+ el.addEventListener("pointerleave", leave);+ return () => {+ el.removeEventListener("pointermove", move);+ el.removeEventListener("pointerleave", leave);+ useEditor.getState().setSkimTime(null);+ };+ }, [scrollRef, innerRef]);+ if (skimTime === null) return null;+ return (+ <div+ className="tl-hover-line pointer-events-none absolute top-0 bottom-2 z-6 w-px bg-foreground/30"+ style={{ transform: `translateX(${skimTime * pps}px)` }}+ />+ );+}++/** Playback transport, centered in the timeline toolbar. */+function Transport({ total }: { total: number }) {+ const playing = useEditor((s) => s.playing);+ const currentTime = useEditor((s) => s.currentTime);+ const hasClips = total > 0;++ const toggle = () => {+ const s = useEditor.getState();+ if (!s.playing && s.currentTime >= total - 0.01) s.seek(0);+ s.setPlaying(!s.playing);+ };++ return (+ <div className="absolute left-1/2 flex -translate-x-1/2 items-center gap-2">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Back to start"+ disabled={!hasClips}+ onClick={() => useEditor.getState().seek(0)}+ >+ <SkipBack className="fill-current" />+ </Button>+ <button+ className="grid size-8 place-items-center rounded-full bg-foreground text-background transition-transform hover:opacity-90 active:scale-95 disabled:opacity-40"+ title="Play/Pause (Space)"+ disabled={!hasClips}+ onClick={toggle}+ >+ {playing ? (+ <Pause className="size-4 fill-current stroke-none" />+ ) : (+ <Play className="ml-0.5 size-4 fill-current stroke-none" />+ )}+ </button>+ <div className="flex min-w-30 items-baseline gap-1.5 font-mono text-xs tabular-nums">+ <span className="tc-now">{formatTimecode(currentTime)}</span>+ <span className="text-muted-foreground">/</span>+ <span className="text-muted-foreground">{formatTimecode(total)}</span>+ </div>+ </div>+ );+}++function TrackHint({ icon, label }: { icon: React.ReactNode; label: string }) {+ return (+ <div className="pointer-events-none sticky left-0 inline-flex h-full items-center gap-1.5 px-4 text-[10.5px] font-semibold tracking-wider text-muted-foreground/70 uppercase">+ {icon} {label}+ </div>+ );+}++function Ruler({+ pps,+ width,+ onScrub,+}: {+ pps: number;+ width: number;+ onScrub: (e: React.PointerEvent) => void;+}) {+ const steps = [0.5, 1, 2, 5, 10, 15, 30, 60];+ const step = steps.find((s) => s * pps >= 64) ?? 120;+ const count = Math.ceil(width / (step * pps));+ const ticks = Array.from({ length: count }, (_, i) => i * step);+ return (+ <div className="relative h-[26px] cursor-ew-resize border-b border-border" onPointerDown={onScrub}>+ {ticks.map((t) => (+ <div+ key={t}+ className="absolute top-0 bottom-0 border-l border-foreground/15 pl-1.5"+ style={{ left: t * pps }}+ >+ <span className="font-mono text-[9.5px] leading-6 text-muted-foreground select-none">+ {formatTime(t)}+ </span>+ </div>+ ))}+ </div>+ );+}++function Playhead({+ pps,+ scrollRef,+ onScrub,+}: {+ pps: number;+ scrollRef: React.RefObject<HTMLDivElement | null>;+ onScrub: (e: React.PointerEvent) => void;+}) {+ const t = useEditor((s) => s.currentTime);+ const playing = useEditor((s) => s.playing);+ const x = t * pps;++ useEffect(() => {+ const el = scrollRef.current;+ if (!el || !playing) return;+ const sx = x + PAD_SIDE; // playhead position in scroll coordinates+ if (sx < el.scrollLeft + 24 || sx > el.scrollLeft + el.clientWidth - 80) {+ el.scrollLeft = Math.max(0, sx - 80);+ }+ }, [x, playing, scrollRef]);++ return (+ <div+ className="pointer-events-none absolute top-0 bottom-2 left-0 z-8 w-[1.5px] bg-[#0a84ff] shadow-[0_0_8px_rgba(10,132,255,0.6)]"+ style={{ transform: `translateX(${x}px)` }}+ >+ <div+ className="tl-playhead-cap pointer-events-auto absolute -top-0 -left-[7px] h-5 w-4 cursor-ew-resize"+ onPointerDown={onScrub}+ >+ <div className="mx-auto h-3 w-2.5 rounded-t-[3px] bg-[#0a84ff] [clip-path:polygon(0_0,100%_0,100%_58%,50%_100%,0_58%)]" />+ </div>+ </div>+ );+}++function ClipView({+ span,+ index,+ pps,+ selected,+ drag,+ scrollRef,+ onDrag,+ onDrop,+}: {+ span: ClipSpan;+ index: number;+ pps: number;+ selected: boolean;+ drag: ClipDrag | null;+ scrollRef: React.RefObject<HTMLDivElement | null>;+ onDrag: (id: string, dx: number, dy: number) => void;+ onDrop: (id: string, dx: number | null) => void;+}) {+ // Left-trim keeps the box and its frames pinned: the handle sweeps through+ // the clip and the leading area dims as "hidden"; release collapses it.+ const [trim, setTrim] = useState<{ side: "l"; in0: number } | { side: "r" } | null>(null);+ const { clip, asset } = span;+ const w = span.len * pps;+ const left = span.start * pps;+ const trimL = trim?.side === "l" ? trim : null;+ const stripIn = trimL ? Math.min(clip.in, trimL.in0) : clip.in;+ const hidPx = trimL ? Math.max(0, (clip.in - trimL.in0) * pps) : 0;+ const boxW = trimL ? (clip.out - stripIn) * pps : w;+ const isDragged = drag?.id === clip.id;+ // Neighbors part to make room for the open slot.+ const shiftSec =+ !drag || isDragged+ ? 0+ : drag.from < index && index <= drag.to+ ? -drag.len+ : drag.to <= index && index < drag.from+ ? drag.len+ : 0;++ // During a left-trim the strip is computed from the drag-start in-point so+ // every frame stays pinned in place while the hidden region sweeps over it.+ const filmstrip = useMemo(() => {+ if (!asset.thumbs?.length || !asset.thumbStep) return [];+ const aspect = (asset.width ?? 16) / Math.max(1, asset.height ?? 9);+ const imgW = Math.max(26, Math.round((VIDEO_H - 4) * aspect));+ const count = Math.min(120, Math.ceil(boxW / imgW));+ return Array.from({ length: count }, (_, k) => {+ const timeAt = stripIn + (k * imgW + imgW / 2) / pps;+ const idx = Math.min(+ asset.thumbs!.length - 1,+ Math.max(0, Math.floor(timeAt / asset.thumbStep!))+ );+ return { src: asset.thumbs![idx], left: k * imgW, width: imgW };+ });+ }, [asset, stripIn, boxW, pps]);++ const onBody = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "clip", id: clip.id });+ // Clicking anywhere on the timeline moves the playhead — clips included.+ const rect = e.currentTarget.getBoundingClientRect();+ s.seek(span.start + (e.clientX - rect.left) / pps);+ const el = scrollRef.current;+ const sc0 = el?.scrollLeft ?? 0;+ let effDx = 0;+ let live = false;+ startDrag(e, {+ onMove: (dx, dy, ev) => {+ if (!live && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;+ live = true;+ if (el) {+ const r = el.getBoundingClientRect();+ if (ev.clientX > r.right - 36) el.scrollLeft += 14;+ else if (ev.clientX < r.left + 36) el.scrollLeft -= 14;+ }+ effDx = dx + ((el?.scrollLeft ?? sc0) - sc0);+ onDrag(clip.id, effDx, Math.max(-26, Math.min(14, dy)));+ },+ onUp: () => onDrop(clip.id, live ? effDx : null),+ });+ };++ const onTrimLeft = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "clip", id: clip.id });+ s.pushHistory();+ const in0 = clip.in;+ setTrim({ side: "l", in0 });+ startDrag(e, {+ onMove: (dx) => {+ const nin = Math.min(clip.out - 0.15, Math.max(0, in0 + dx / pps));+ s.updateClipTransient(clip.id, { in: nin });+ },+ onUp: () => setTrim(null),+ });+ };++ const onTrimRight = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "clip", id: clip.id });+ s.pushHistory();+ setTrim({ side: "r" });+ const out0 = clip.out;+ startDrag(e, {+ onMove: (dx) => {+ const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));+ s.updateClipTransient(clip.id, { out: nout });+ },+ onUp: () => setTrim(null),+ });+ };++ return (+ <>+ <div+ className={cn(+ "tl-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-lg bg-neutral-200 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]",+ selected && SELECTED_SHADOW,+ isDragged+ ? "tl-clip-ghost pointer-events-none z-7 cursor-grabbing opacity-80 shadow-2xl"+ : drag && "transition-transform duration-150 ease-out"+ )}+ style={{+ left,+ width: Math.max(10, boxW - CLIP_GAP),+ height: VIDEO_H - 4,+ transform: isDragged+ ? `translate(${drag!.dx}px, ${drag!.dy}px)`+ : shiftSec !== 0+ ? `translateX(${shiftSec * pps}px)`+ : undefined,+ }}+ onPointerDown={onBody}+ >+ <div className="tl-filmstrip pointer-events-none absolute inset-0">+ {filmstrip.map((f, k) => (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ key={k}+ src={f.src}+ alt=""+ draggable={false}+ className="absolute top-0 h-full object-cover"+ style={{ left: f.left, width: f.width }}+ />+ ))}+ </div>+ {hidPx > 0 && (+ <div+ className="tl-trim-hidden pointer-events-none absolute inset-y-0 left-0 z-2 border-r border-white/70 bg-black/55"+ style={{ width: hidPx }}+ />+ )}+ {(isDragged || trim !== null) && (+ <span+ className="tl-dur-chip pointer-events-none absolute top-1 z-2 rounded-[5px] bg-black/65 px-1.5 py-px font-mono text-[10px] tabular-nums text-white"+ style={{ left: hidPx + 4 }}+ >+ {(Math.round(span.len * 10) / 10).toFixed(1)}s+ </span>+ )}+ {clip.muted && (+ <span className="tl-mute-chip absolute bottom-1 left-1 z-2 grid size-[18px] place-items-center rounded-[5px] bg-black/70 text-white" title="Muted">+ <VolumeX className="size-3" />+ </span>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <button+ aria-label="Clip options"+ className="tl-clip-menu absolute top-1 right-2 z-4 grid size-[18px] place-items-center rounded-[5px] bg-black/55 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/75"+ onPointerDown={(e) => e.stopPropagation()}+ />+ }+ >+ <EllipsisVertical className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-44">+ <DropdownMenuItem+ disabled={clip.muted}+ onClick={() => {+ const s = useEditor.getState();+ s.select({ kind: "clip", id: clip.id });+ s.detachAudio();+ void ensurePeaks(asset);+ }}+ >+ <AudioLines /> Detach audio+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <span+ className={cn(trimHandle, "tl-trim-l", trim?.side === "l" && "z-3 after:opacity-100")}+ style={{ left: hidPx }}+ onPointerDown={onTrimLeft}+ />+ <span+ className={cn(trimHandle, "tl-trim-r right-0", trim?.side === "r" && "after:opacity-100")}+ onPointerDown={onTrimRight}+ />+ </div>+ {trim !== null && (+ <div+ className="tl-trim-tip pointer-events-none absolute z-9 -translate-x-1/2 rounded-md bg-foreground px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-background shadow-md"+ style={{+ left: trim.side === "l" ? left + hidPx : left + Math.max(10, w - CLIP_GAP),+ top: -24,+ }}+ >+ {formatTimecode(trim.side === "l" ? clip.in : clip.out)}+ </div>+ )}+ </>+ );+}++function AudioView({+ clip,+ asset,+ pps,+ selected,+}: {+ clip: AudioClip;+ asset: MediaAsset | undefined;+ pps: number;+ selected: boolean;+}) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const len = clipLen(clip);+ const w = Math.max(10, len * pps);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || !asset?.peaks) return;+ const width = Math.min(4000, Math.round(w));+ const height = AUDIO_H - 8;+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d")!;+ ctx.clearRect(0, 0, width, height);+ ctx.fillStyle = "rgba(255, 255, 255, 0.85)";+ const peaks = asset.peaks;+ const n = peaks.length;+ const from = (clip.in / asset.duration) * n;+ const span = ((clip.out - clip.in) / asset.duration) * n;+ const bars = Math.max(1, Math.floor(width / 3));+ for (let i = 0; i < bars; i++) {+ const p = peaks[Math.min(n - 1, Math.floor(from + (i / bars) * span))] ?? 0;+ const h = Math.max(1.5, p * (height - 2));+ ctx.fillRect(i * 3, (height - h) / 2, 2, h);+ }+ }, [asset, clip.in, clip.out, w]);++ if (!asset) return null;++ const onBody = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "audio", id: clip.id });+ s.seek(clip.start + (e.clientX - e.currentTarget.getBoundingClientRect().left) / pps);+ s.pushHistory();+ const start0 = clip.start;+ startDrag(e, {+ onMove: (dx) =>+ s.updateAudioTransient(clip.id, { start: Math.max(0, start0 + dx / pps) }),+ });+ };++ const onTrimLeft = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "audio", id: clip.id });+ s.pushHistory();+ const in0 = clip.in;+ const start0 = clip.start;+ startDrag(e, {+ onMove: (dx) => {+ let d = dx / pps;+ d = Math.max(d, -in0, -start0);+ d = Math.min(d, clip.out - 0.15 - in0);+ s.updateAudioTransient(clip.id, { in: in0 + d, start: start0 + d });+ },+ });+ };++ const onTrimRight = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "audio", id: clip.id });+ s.pushHistory();+ const out0 = clip.out;+ startDrag(e, {+ onMove: (dx) => {+ const nout = Math.max(clip.in + 0.15, Math.min(asset.duration, out0 + dx / pps));+ s.updateAudioTransient(clip.id, { out: nout });+ },+ });+ };++ return (+ <div+ className={cn(+ "tl-audio-clip group absolute top-0.5 cursor-grab overflow-hidden rounded-[7px] bg-gradient-to-b from-emerald-500 to-emerald-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",+ selected && SELECTED_SHADOW+ )}+ style={{ left: clip.start * pps, width: w, height: AUDIO_H - 4 }}+ onPointerDown={onBody}+ >+ <canvas ref={canvasRef} className="pointer-events-none absolute inset-x-0 inset-y-1" />+ {(clip.fadeIn ?? 0) > 0 && (+ <div+ className="tl-fade-in pointer-events-none absolute inset-y-0 left-0 bg-gradient-to-r from-black/45 to-transparent"+ style={{ width: Math.min(w, (clip.fadeIn ?? 0) * pps) }}+ />+ )}+ {(clip.fadeOut ?? 0) > 0 && (+ <div+ className="tl-fade-out pointer-events-none absolute inset-y-0 right-0 bg-gradient-to-l from-black/45 to-transparent"+ style={{ width: Math.min(w, (clip.fadeOut ?? 0) * pps) }}+ />+ )}+ <span className="pointer-events-none absolute top-[3px] left-2 text-[9.5px] whitespace-nowrap text-white/90 [text-shadow:0_1px_2px_rgba(0,0,0,0.35)]">+ {asset.name}+ </span>+ <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />+ <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />+ </div>+ );+}++function TextBar({+ overlay: o,+ pps,+ selected,+}: {+ overlay: TextOverlay;+ pps: number;+ selected: boolean;+}) {+ const w = Math.max(8, (o.end - o.start) * pps);++ const onBody = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "text", id: o.id });+ s.pushHistory();+ const start0 = o.start;+ const len = o.end - o.start;+ startDrag(e, {+ onMove: (dx) => {+ const start = Math.max(0, start0 + dx / pps);+ s.updateOverlayTransient(o.id, { start, end: start + len });+ },+ });+ };++ const onTrimLeft = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "text", id: o.id });+ s.pushHistory();+ const start0 = o.start;+ startDrag(e, {+ onMove: (dx) => {+ const start = Math.min(o.end - 0.2, Math.max(0, start0 + dx / pps));+ s.updateOverlayTransient(o.id, { start });+ },+ });+ };++ const onTrimRight = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.select({ kind: "text", id: o.id });+ s.pushHistory();+ const end0 = o.end;+ startDrag(e, {+ onMove: (dx) => {+ const end = Math.max(o.start + 0.2, end0 + dx / pps);+ s.updateOverlayTransient(o.id, { end });+ },+ });+ };++ return (+ <div+ className={cn(+ "tl-text-bar group absolute top-0.5 flex cursor-grab items-center overflow-hidden rounded-md bg-gradient-to-b from-purple-500 to-purple-600 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.1)]",+ selected && SELECTED_SHADOW+ )}+ style={{ left: o.start * pps, width: w, height: TEXT_H - 6 }}+ onPointerDown={onBody}+ >+ <span className="pointer-events-none truncate px-2 text-[10.5px] font-medium text-white">+ {o.text.replace(/\n/g, " ")}+ </span>+ <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={onTrimLeft} />+ <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={onTrimRight} />+ </div>+ );+}++/** A subtitle cue on its track: drag to retime, edges to trim, click seeks.+ * Editing the words happens in the Subtitles panel. */+function SubBar({ cue, pps }: { cue: SubtitleCue; pps: number }) {+ const w = Math.max(8, (cue.end - cue.start) * pps);++ const finish = (moved: boolean) => {+ const s = useEditor.getState();+ if (moved) s.sortCues();+ else s.seek(cue.start + 0.001);+ };++ const onBody = (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.pushHistory();+ const start0 = cue.start;+ const len = cue.end - cue.start;+ startDrag(e, {+ onMove: (dx) => {+ const start = Math.max(0, start0 + dx / pps);+ // Moving a cue detaches it from its word timings.+ s.updateCueTransient(cue.id, { start, end: start + len, words: undefined });+ },+ onUp: (_dx, _dy, moved) => finish(moved),+ });+ };++ const trim = (side: "l" | "r") => (e: React.PointerEvent) => {+ const s = useEditor.getState();+ s.pushHistory();+ const { start: start0, end: end0 } = cue;+ startDrag(e, {+ onMove: (dx) => {+ if (side === "l")+ s.updateCueTransient(cue.id, {+ start: Math.min(end0 - 0.15, Math.max(0, start0 + dx / pps)),+ words: undefined,+ });+ else+ s.updateCueTransient(cue.id, {+ end: Math.max(start0 + 0.15, end0 + dx / pps),+ words: undefined,+ });+ },+ onUp: (_dx, _dy, moved) => finish(moved),+ });+ };++ return (+ <div+ className="tl-sub-bar group absolute top-px flex cursor-grab items-center overflow-hidden rounded-[5px] bg-gradient-to-b from-amber-300 to-amber-400 shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]"+ style={{ left: cue.start * pps, width: w, height: SUB_H - 4 }}+ title={cue.text}+ onPointerDown={onBody}+ >+ <span className="pointer-events-none truncate px-1.5 text-[9.5px] font-medium text-amber-950/90">+ {cue.text}+ </span>+ <span className={cn(trimHandle, "tl-trim-l left-0")} onPointerDown={trim("l")} />+ <span className={cn(trimHandle, "tl-trim-r right-0")} onPointerDown={trim("r")} />+ </div>+ );+}diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxnew file mode 100644index 00000000..1ea60989--- /dev/null+++ b/site/src/cut/components/TopBar.tsx@@ -0,0 +1,140 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import { Check, ChevronDown, ChevronLeft, Loader2, Monitor, Smartphone, Sparkles, Upload } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useEditor } from "@/cut/lib/store";+import { ASPECT_LABEL, type Aspect } from "@/cut/lib/types";+import { cn } from "@/lib/utils";++export function TopBar() {+ const hasClips = useEditor((s) => s.clips.length > 0);+ const aspect = useEditor((s) => s.aspect);+ const projectName = useEditor((s) => s.projectName);+ const saveState = useEditor((s) => s.saveState);+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState("");++ const commitName = () => {+ setEditing(false);+ const name = draft.trim();+ if (name && name !== projectName) useEditor.getState().setProjectName(name);+ };++ return (+ <header className="relative flex items-center justify-between border-b border-border bg-card pr-3 pl-2">+ <div className="absolute left-1/2 -translate-x-1/2">+ <DropdownMenu>+ <DropdownMenuTrigger className="aspect-switch flex items-center gap-1.5 rounded-full border border-border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-xs transition-colors hover:text-foreground">+ {aspect === "9:16" ? <Smartphone className="size-3.5" /> : <Monitor className="size-3.5" />}+ {ASPECT_LABEL[aspect]}+ <ChevronDown className="size-3" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-56">+ {(Object.keys(ASPECT_LABEL) as Aspect[]).map((a) => (+ <DropdownMenuItem key={a} onClick={() => useEditor.getState().setAspect(a)}>+ {a === "9:16" ? <Smartphone /> : <Monitor />}+ <span className="flex-1">+ {ASPECT_LABEL[a]}+ <span className="block text-[10.5px] text-muted-foreground">+ {a === "9:16" ? "TikTok, Reels, Shorts" : "YouTube"}+ </span>+ </span>+ {aspect === a && <Check className="size-3.5 text-coral" />}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <div className="flex min-w-0 items-center gap-1">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Back to projects"+ nativeButton={false}+ render={<Link href="/" />}+ >+ <ChevronLeft />+ </Button>+ <span className="grid size-[22px] shrink-0 place-items-center overflow-hidden rounded-md">+ <img src="/donkey-logo.svg" alt="Donkey" className="block h-full w-full object-contain" />+ </span>+ {editing ? (+ <input+ autoFocus+ className="ml-1.5 h-7 w-52 rounded-md border border-input bg-transparent px-2 text-sm font-medium outline-none select-text focus:border-ring"+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commitName}+ onKeyDown={(e) => {+ if (e.key === "Enter") commitName();+ if (e.key === "Escape") setEditing(false);+ }}+ />+ ) : (+ <button+ className="ml-1.5 max-w-64 cursor-text truncate rounded-md px-2 py-1 text-sm font-medium tracking-tight hover:bg-muted"+ title="Rename project"+ onClick={() => {+ setDraft(projectName);+ setEditing(true);+ }}+ >+ {projectName}+ </button>+ )}+ <span+ className={cn(+ "ml-2 flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity",+ saveState === "saved" && "opacity-60"+ )}+ >+ {saveState === "saving" || saveState === "dirty" ? (+ <>+ <Loader2 className="size-3 animate-spin" /> Saving+ </>+ ) : saveState === "error" ? (+ <span className="text-destructive">Couldn’t save</span>+ ) : (+ <>+ <Check className="size-3" /> Saved+ </>+ )}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <Button+ variant="ghost"+ size="sm"+ className="ai-toggle"+ aria-label="Chat"+ title="Chat (⌘J)"+ onClick={() => {+ const s = useEditor.getState();+ s.setAiOpen(!s.aiOpen);+ }}+ >+ <Sparkles data-icon="inline-start" /> Chat+ </Button>+ <Button+ size="sm"+ disabled={!hasClips}+ onClick={() => {+ const s = useEditor.getState();+ s.setPlaying(false);+ s.setExportOpen(true);+ }}+ >+ <Upload data-icon="inline-start" /> Export+ </Button>+ </div>+ </header>+ );+}diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsnew file mode 100644index 00000000..efd66ef9--- /dev/null+++ b/site/src/cut/hooks/usePlayback.ts@@ -0,0 +1,234 @@+"use client";++import { useEffect, type RefObject } from "react";+import { getClipSpans, totalDuration, useEditor } from "@/cut/lib/store";+import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";++// The canvas backing store is the full frame resolution (1080×1920 or+// 1920×1080, set by Preview from the project aspect) so the preview stays+// sharp on Retina displays. The engine reads the size off the canvas each+// frame, so an aspect switch takes effect seamlessly.++/**+ * Preview engine. One hidden <video> per asset and one <audio> per soundtrack+ * clip; the active clip's video element is the master clock while playing and+ * every frame is composited onto the preview canvas (contain-fit, matching the+ * export's letterboxing).+ */+class Engine {+ private videoEls = new Map<string, HTMLVideoElement>();+ private audioEls = new Map<string, HTMLAudioElement>();+ private raf = 0;+ private activeClipId: string | null = null;+ private lastWritten = -1;+ private disposed = false;++ constructor(private canvas: HTMLCanvasElement) {+ this.tick = this.tick.bind(this);+ this.raf = requestAnimationFrame(this.tick);+ }++ dispose() {+ this.disposed = true;+ cancelAnimationFrame(this.raf);+ for (const el of this.videoEls.values()) {+ el.pause();+ el.removeAttribute("src");+ el.load();+ }+ for (const el of this.audioEls.values()) el.pause();+ this.videoEls.clear();+ this.audioEls.clear();+ }++ private videoFor(asset: MediaAsset) {+ let el = this.videoEls.get(asset.id);+ if (!el) {+ el = document.createElement("video");+ el.playsInline = true;+ el.preload = "auto";+ el.crossOrigin = "anonymous";+ el.src = asset.url;+ this.videoEls.set(asset.id, el);+ }+ return el;+ }++ private switchTo(span: ClipSpan, t: number, play: boolean) {+ const el = this.videoFor(span.asset);+ for (const [assetId, other] of this.videoEls) {+ if (assetId !== span.asset.id && !other.paused) other.pause();+ }+ const target = span.clip.in + Math.max(0, t - span.start);+ // Let an in-flight seek finish before issuing the next one — restarting+ // the decoder every mousemove makes scrubbing stutter. The tick loop+ // re-applies the newest target as soon as the element is free.+ if (Math.abs(el.currentTime - target) > 0.05 && !el.seeking) el.currentTime = target;+ this.activeClipId = span.clip.id;+ if (play) void el.play().catch(() => {});+ return el;+ }++ private draw(el: HTMLVideoElement | null, clip?: VideoClip) {+ const ctx = this.canvas.getContext("2d");+ if (!ctx) return;+ const W = this.canvas.width;+ const H = this.canvas.height;+ if (!el) {+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, W, H);+ return;+ }+ // Mid-seek the element has no decodable frame; keep the previous frame+ // on the canvas instead of strobing black (matters while skimming).+ if (el.readyState < 2 || !el.videoWidth) return;+ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, W, H);+ const fill = clip?.fit === "fill";+ const scale = fill+ ? Math.max(W / el.videoWidth, H / el.videoHeight)+ : Math.min(W / el.videoWidth, H / el.videoHeight);+ const dw = el.videoWidth * scale;+ const dh = el.videoHeight * scale;+ let dx = (W - dw) / 2;+ let dy = (H - dh) / 2;+ if (fill) {+ // Pan the crop window across the overflow (matches the export crop).+ const kx = 0.5 + (clip?.panX ?? 0) / 2;+ const ky = 0.5 + (clip?.panY ?? 0) / 2;+ dx = -(dw - W) * kx;+ dy = -(dh - H) * ky;+ }+ ctx.drawImage(el, dx, dy, dw, dh);+ }++ private syncSoundtrack(t: number, playing: boolean) {+ const s = useEditor.getState();+ const live = new Set<string>();+ for (const a of s.audioClips) {+ live.add(a.id);+ const asset = s.assets.find((x) => x.id === a.assetId);+ if (!asset) continue;+ let el = this.audioEls.get(a.id);+ if (!el) {+ el = new Audio(asset.url);+ el.preload = "auto";+ this.audioEls.set(a.id, el);+ }+ const len = Math.max(0.1, a.out - a.in);+ const active = playing && t >= a.start && t < a.start + len;+ if (active) {+ // Fade envelope: linear ramps at either end of the clip.+ const rel = t - a.start;+ const fi = a.fadeIn ?? 0;+ const fo = a.fadeOut ?? 0;+ let gain = 1;+ if (fi > 0 && rel < fi) gain *= rel / fi;+ if (fo > 0 && rel > len - fo) gain *= Math.max(0, (len - rel) / fo);+ el.volume = Math.max(0, Math.min(1, a.volume * gain));+ const expected = a.in + (t - a.start);+ if (Math.abs(el.currentTime - expected) > 0.25) el.currentTime = expected;+ if (el.paused) void el.play().catch(() => {});+ } else if (!el.paused) {+ el.pause();+ }+ }+ for (const [id, el] of this.audioEls) {+ if (!live.has(id)) {+ el.pause();+ this.audioEls.delete(id);+ }+ }+ }++ private tick() {+ if (this.disposed) return;+ this.raf = requestAnimationFrame(this.tick);++ const s = useEditor.getState();+ const spans = getClipSpans(s.clips, s.assets);+ const total = totalDuration(s.clips);++ if (spans.length === 0) {+ this.draw(null);+ this.syncSoundtrack(0, false);+ if (s.playing) useEditor.setState({ playing: false, currentTime: 0 });+ return;+ }++ let t = Math.min(s.currentTime, total);+ const externalSeek = Math.abs(t - this.lastWritten) > 0.15;++ if (!s.playing) {+ for (const el of this.videoEls.values()) if (!el.paused) el.pause();+ // iMovie skimming: while the mouse hovers the timeline, preview the+ // frame under it. The playhead (currentTime) is never touched.+ const pt =+ s.skimTime !== null ? Math.max(0, Math.min(s.skimTime, total - 0.001)) : t;+ const span =+ spans.find((sp) => pt >= sp.start && pt < sp.start + sp.len) ??+ spans[spans.length - 1];+ const el = this.switchTo(span, Math.min(pt, span.start + span.len), false);+ this.lastWritten = t;+ this.draw(el, span.clip);+ this.syncSoundtrack(t, false);+ return;+ }++ let span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len);+ if (!span) {+ // Reached the end of the last clip.+ useEditor.setState({ playing: false, currentTime: total });+ this.lastWritten = total;+ for (const el of this.videoEls.values()) el.pause();+ this.syncSoundtrack(total, false);+ return;+ }++ let el = this.videoFor(span.asset);+ if (span.clip.id !== this.activeClipId || externalSeek) {+ el = this.switchTo(span, t, true);+ }+ el.muted = span.clip.muted;+ if (el.paused && el.readyState >= 2) void el.play().catch(() => {});++ // The active element is the master clock.+ const derived = span.start + (el.currentTime - span.clip.in);+ if (Math.abs(derived - t) < 1.5) {+ t = Math.max(span.start, Math.min(derived, span.start + span.len));+ }++ // Clip boundary: hand off to the next clip (or finish).+ if (el.currentTime >= span.clip.out - 0.02 || el.ended) {+ const idx = spans.indexOf(span);+ const next = spans[idx + 1];+ if (next) {+ t = next.start + 0.0001;+ span = next;+ el = this.switchTo(next, t, true);+ el.muted = next.clip.muted;+ } else {+ useEditor.setState({ playing: false, currentTime: total });+ this.lastWritten = total;+ el.pause();+ this.draw(el, span.clip);+ this.syncSoundtrack(total, false);+ return;+ }+ }++ this.lastWritten = t;+ useEditor.setState({ currentTime: t });+ this.draw(el, span.clip);+ this.syncSoundtrack(t, true);+ }+}++export function usePlayback(canvasRef: RefObject<HTMLCanvasElement | null>) {+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const engine = new Engine(canvas);+ return () => engine.dispose();+ }, [canvasRef]);+}diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.tsnew file mode 100644index 00000000..36b10d19--- /dev/null+++ b/site/src/cut/lib/aiContext.ts@@ -0,0 +1,122 @@+"use client";++import { getClipSpans, totalDuration, useEditor } from "./store";++const r = (n: number) => Math.round(n * 100) / 100;++/**+ * Compact JSON snapshot of everything the assistant should know: the cut,+ * the selection, what's on screen, and every user-facing setting. Sent with+ * each message and served by the get_state tool.+ */+export function buildAiContext() {+ const s = useEditor.getState();+ const spans = getClipSpans(s.clips, s.assets);+ const duration = totalDuration(s.clips);+ const assetById = new Map(s.assets.map((a) => [a.id, a]));++ const selection = (() => {+ if (!s.selection) return null;+ const { kind, id } = s.selection;+ if (kind === "clip") {+ const sp = spans.find((x) => x.clip.id === id);+ return sp+ ? { kind, id, asset: sp.asset.name, start: r(sp.start), len: r(sp.len), muted: sp.clip.muted }+ : { kind, id };+ }+ if (kind === "audio") {+ const a = s.audioClips.find((x) => x.id === id);+ return a ? { kind, id, ...describeAudio(a, assetById) } : { kind, id };+ }+ const o = s.overlays.find((x) => x.id === id);+ return o ? { kind, id, ...describeOverlay(o) } : { kind, id };+ })();++ return {+ project: {+ id: s.projectId,+ name: s.projectName,+ duration: r(duration),+ aspect: s.aspect,+ frame: s.aspect === "9:16" ? "1080x1920" : "1920x1080",+ },+ playhead: r(s.currentTime),+ skimmer: s.skimTime === null ? null : r(s.skimTime),+ playing: s.playing,+ selection,+ videoTrack: spans.map((sp, index) => ({+ index,+ id: sp.clip.id,+ asset: sp.asset.name,+ start: r(sp.start),+ len: r(sp.len),+ in: r(sp.clip.in),+ out: r(sp.clip.out),+ sourceDuration: r(sp.asset.duration),+ muted: sp.clip.muted,+ framing: sp.clip.fit ?? "fit",+ ...(sp.clip.fit === "fill"+ ? { panX: r(sp.clip.panX ?? 0), panY: r(sp.clip.panY ?? 0) }+ : {}),+ })),+ soundtrack: s.audioClips.map((a) => ({ id: a.id, ...describeAudio(a, assetById) })),+ titles: s.overlays.map((o) => ({ id: o.id, ...describeOverlay(o) })),+ subtitles: {+ count: s.subtitles.cues.length,+ showOnVideo: s.subtitles.showOnVideo,+ showOnTimeline: s.subtitles.showOnTimeline,+ locale: s.subtitles.locale ?? "en-US",+ status: s.subtitleStatus,+ cues: s.subtitles.cues.slice(0, 40).map((c) => ({+ id: c.id,+ start: r(c.start),+ end: r(c.end),+ text: c.text,+ })),+ cuesTruncated: s.subtitles.cues.length > 40,+ },+ publish: s.publish,+ view: {+ pxPerSec: r(s.pxPerSec),+ timelineH: s.timelineH,+ exportDialogOpen: s.exportOpen,+ },+ };+}++function describeAudio(+ a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number },+ assets: Map<string, { name: string }>+) {+ return {+ asset: assets.get(a.assetId)?.name ?? a.assetId,+ start: r(a.start),+ len: r(a.out - a.in),+ in: r(a.in),+ out: r(a.out),+ volume: r(a.volume),+ fadeIn: r(a.fadeIn ?? 0),+ fadeOut: r(a.fadeOut ?? 0),+ };+}++function describeOverlay(o: {+ text: string; start: number; end: number; x: number; y: number;+ size: number; font: string; weight: number; color: string; shadow: boolean; plate: boolean;+ plateRadius?: number;+}) {+ return {+ text: o.text,+ start: r(o.start),+ end: r(o.end),+ x: r(o.x),+ y: r(o.y),+ size: o.size,+ font: o.font,+ weight: o.weight,+ color: o.color,+ shadow: o.shadow,+ plate: o.plate,+ ...(o.plateRadius !== undefined && { plateRadius: r(o.plateRadius) }),+ };+}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsnew file mode 100644index 00000000..8a5c7669--- /dev/null+++ b/site/src/cut/lib/aiTools.ts@@ -0,0 +1,340 @@+"use client";++import { enrichAsset, ensurePeaks } from "./media";+import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";+import { buildAiContext } from "./aiContext";+import { FRAME, mediaUrl, type FontId, type MediaAsset } from "./types";++const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));+const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);++class ToolError extends Error {}++/**+ * Execute an assistant tool call against the live editor store.+ * Returns a small JSON-safe result; throws ToolError with a readable message.+ */+export async function runAiTool(+ name: string,+ input: Record<string, unknown>+): Promise<unknown> {+ const s = useEditor.getState();++ switch (name) {+ case "get_state":+ return buildAiContext();++ case "capture_frame": {+ const canvas = document.querySelector<HTMLCanvasElement>(".stage canvas");+ if (!canvas) throw new ToolError("No preview canvas on screen.");+ const scaled = document.createElement("canvas");+ // Downscale at the frame's own aspect (long side 640).+ const k = 640 / Math.max(canvas.width, canvas.height);+ scaled.width = Math.round(canvas.width * k);+ scaled.height = Math.round(canvas.height * k);+ const ctx = scaled.getContext("2d")!;+ ctx.drawImage(canvas, 0, 0, scaled.width, scaled.height);+ // Overlays/captions are DOM, not canvas — note that for the model.+ return { image: scaled.toDataURL("image/jpeg", 0.75), note: "Video frame only; titles and captions overlay this in the UI." };+ }++ case "seek": {+ if (!isNum(input.t)) throw new ToolError("t (seconds) is required.");+ s.seek(input.t);+ return { playhead: useEditor.getState().currentTime };+ }++ case "set_playing":+ s.setPlaying(Boolean(input.playing));+ return { playing: Boolean(input.playing) };++ case "select": {+ const kind = String(input.kind);+ if (kind === "none") {+ s.select(null);+ return { selection: null };+ }+ const id = String(input.id ?? "");+ const pool =+ kind === "clip" ? s.clips : kind === "audio" ? s.audioClips : kind === "text" ? s.overlays : null;+ if (!pool) throw new ToolError(`Unknown kind: ${kind}`);+ if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);+ s.select({ kind: kind as "clip" | "audio" | "text", id });+ return { selection: { kind, id } };+ }++ case "split_at": {+ const before = s.clips.length + s.audioClips.length;+ s.splitAtPlayhead(isNum(input.t) ? input.t : undefined);+ const after = useEditor.getState();+ const made = after.clips.length + after.audioClips.length - before;+ if (made === 0) throw new ToolError("Nothing to split at that time.");+ return { split: true, videoClips: after.clips.length };+ }++ case "move_clip": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ if (!isNum(input.toIndex)) throw new ToolError("toIndex is required.");+ s.moveClip(clip.id, clamp(Math.round(input.toIndex), 0, s.clips.length - 1));+ return { order: useEditor.getState().clips.map((c) => c.id) };+ }++ case "trim_clip": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const asset = s.assets.find((a) => a.id === clip.assetId);+ const dur = asset?.duration ?? clip.out;+ const nextIn = isNum(input.in) ? clamp(input.in, 0, dur - 0.1) : clip.in;+ const nextOut = isNum(input.out) ? clamp(input.out, 0.1, dur) : clip.out;+ if (nextOut - nextIn < 0.1) throw new ToolError("Clip must stay at least 0.1s long.");+ s.updateClip(clip.id, { in: nextIn, out: nextOut });+ return { in: nextIn, out: nextOut, len: Math.round((nextOut - nextIn) * 100) / 100 };+ }++ case "set_clip_muted": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ s.updateClip(clip.id, { muted: Boolean(input.muted) });+ return { muted: Boolean(input.muted) };+ }++ case "detach_audio": {+ const id = input.clipId ? String(input.clipId) : s.selection?.kind === "clip" ? s.selection.id : null;+ if (!id) throw new ToolError("Pass clipId or select a video clip first.");+ const clip = requireItem(s.clips, id, "video clip");+ if (clip.muted) throw new ToolError("That clip's audio is muted — nothing to detach.");+ s.select({ kind: "clip", id: clip.id });+ s.detachAudio();+ const asset = s.assets.find((a) => a.id === clip.assetId);+ if (asset) void ensurePeaks(asset);+ const sel = useEditor.getState().selection;+ return { audioClipId: sel?.kind === "audio" ? sel.id : null };+ }++ case "delete_item": {+ const kind = String(input.kind) as "clip" | "audio" | "text";+ const id = String(input.id ?? "");+ const pool = kind === "clip" ? s.clips : kind === "audio" ? s.audioClips : s.overlays;+ if (!pool.some((x) => x.id === id)) throw new ToolError(`No ${kind} with id ${id}.`);+ s.select({ kind, id });+ s.deleteSelection();+ return { deleted: { kind, id } };+ }++ case "add_title": {+ if (typeof input.text !== "string" || !input.text.trim())+ throw new ToolError("text is required.");+ if (isNum(input.start)) s.seek(input.start);+ s.addOverlay();+ const cur = useEditor.getState();+ const sel = cur.selection;+ if (sel?.kind !== "text") throw new ToolError("Could not create the title.");+ cur.updateOverlayTransient(sel.id, titlePatch({ ...input, id: sel.id }));+ const o = useEditor.getState().overlays.find((x) => x.id === sel.id)!;+ return { id: o.id, text: o.text, start: o.start, end: o.end };+ }++ case "update_title": {+ const o = requireItem(s.overlays, input.id, "title");+ s.updateOverlay(o.id, titlePatch(input));+ const next = useEditor.getState().overlays.find((x) => x.id === o.id)!;+ return { id: next.id, text: next.text, color: next.color, size: next.size };+ }++ case "update_audio": {+ const a = requireItem(s.audioClips, input.id, "soundtrack clip");+ const len = a.out - a.in;+ const patch: Record<string, number> = {};+ if (isNum(input.volume)) patch.volume = clamp(input.volume, 0, 1.5);+ if (isNum(input.fadeIn)) patch.fadeIn = clamp(input.fadeIn, 0, len / 2);+ if (isNum(input.fadeOut)) patch.fadeOut = clamp(input.fadeOut, 0, len / 2);+ if (isNum(input.start)) patch.start = Math.max(0, input.start);+ if (isNum(input.in)) patch.in = Math.max(0, input.in);+ if (isNum(input.out)) patch.out = input.out;+ if (isNum(patch.in ?? NaN) || isNum(patch.out ?? NaN)) {+ const nIn = patch.in ?? a.in;+ const nOut = patch.out ?? a.out;+ if (nOut - nIn < 0.1) throw new ToolError("Audio clip must stay at least 0.1s long.");+ }+ if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");+ s.updateAudio(a.id, patch);+ return { id: a.id, ...patch };+ }++ case "set_framing": {+ const clip = requireItem(s.clips, input.clipId, "video clip");+ const mode = input.mode === "fill" ? "fill" : "fit";+ s.updateClip(clip.id, {+ fit: mode,+ panX: mode === "fill" && isNum(input.panX) ? clamp(input.panX, -1, 1) : 0,+ panY: mode === "fill" && isNum(input.panY) ? clamp(input.panY, -1, 1) : 0,+ });+ const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;+ return { id: next.id, fit: next.fit, panX: next.panX ?? 0, panY: next.panY ?? 0 };+ }++ case "freeze_frame": {+ const projectId = s.projectId;+ if (!projectId) throw new ToolError("No project open.");+ const spans = getClipSpans(s.clips, s.assets);+ if (spans.length === 0) throw new ToolError("The timeline is empty.");+ const total = totalDuration(s.clips);+ const t = clamp(isNum(input.t) ? input.t : s.currentTime, 0, Math.max(0, total - 0.001));+ const span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len) ?? spans[spans.length - 1];+ const srcTime = span.clip.in + (t - span.start);+ const res = await fetch(`/api/projects/${projectId}/freeze`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ file: span.asset.fileName,+ srcTime,+ duration: isNum(input.duration) ? input.duration : 1,+ // Bake the still at the current project frame, framed exactly as+ // the preview shows it. Switching aspect later letterboxes this+ // still — capture a fresh one to re-fit.+ frame: { w: FRAME[s.aspect].w, h: FRAME[s.aspect].h },+ framing: {+ fit: span.clip.fit ?? "fit",+ panX: span.clip.panX ?? 0,+ panY: span.clip.panY ?? 0,+ },+ }),+ });+ const body = (await res.json()) as MediaAsset & { error?: string };+ if (!res.ok) throw new ToolError(body.error ?? "Could not render the freeze frame.");+ const asset: MediaAsset = { ...body, url: mediaUrl(projectId, body.fileName) };+ const cur = useEditor.getState();+ cur.addAsset(asset);+ cur.addClipFromAsset(asset.id); // lands at the end, selected+ const sel = useEditor.getState().selection;+ const index = clamp(isNum(input.index) ? Math.round(input.index) : 0, 0, useEditor.getState().clips.length - 1);+ if (sel?.kind === "clip") cur.moveClip(sel.id, index);+ void enrichAsset(asset);+ return {+ clipId: sel?.kind === "clip" ? sel.id : null,+ index,+ duration: body.duration,+ from: { time: Math.round(t * 100) / 100, source: span.asset.name },+ };+ }++ case "subtitles_generate": {+ if (typeof input.locale === "string" && input.locale) {+ s.setSubtitlesView({ locale: input.locale });+ }+ await s.generateSubtitles();+ const cur = useEditor.getState();+ if (cur.subtitleStatus === "error")+ throw new ToolError(cur.subtitleError ?? "Transcription failed.");+ if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ return {+ status: cur.subtitleStatus,+ cues: cur.subtitles.cues.length,+ note:+ cur.subtitleStatus === "empty"+ ? "No speech found — no subtitles were added to the video."+ : undefined,+ };+ }++ case "subtitles_set_view": {+ const patch: { showOnVideo?: boolean; showOnTimeline?: boolean } = {};+ if (typeof input.showOnVideo === "boolean") patch.showOnVideo = input.showOnVideo;+ if (typeof input.showOnTimeline === "boolean") patch.showOnTimeline = input.showOnTimeline;+ s.setSubtitlesView(patch);+ if (patch.showOnTimeline && s.subtitles.cues.length > 0 && s.timelineH < 276) s.setTimelineH(276);+ return patch;+ }++ case "update_cue": {+ const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");+ if (typeof input.text === "string") s.setCueText(cue.id, input.text);+ if (isNum(input.start) || isNum(input.end)) {+ const start = isNum(input.start) ? Math.max(0, input.start) : cue.start;+ const end = isNum(input.end) ? input.end : cue.end;+ if (end - start < 0.15) throw new ToolError("Cue must stay at least 0.15s long.");+ s.pushHistory();+ s.updateCueTransient(cue.id, { start, end, words: undefined });+ s.sortCues();+ }+ const next = useEditor.getState().subtitles.cues.find((c) => c.id === cue.id);+ return next ? { id: next.id, start: next.start, end: next.end, text: next.text } : { deleted: cue.id };+ }++ case "delete_cue": {+ const cue = requireItem(s.subtitles.cues, input.id, "subtitle cue");+ s.deleteCue(cue.id);+ return { deleted: cue.id };+ }++ case "set_publish": {+ const patch: Record<string, string> = {};+ for (const k of ["caption", "tags", "soundTitle", "handle"] as const) {+ if (typeof input[k] === "string") patch[k] = input[k] as string;+ }+ if (Object.keys(patch).length === 0) throw new ToolError("Nothing to change.");+ s.setPublish(patch);+ return patch;+ }++ case "set_view": {+ const out: Record<string, number> = {};+ if (input.fit) {+ const el = document.querySelector<HTMLElement>(".tl-scroll");+ const dur = totalDuration(s.clips);+ if (el && dur > 0) {+ s.setPxPerSec((el.clientWidth - 60) / dur);+ el.scrollLeft = 0;+ }+ out.pxPerSec = useEditor.getState().pxPerSec;+ } else if (isNum(input.pxPerSec)) {+ s.setPxPerSec(input.pxPerSec);+ out.pxPerSec = useEditor.getState().pxPerSec;+ }+ if (isNum(input.timelineH)) {+ s.setTimelineH(clamp(input.timelineH, TIMELINE_H_MIN, TIMELINE_H_MAX));+ out.timelineH = useEditor.getState().timelineH;+ }+ return out;+ }++ case "undo":+ s.undo();+ return { ok: true };+ case "redo":+ s.redo();+ return { ok: true };++ case "open_export": {+ if (getClipSpans(s.clips, s.assets).length === 0)+ throw new ToolError("Add a video to the timeline first.");+ s.setExportOpen(true);+ return { open: true };+ }++ default:+ throw new ToolError(`Unknown tool: ${name}`);+ }+}++function requireItem<T extends { id: string }>(pool: T[], id: unknown, label: string): T {+ const item = pool.find((x) => x.id === String(id ?? ""));+ if (!item) throw new ToolError(`No ${label} with id ${String(id)}. Call get_state for current ids.`);+ return item;+}++function titlePatch(input: Record<string, unknown>) {+ const patch: Record<string, unknown> = {};+ if (typeof input.text === "string" && input.text.trim()) patch.text = input.text;+ if (isNum(input.start)) patch.start = Math.max(0, input.start);+ if (isNum(input.end)) patch.end = input.end;+ if (isNum(input.x)) patch.x = clamp(input.x, 0.02, 0.98);+ if (isNum(input.y)) patch.y = clamp(input.y, 0.02, 0.98);+ if (isNum(input.size)) patch.size = clamp(Math.round(input.size), 16, 320);+ if (typeof input.color === "string") patch.color = input.color;+ if (["sf", "serif", "rounded", "mono", "impact"].includes(String(input.font)))+ patch.font = input.font as FontId;+ if (input.weight === 400 || input.weight === 700) patch.weight = input.weight;+ if (typeof input.shadow === "boolean") patch.shadow = input.shadow;+ if (typeof input.plate === "boolean") patch.plate = input.plate;+ if (isNum(input.plateRadius)) patch.plateRadius = clamp(input.plateRadius, 0, 1);+ return patch;+}diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.tsnew file mode 100644index 00000000..63a615db--- /dev/null+++ b/site/src/cut/lib/assetDrag.ts@@ -0,0 +1,25 @@+"use client";++import type React from "react";++/** Internal HTML5 drag payload for project media assets. The custom MIME+ * keeps these drags invisible to the window-level OS-file import overlay,+ * which only reacts to `Files`. */+export const ASSET_MIME = "application/x-cut-asset";++export function setAssetDragData(e: React.DragEvent, assetId: string) {+ e.dataTransfer.setData(ASSET_MIME, assetId);+ e.dataTransfer.effectAllowed = "copy";+}++export function draggedAssetId(e: React.DragEvent | DragEvent): string | null {+ const dt = "dataTransfer" in e ? e.dataTransfer : null;+ if (!dt || !Array.from(dt.types).includes(ASSET_MIME)) return null;+ return dt.getData(ASSET_MIME) || null;+}++/** True while dragging (getData is only readable on drop). */+export function hasAssetDrag(e: React.DragEvent | DragEvent): boolean {+ const dt = "dataTransfer" in e ? e.dataTransfer : null;+ return !!dt && Array.from(dt.types).includes(ASSET_MIME);+}diff --git a/site/src/cut/lib/drag.ts b/site/src/cut/lib/drag.tsnew file mode 100644index 00000000..827ebfee--- /dev/null+++ b/site/src/cut/lib/drag.ts@@ -0,0 +1,33 @@+"use client";++import type React from "react";++interface DragOpts {+ onMove: (dx: number, dy: number, ev: PointerEvent) => void;+ onUp?: (dx: number, dy: number, moved: boolean) => void;+}++/** Pointer-drag helper: tracks deltas from pointerdown until release. */+export function startDrag(e: React.PointerEvent, opts: DragOpts) {+ e.preventDefault();+ e.stopPropagation();+ const startX = e.clientX;+ const startY = e.clientY;+ let moved = false;++ const move = (ev: PointerEvent) => {+ const dx = ev.clientX - startX;+ const dy = ev.clientY - startY;+ if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true;+ opts.onMove(dx, dy, ev);+ };+ const up = (ev: PointerEvent) => {+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", up);+ window.removeEventListener("pointercancel", up);+ opts.onUp?.(ev.clientX - startX, ev.clientY - startY, moved);+ };+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", up);+ window.addEventListener("pointercancel", up);+}diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsnew file mode 100644index 00000000..5f799c12--- /dev/null+++ b/site/src/cut/lib/exportClient.ts@@ -0,0 +1,171 @@+"use client";++import { getClipSpans, totalDuration } from "./store";+import { cueOverlay } from "./subtitles";+import { renderOverlayPng } from "./textRender";+import type { Aspect, AudioClip, MediaAsset, SubtitlesBlock, TextOverlay, VideoClip } from "./types";++export interface ExportSettings {+ width: number;+ height: number;+ fps: number;+ crf: number;+ preset: string;+}++/** Presets are stored portrait (9:16); `presetSettings` flips them for 16:9. */+export const EXPORT_PRESETS = [+ {+ id: "tiktok",+ label: "Best · 1080p",+ detail: "H.264 · best quality",+ settings: { width: 1080, height: 1920, fps: 30, crf: 19, preset: "medium" },+ },+ {+ id: "fast",+ label: "Quick share · 1080p",+ detail: "smaller file, faster",+ settings: { width: 1080, height: 1920, fps: 30, crf: 24, preset: "veryfast" },+ },+ {+ id: "light",+ label: "Draft · 720p",+ detail: "fastest render",+ settings: { width: 720, height: 1280, fps: 30, crf: 24, preset: "veryfast" },+ },+] as const;++export function presetSettings(+ preset: (typeof EXPORT_PRESETS)[number],+ aspect: Aspect+): ExportSettings {+ const { width, height, ...rest } = preset.settings;+ return aspect === "16:9"+ ? { width: height, height: width, ...rest }+ : { width, height, ...rest };+}++export interface ExportHandle {+ cancel: () => void;+ done: Promise<{ outName: string }>;+}++export function startExport(+ projectId: string,+ doc: {+ assets: MediaAsset[];+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: TextOverlay[];+ subtitles: SubtitlesBlock;+ },+ settings: ExportSettings,+ onProgress: (stage: string, ratio: number) => void+): ExportHandle {+ let jobId: string | null = null;+ let canceled = false;++ const done = (async () => {+ const spans = getClipSpans(doc.clips, doc.assets);+ if (spans.length === 0) throw new Error("Add a video to the timeline first.");+ const duration = totalDuration(doc.clips);++ onProgress("Preparing", 0);+ const form = new FormData();+ const assetById = new Map(doc.assets.map((a) => [a.id, a]));++ // Media already lives in the project folder — the spec references it by+ // file name; only overlay PNGs travel with the request.+ const clips = spans.map((sp) => ({+ file: sp.asset.fileName,+ in: sp.clip.in,+ out: sp.clip.out,+ muted: sp.clip.muted,+ fit: sp.clip.fit ?? "fit",+ panX: sp.clip.panX ?? 0,+ panY: sp.clip.panY ?? 0,+ }));++ const audio = doc.audioClips+ .filter((a) => a.start < duration && assetById.has(a.assetId))+ .map((a) => ({+ file: assetById.get(a.assetId)!.fileName,+ in: a.in,+ out: a.out,+ start: a.start,+ volume: a.volume,+ fadeIn: a.fadeIn ?? 0,+ fadeOut: a.fadeOut ?? 0,+ }));++ const overlays: { file: string; start: number; end: number }[] = [];+ for (let i = 0; i < doc.overlays.length; i++) {+ const o = doc.overlays[i];+ if (o.start >= duration || !o.text.trim()) continue;+ const png = await renderOverlayPng(o, settings.width, settings.height);+ const key = `overlay_${i}.png`;+ form.append(key, png, key);+ overlays.push({ file: key, start: o.start, end: Math.min(o.end, duration) });+ }++ // Subtitles burn in through the same overlay pipeline. When there are no+ // cues (no speech was found) nothing is added to the video.+ if (doc.subtitles.showOnVideo) {+ for (let i = 0; i < doc.subtitles.cues.length; i++) {+ const cue = doc.subtitles.cues[i];+ if (cue.start >= duration || !cue.text.trim()) continue;+ const png = await renderOverlayPng(cueOverlay(cue), settings.width, settings.height);+ const key = `sub_${i}.png`;+ form.append(key, png, key);+ overlays.push({ file: key, start: cue.start, end: Math.min(cue.end, duration) });+ }+ }++ form.append(+ "spec",+ JSON.stringify({ projectId, ...settings, duration, clips, audio, overlays })+ );++ onProgress("Starting encoder", 0);+ const res = await fetch("/api/export", { method: "POST", body: form });+ const body = (await res.json()) as { id?: string; error?: string };+ if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");+ jobId = body.id;++ let outName = "export.mp4";+ for (;;) {+ if (canceled) throw new Error("Export canceled.");+ await new Promise((r) => setTimeout(r, 400));+ const st = await fetch(`/api/export/${jobId}`);+ const status = (await st.json()) as {+ status: string;+ progress: number;+ error?: string;+ outName?: string;+ };+ if (status.status === "error") throw new Error(status.error ?? "Export failed.");+ onProgress("Rendering", status.progress);+ if (status.status === "done") {+ outName = status.outName ?? outName;+ break;+ }+ }++ onProgress("Done", 1);+ const a = document.createElement("a");+ a.href = `/api/export/${jobId}/file`;+ a.download = outName;+ document.body.appendChild(a);+ a.click();+ a.remove();+ return { outName };+ })();++ return {+ done,+ cancel: () => {+ canceled = true;+ if (jobId) void fetch(`/api/export/${jobId}`, { method: "DELETE" });+ },+ };+}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsnew file mode 100644index 00000000..13877754--- /dev/null+++ b/site/src/cut/lib/library.ts@@ -0,0 +1,81 @@+"use client";++import { useEditor } from "./store";+import type { MediaAsset } from "./types";+import { mediaUrl } from "./types";++export interface LibraryAsset {+ id: string;+ fileName: string;+ name: string;+ type: "video" | "audio";+ duration: number;+ width?: number;+ height?: number;+ addedAt: number;+}++export const libraryMediaUrl = (fileName: string) =>+ `/api/library/media/${encodeURIComponent(fileName)}`;++export async function fetchLibrary(): Promise<LibraryAsset[]> {+ const res = await fetch("/api/library");+ if (!res.ok) throw new Error("Could not load the library.");+ return (await res.json()) as LibraryAsset[];+}++export async function uploadToLibrary(file: File): Promise<LibraryAsset> {+ const form = new FormData();+ form.append("file", file, file.name);+ const res = await fetch("/api/library", { method: "POST", body: form });+ const body = (await res.json()) as LibraryAsset & { error?: string };+ if (!res.ok) throw new Error(body.error ?? "Upload failed.");+ return body;+}++export async function deleteFromLibrary(id: string) {+ const res = await fetch(`/api/library/${id}`, { method: "DELETE" });+ if (!res.ok) throw new Error("Could not delete.");+}++/** Copy a library asset into the open project and put it on the timeline. */+export async function addLibraryAssetToProject(+ projectId: string,+ lib: LibraryAsset+): Promise<MediaAsset> {+ const res = await fetch("/api/library/use", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ assetId: lib.id, projectId }),+ });+ const body = (await res.json()) as { fileName?: string; error?: string };+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not add from library.");++ const asset: MediaAsset = {+ id: crypto.randomUUID().slice(0, 8),+ fileName: body.fileName,+ name: lib.name,+ type: lib.type,+ duration: lib.duration,+ width: lib.width,+ height: lib.height,+ url: mediaUrl(projectId, body.fileName),+ };+ const s = useEditor.getState();+ s.addAsset(asset);+ if (asset.type === "video") s.addClipFromAsset(asset.id);+ else s.addAudioFromAsset(asset.id);+ return asset;+}++/** Copy a project asset into the shared library for reuse. */+export async function saveAssetToLibrary(projectId: string, asset: MediaAsset) {+ const res = await fetch("/api/library/save", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ projectId, fileName: asset.fileName, name: asset.name }),+ });+ const body = (await res.json()) as LibraryAsset & { error?: string };+ if (!res.ok) throw new Error(body.error ?? "Could not save to library.");+ return body;+}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsnew file mode 100644index 00000000..9c4cef92--- /dev/null+++ b/site/src/cut/lib/media.ts@@ -0,0 +1,203 @@+"use client";++import { useEditor } from "./store";+import type { MediaAsset } from "./types";+import { mediaUrl } from "./types";++const uid = () => crypto.randomUUID().slice(0, 8);++export function isVideoFile(file: File) {+ return file.type.startsWith("video/") || /\.(mp4|mov|m4v|webm|mkv)$/i.test(file.name);+}++export function isAudioFile(file: File) {+ return file.type.startsWith("audio/") || /\.(mp3|m4a|aac|wav|ogg|flac)$/i.test(file.name);+}++/** Upload a raw file into the project folder, probe it, and return the asset.+ * Thumbnails/waveform are filled in asynchronously via `enrichAsset`. */+export async function importFileToProject(+ projectId: string,+ file: File+): Promise<MediaAsset | null> {+ // MIME wins over extension: recordings are .webm for both video and audio.+ const type = file.type.startsWith("video/")+ ? "video"+ : file.type.startsWith("audio/")+ ? "audio"+ : isVideoFile(file)+ ? "video"+ : isAudioFile(file)+ ? "audio"+ : null;+ if (!type) return null;++ const form = new FormData();+ form.append("file", file, file.name);+ const res = await fetch(`/api/projects/${projectId}/media`, {+ method: "POST",+ body: form,+ });+ const body = (await res.json()) as { fileName?: string; error?: string };+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Upload failed.");++ const url = mediaUrl(projectId, body.fileName);+ const asset: MediaAsset = {+ id: uid(),+ fileName: body.fileName,+ name: file.name,+ type,+ duration: 0,+ url,+ };++ if (type === "video") {+ const v = await loadVideoMeta(url);+ if (v.videoWidth === 0) {+ // A "video" container with no video stream is really audio.+ asset.type = "audio";+ asset.duration = v.duration;+ } else {+ asset.duration = v.duration;+ asset.width = v.videoWidth;+ asset.height = v.videoHeight;+ }+ } else {+ asset.duration = await loadAudioDuration(url);+ }+ return asset;+}++/** Generate filmstrip thumbnails / waveform peaks and merge them into the+ * store. Safe to call repeatedly; skips assets that are already enriched. */+export async function enrichAsset(asset: MediaAsset) {+ try {+ if (asset.type === "video" && !asset.thumbs?.length) {+ const { thumbs, thumbStep } = await makeThumbs(asset.url, asset.duration);+ useEditor.getState().updateAsset(asset.id, { thumbs, thumbStep });+ } else if (asset.type === "audio" && !asset.peaks?.length) {+ const peaks = await makePeaks(asset.url);+ useEditor.getState().updateAsset(asset.id, { peaks });+ }+ } catch {+ // Thumbnails and waveforms are decorative; editing works without them.+ }+}++/** Waveform peaks on demand — e.g. when a video clip's audio is detached+ * onto the soundtrack track (video assets don't get peaks at import). */+export async function ensurePeaks(asset: MediaAsset) {+ try {+ if (!asset.peaks?.length) {+ const peaks = await makePeaks(asset.url);+ useEditor.getState().updateAsset(asset.id, { peaks });+ }+ } catch {+ // Waveforms are decorative; editing works without them.+ }+}++/** MediaRecorder webm files report Infinity until seeked to the end. */+function ensureFiniteDuration(el: HTMLVideoElement | HTMLAudioElement): Promise<number> {+ if (Number.isFinite(el.duration) && el.duration > 0) return Promise.resolve(el.duration);+ return new Promise((resolve) => {+ const done = () => {+ el.removeEventListener("durationchange", done);+ clearTimeout(timer);+ el.currentTime = 0;+ resolve(Number.isFinite(el.duration) ? el.duration : 0);+ };+ const timer = setTimeout(done, 4000);+ el.addEventListener("durationchange", done);+ el.currentTime = 1e7;+ });+}++function loadVideoMeta(url: string): Promise<HTMLVideoElement> {+ return new Promise((resolve, reject) => {+ const v = document.createElement("video");+ v.preload = "metadata";+ v.muted = true;+ v.src = url;+ v.onloadedmetadata = () => void ensureFiniteDuration(v).then(() => resolve(v));+ v.onerror = () => reject(new Error("Could not read this video file."));+ });+}++function loadAudioDuration(url: string): Promise<number> {+ return new Promise((resolve, reject) => {+ const a = new Audio();+ a.preload = "metadata";+ a.src = url;+ a.onloadedmetadata = () => void ensureFiniteDuration(a).then(resolve);+ a.onerror = () => reject(new Error("Could not read this audio file."));+ });+}++// Filmstrip frames render at 60 CSS px tall — capture at 2× for Retina.+const THUMB_H = 120;++async function makeThumbs(url: string, duration: number) {+ const v = await loadVideoMeta(url);+ // One frame every ~2s (min 10, max 24) so long clips don't repeat frames.+ const count = Math.min(24, Math.max(10, Math.round(duration / 2)));+ const thumbStep = duration / count;+ const aspect = v.videoWidth / Math.max(1, v.videoHeight);+ const w = Math.max(64, Math.round(THUMB_H * aspect));+ const canvas = document.createElement("canvas");+ canvas.width = w;+ canvas.height = THUMB_H;+ const ctx = canvas.getContext("2d")!;+ ctx.imageSmoothingQuality = "high";+ const thumbs: string[] = [];+ for (let i = 0; i < count; i++) {+ const t = Math.min(duration - 0.05, (i + 0.5) * thumbStep);+ await seekTo(v, Math.max(0, t));+ ctx.drawImage(v, 0, 0, w, THUMB_H);+ thumbs.push(canvas.toDataURL("image/jpeg", 0.85));+ }+ v.removeAttribute("src");+ v.load();+ return { thumbs, thumbStep };+}++function seekTo(v: HTMLVideoElement, t: number): Promise<void> {+ return new Promise((resolve) => {+ const done = () => {+ v.removeEventListener("seeked", done);+ clearTimeout(timer);+ resolve();+ };+ const timer = setTimeout(done, 1500);+ v.addEventListener("seeked", done);+ v.currentTime = t;+ });+}++const PEAK_BUCKETS = 1600;++async function makePeaks(url: string): Promise<number[]> {+ const buf = await (await fetch(url)).arrayBuffer();+ const AC: typeof AudioContext =+ window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;+ const ctx = new AC();+ try {+ const audio = await ctx.decodeAudioData(buf);+ const data = audio.getChannelData(0);+ const bucketSize = Math.max(1, Math.floor(data.length / PEAK_BUCKETS));+ const peaks: number[] = [];+ for (let i = 0; i < PEAK_BUCKETS; i++) {+ let max = 0;+ const from = i * bucketSize;+ const to = Math.min(data.length, from + bucketSize);+ for (let j = from; j < to; j += 8) {+ const v = Math.abs(data[j]);+ if (v > max) max = v;+ }+ peaks.push(max);+ }+ return peaks;+ } finally {+ void ctx.close();+ }+}diff --git a/site/src/cut/lib/publish.ts b/site/src/cut/lib/publish.tsnew file mode 100644index 00000000..bd39c768--- /dev/null+++ b/site/src/cut/lib/publish.ts@@ -0,0 +1,11 @@+/** TikTok caption limit; hashtags, mentions, and emoji all count toward it. */+export const CAPTION_LIMIT = 4000;++/** "fyp, how to" → "#fyp #howto"-style hashtag line. */+export const normalizeTags = (raw: string) =>+ raw+ .split(/[\s,]+/)+ .map((t) => t.replace(/^#+/, ""))+ .filter(Boolean)+ .map((t) => `#${t}`)+ .join(" ");diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsnew file mode 100644index 00000000..88f4b359--- /dev/null+++ b/site/src/cut/lib/store.ts@@ -0,0 +1,868 @@+"use client";++import { create } from "zustand";+import type {+ Aspect,+ AudioClip,+ ClipSpan,+ MediaAsset,+ ProjectDoc,+ Selection,+ StoredAsset,+ SubtitleCue,+ SubtitlesBlock,+ TextOverlay,+ VideoClip,+} from "./types";+import { emptySubtitles, mediaUrl } from "./types";+import { loadUiState, saveUiState } from "./uiState";++const uid = () => crypto.randomUUID().slice(0, 8);++const MIN_LEN = 0.1;++export const TIMELINE_H_DEFAULT = 248;+export const TIMELINE_H_MIN = 170;+export const TIMELINE_H_MAX = 600;++interface DocSnapshot {+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: TextOverlay[];+ subtitles: SubtitlesBlock;+}++export type SubtitleStatus = "idle" | "running" | "ready" | "empty" | "error";++export type SaveState = "saved" | "dirty" | "saving" | "error";++interface EditorState {+ projectId: string | null;+ projectName: string;+ loaded: boolean;+ loadError: string | null;+ saveState: SaveState;++ assets: MediaAsset[];+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: TextOverlay[];+ /** Output frame (9:16 vertical or 16:9 widescreen), persisted per project. */+ aspect: Aspect;+ selection: Selection;+ currentTime: number;+ playing: boolean;+ pxPerSec: number;+ /** Timeline panel height in px (drag the panel's top border to change). */+ timelineH: number;+ /** Timeline time under the mouse (iMovie skimmer); null when off the timeline. */+ skimTime: number | null;+ /** TikTok publishing metadata (caption, hashtags, sound title). */+ publish: { caption: string; tags: string; soundTitle: string; handle: string };+ /** Subtitles: cues + visibility, persisted with the project. */+ subtitles: SubtitlesBlock;+ subtitleStatus: SubtitleStatus;+ subtitleError: string | null;+ exportOpen: boolean;+ dropActive: boolean;+ /** Whether the AI assistant panel is open (remembered across sessions). */+ aiOpen: boolean;++ loadProject: (id: string) => Promise<void>;+ setProjectName: (name: string) => void;+ setSaveState: (s: SaveState) => void;++ setAspect: (a: Aspect) => void;+ addAsset: (asset: MediaAsset) => void;+ updateAsset: (id: string, patch: Partial<MediaAsset>) => void;+ addClipFromAsset: (assetId: string) => void;+ addAudioFromAsset: (assetId: string, start?: number) => void;+ addOverlay: () => void;+ updateClip: (id: string, patch: Partial<VideoClip>) => void;+ updateAudio: (id: string, patch: Partial<AudioClip>) => void;+ updateOverlay: (id: string, patch: Partial<TextOverlay>) => void;+ /** Live-drag updates that should not create undo entries. */+ updateOverlayTransient: (id: string, patch: Partial<TextOverlay>) => void;+ updateClipTransient: (id: string, patch: Partial<VideoClip>) => void;+ updateAudioTransient: (id: string, patch: Partial<AudioClip>) => void;+ moveClip: (id: string, toIndex: number) => void;+ /** iMovie "Detach Audio": lift the selected clip's sound onto the+ * soundtrack track (and mute the clip) so it can be cut independently. */+ detachAudio: () => void;+ /** Split at the given time, or the playhead when omitted. */+ splitAtPlayhead: (at?: number) => void;+ setSkimTime: (t: number | null) => void;+ setPublish: (patch: Partial<{ caption: string; tags: string; soundTitle: string; handle: string }>) => void;+ /** Kick off (and poll) an on-device transcription of the current cut. */+ generateSubtitles: () => Promise<void>;+ setSubtitlesView: (patch: Partial<Pick<SubtitlesBlock, "showOnVideo" | "showOnTimeline" | "locale">>) => void;+ /** Commit a cue's edited text (empty text deletes the cue). */+ setCueText: (id: string, text: string) => void;+ /** Split a cue at a character offset — at real word timings when known. */+ splitCue: (id: string, charOffset: number) => void;+ mergeCueIntoPrev: (id: string) => void;+ deleteCue: (id: string) => void;+ updateCueTransient: (id: string, patch: Partial<SubtitleCue>) => void;+ sortCues: () => void;+ deleteSelection: () => void;+ select: (sel: Selection) => void;+ seek: (t: number) => void;+ setPlaying: (p: boolean) => void;+ setPxPerSec: (v: number) => void;+ setTimelineH: (h: number) => void;+ setExportOpen: (v: boolean) => void;+ setDropActive: (v: boolean) => void;+ setAiOpen: (v: boolean) => void;+ undo: () => void;+ redo: () => void;+ pushHistory: () => void;+ /** Copy the selected clip/audio/title to the timeline clipboard. */+ copySelection: () => boolean;+ /** Paste the clipboard at the playhead; selects the pasted item. */+ paste: () => boolean;+}++// Per-project undo/redo stacks; both reset when a project loads. Capped so a+// long session (each snapshot deep-copies every clip/cue) can't grow unbounded.+const HISTORY_CAP = 100;+const history: DocSnapshot[] = [];+const future: DocSnapshot[] = [];+/** A checkpoint captured on pointerdown/focus but not yet committed: it lands+ * in `history` only once an edit actually follows (see flush), so a bare+ * click-to-select never records a no-op snapshot or clears the redo branch. */+let pending: { snap: DocSnapshot; seq: number } | null = null;+/** Bumped whenever the persistable doc actually changes, letting a pending+ * checkpoint tell a real edit apart from a select/seek that touched nothing. */+let docSeq = 0;++/** Timeline clipboard (⌘C/⌘V) — survives across projects in one session. */+type Clipboard =+ | { kind: "clip"; item: VideoClip }+ | { kind: "audio"; item: AudioClip }+ | { kind: "text"; item: TextOverlay }+ | null;+let clipboard: Clipboard = null;++export const useEditor = create<EditorState>((set, get) => {+ const snapshot = (): DocSnapshot => {+ const { clips, audioClips, overlays, subtitles } = get();+ return {+ clips: clips.map((c) => ({ ...c })),+ audioClips: audioClips.map((c) => ({ ...c })),+ overlays: overlays.map((o) => ({ ...o })),+ subtitles: {+ ...subtitles,+ cues: subtitles.cues.map((c) => ({ ...c, words: c.words?.map((w) => ({ ...w })) })),+ },+ };+ };++ /** Seal the deferred checkpoint: commit it to history only if the doc+ * changed since it was taken; otherwise drop it and leave redo intact. */+ const flush = () => {+ if (!pending) return;+ const p = pending;+ pending = null;+ if (docSeq !== p.seq) {+ history.push(p.snap);+ if (history.length > HISTORY_CAP) history.shift();+ future.length = 0; // a real edit invalidates the redo branch+ }+ };++ const push = () => {+ flush(); // seal the previous edit's checkpoint before starting a new one+ pending = { snap: snapshot(), seq: docSeq };+ };++ return {+ projectId: null,+ projectName: "",+ loaded: false,+ loadError: null,+ saveState: "saved",++ assets: [],+ clips: [],+ audioClips: [],+ overlays: [],+ aspect: "9:16",+ selection: null,+ currentTime: 0,+ playing: false,+ pxPerSec: 60,+ timelineH: TIMELINE_H_DEFAULT,+ skimTime: null,+ publish: { caption: "", tags: "", soundTitle: "", handle: "" },+ subtitles: emptySubtitles(),+ subtitleStatus: "idle",+ subtitleError: null,+ exportOpen: false,+ dropActive: false,+ aiOpen: typeof window !== "undefined" && localStorage.getItem("cut-ai-open") === "1",++ loadProject: async (id) => {+ history.length = 0;+ future.length = 0;+ pending = null;+ set({+ projectId: id,+ loaded: false,+ loadError: null,+ saveState: "saved",+ assets: [],+ clips: [],+ audioClips: [],+ overlays: [],+ aspect: "9:16",+ selection: null,+ currentTime: 0,+ playing: false,+ subtitles: emptySubtitles(),+ subtitleStatus: "idle",+ subtitleError: null,+ exportOpen: false,+ });+ try {+ const [res, ui] = await Promise.all([fetch(`/api/projects/${id}`), loadUiState(id)]);+ if (!res.ok) throw new Error("This project no longer exists.");+ const doc = (await res.json()) as ProjectDoc;+ const assets: MediaAsset[] = doc.assets.map((a) => ({+ ...a,+ url: mediaUrl(id, a.fileName),+ }));+ set({+ projectName: doc.name,+ assets,+ clips: doc.clips,+ audioClips: doc.audioClips,+ overlays: doc.overlays,+ aspect: doc.aspect ?? "9:16",+ // View state lives in IndexedDB; doc.ui covers projects saved+ // before the move.+ pxPerSec: Math.max(12, Math.min(800, ui.pxPerSec ?? doc.ui?.pxPerSec ?? 60)),+ timelineH: Math.max(+ TIMELINE_H_MIN,+ Math.min(TIMELINE_H_MAX, ui.timelineH ?? TIMELINE_H_DEFAULT)+ ),+ publish: {+ caption: doc.publish?.caption ?? "",+ tags: doc.publish?.tags ?? "",+ soundTitle: doc.publish?.soundTitle ?? "",+ handle: doc.publish?.handle ?? "",+ },+ subtitles: doc.subtitles ?? emptySubtitles(),+ subtitleStatus: (doc.subtitles?.cues.length ?? 0) > 0 ? "ready" : "idle",+ loaded: true,+ });+ } catch (err) {+ set({ loadError: err instanceof Error ? err.message : String(err) });+ }+ },++ setProjectName: (name) => set({ projectName: name }),+ setSaveState: (s) => set({ saveState: s }),++ pushHistory: push,++ setAspect: (a) => set({ aspect: a }),++ addAsset: (asset) =>+ set((s) => {+ // The first video in an untouched project decides the starting frame+ // (landscape footage → 16:9, portrait → 9:16); the user can switch it+ // any time from the top bar.+ const guess =+ asset.type === "video" &&+ asset.width !== undefined &&+ asset.height !== undefined &&+ s.clips.length === 0 &&+ !s.assets.some((a) => a.type === "video")+ ? asset.width >= asset.height+ ? ("16:9" as Aspect)+ : ("9:16" as Aspect)+ : null;+ return { assets: [...s.assets, asset], ...(guess ? { aspect: guess } : {}) };+ }),++ updateAsset: (id, patch) =>+ set((s) => ({+ assets: s.assets.map((a) => (a.id === id ? { ...a, ...patch } : a)),+ })),++ addClipFromAsset: (assetId) => {+ const asset = get().assets.find((a) => a.id === assetId);+ if (!asset || asset.type !== "video") return;+ push();+ const clip: VideoClip = {+ id: uid(),+ assetId,+ in: 0,+ out: asset.duration,+ muted: false,+ };+ set((s) => ({+ clips: [...s.clips, clip],+ selection: { kind: "clip", id: clip.id },+ }));+ },++ addAudioFromAsset: (assetId, start) => {+ const asset = get().assets.find((a) => a.id === assetId);+ if (!asset || asset.type !== "audio") return;+ push();+ const clip: AudioClip = {+ id: uid(),+ assetId,+ start: Math.max(0, start ?? get().currentTime),+ in: 0,+ out: asset.duration,+ volume: 1,+ };+ set((s) => ({+ audioClips: [...s.audioClips, clip],+ selection: { kind: "audio", id: clip.id },+ }));+ },++ addOverlay: () => {+ push();+ const t = get().currentTime;+ const total = totalDuration(get().clips);+ const start = Math.min(t, Math.max(0, total - 0.5));+ const overlay: TextOverlay = {+ id: uid(),+ text: "Your text",+ start,+ end: Math.min(start + 3, Math.max(total, start + 3)),+ x: 0.5,+ y: 0.42,+ size: 88,+ font: "sf",+ weight: 700,+ color: "#FFFFFF",+ shadow: true,+ plate: false,+ };+ set((s) => ({+ overlays: [...s.overlays, overlay],+ selection: { kind: "text", id: overlay.id },+ }));+ },++ // The non-transient updaters are just a checkpoint plus the live update.+ updateClip: (id, patch) => {+ push();+ get().updateClipTransient(id, patch);+ },+ updateAudio: (id, patch) => {+ push();+ get().updateAudioTransient(id, patch);+ },+ updateOverlay: (id, patch) => {+ push();+ get().updateOverlayTransient(id, patch);+ },++ updateOverlayTransient: (id, patch) =>+ set((s) => ({+ overlays: s.overlays.map((o) => (o.id === id ? { ...o, ...patch } : o)),+ })),++ updateClipTransient: (id, patch) =>+ set((s) => ({+ clips: s.clips.map((c) => (c.id === id ? { ...c, ...patch } : c)),+ })),++ updateAudioTransient: (id, patch) =>+ set((s) => ({+ audioClips: s.audioClips.map((c) =>+ c.id === id ? { ...c, ...patch } : c+ ),+ })),++ moveClip: (id, toIndex) => {+ const { clips } = get();+ const from = clips.findIndex((c) => c.id === id);+ if (from < 0) return;+ const to = Math.max(0, Math.min(clips.length - 1, toIndex));+ if (to === from) return;+ push();+ const next = [...clips];+ const [moved] = next.splice(from, 1);+ next.splice(to, 0, moved);+ set({ clips: next });+ },++ detachAudio: () => {+ const { clips, assets, selection } = get();+ if (selection?.kind !== "clip") return;+ const clip = clips.find((c) => c.id === selection.id);+ if (!clip || clip.muted) return; // no sound to detach+ const span = getClipSpans(clips, assets).find((sp) => sp.clip.id === clip.id);+ if (!span) return;+ push();+ const audio: AudioClip = {+ id: uid(),+ assetId: clip.assetId,+ start: span.start,+ in: clip.in,+ out: clip.out,+ volume: 1,+ };+ set((s) => ({+ audioClips: [...s.audioClips, audio],+ clips: s.clips.map((c) => (c.id === clip.id ? { ...c, muted: true } : c)),+ selection: { kind: "audio", id: audio.id },+ }));+ },++ splitAtPlayhead: (at) => {+ const { clips, audioClips, assets, currentTime, selection } = get();+ const t = at ?? currentTime;++ // iMovie-style: with a soundtrack clip selected, ⌘B slices it instead.+ if (selection?.kind === "audio") {+ const a = audioClips.find((c) => c.id === selection.id);+ const len = a ? clipLen(a) : 0;+ if (a && t > a.start + 0.05 && t < a.start + len - 0.05) {+ push();+ const cutIn = a.in + (t - a.start);+ const left: AudioClip = { ...a, out: cutIn };+ const right: AudioClip = { ...a, id: uid(), start: t, in: cutIn };+ set((s) => {+ const idx = s.audioClips.findIndex((c) => c.id === a.id);+ const next = [...s.audioClips];+ next.splice(idx, 1, left, right);+ return { audioClips: next, selection: { kind: "audio", id: right.id } };+ });+ return;+ }+ }++ const spans = getClipSpans(clips, assets);+ const span = spans.find(+ (sp) => t > sp.start + 0.05 && t < sp.start + sp.len - 0.05+ );+ if (!span) return;+ push();+ const cutAt = span.clip.in + (t - span.start);+ const left: VideoClip = { ...span.clip, out: cutAt };+ const right: VideoClip = { ...span.clip, id: uid(), in: cutAt };+ set((s) => {+ const idx = s.clips.findIndex((c) => c.id === span.clip.id);+ const next = [...s.clips];+ next.splice(idx, 1, left, right);+ return { clips: next, selection: { kind: "clip", id: right.id } };+ });+ },++ deleteSelection: () => {+ const sel = get().selection;+ if (!sel) return;+ push();+ set((s) => ({+ clips: sel.kind === "clip" ? s.clips.filter((c) => c.id !== sel.id) : s.clips,+ audioClips:+ sel.kind === "audio"+ ? s.audioClips.filter((c) => c.id !== sel.id)+ : s.audioClips,+ overlays:+ sel.kind === "text"+ ? s.overlays.filter((o) => o.id !== sel.id)+ : s.overlays,+ selection: null,+ }));+ },++ select: (sel) => set({ selection: sel }),++ seek: (t) => {+ const total = totalDuration(get().clips);+ set({ currentTime: Math.max(0, Math.min(total, t)) });+ },++ setPlaying: (p) => set({ playing: p }),+ setSkimTime: (t) => {+ if (get().skimTime !== t) set({ skimTime: t });+ },+ setPublish: (patch) => set((s) => ({ publish: { ...s.publish, ...patch } })),++ generateSubtitles: async () => {+ const s = get();+ if (!s.projectId || s.subtitleStatus === "running") return;+ const projectId = s.projectId;+ const spans = getClipSpans(s.clips, s.assets);+ if (spans.length === 0) {+ set({ subtitleStatus: "error", subtitleError: "Add a video to the timeline first." });+ return;+ }+ const duration = totalDuration(s.clips);+ const assetById = new Map(s.assets.map((a) => [a.id, a]));+ const spec = {+ duration,+ locale: s.subtitles.locale ?? "en-US",+ clips: spans.map((sp) => ({+ file: sp.asset.fileName,+ in: sp.clip.in,+ out: sp.clip.out,+ muted: sp.clip.muted,+ })),+ audio: s.audioClips+ .filter((a) => a.start < duration && assetById.has(a.assetId))+ .map((a) => ({+ file: assetById.get(a.assetId)!.fileName,+ in: a.in,+ out: a.out,+ start: a.start,+ volume: a.volume,+ })),+ };+ set({ subtitleStatus: "running", subtitleError: null });+ try {+ const res = await fetch(`/api/projects/${projectId}/transcribe`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(spec),+ });+ const body = (await res.json()) as { id?: string; error?: string };+ if (!res.ok || !body.id) throw new Error(body.error ?? "Transcription failed to start.");+ for (;;) {+ await new Promise((r) => setTimeout(r, 600));+ if (get().projectId !== projectId) return; // switched projects mid-run+ const st = await fetch(`/api/projects/${projectId}/transcribe?job=${body.id}`);+ if (!st.ok) throw new Error("The transcription job was lost — try again.");+ const status = (await st.json()) as {+ status: string;+ error?: string;+ cues?: SubtitleCue[];+ };+ if (status.status === "error") throw new Error(status.error ?? "Transcription failed.");+ if (status.status === "done") {+ if (get().projectId !== projectId) return;+ const cues = status.cues ?? [];+ if (cues.length === 0) {+ // No speech in the audio — leave the video untouched.+ set((cur) => ({+ subtitles: { ...cur.subtitles, cues: [], generatedAt: Date.now() },+ subtitleStatus: "empty",+ }));+ return;+ }+ push();+ set((cur) => ({+ subtitles: { ...cur.subtitles, cues, generatedAt: Date.now() },+ subtitleStatus: "ready",+ }));+ return;+ }+ }+ } catch (err) {+ if (get().projectId !== projectId) return;+ set({+ subtitleStatus: "error",+ subtitleError: err instanceof Error ? err.message : String(err),+ });+ }+ },++ setSubtitlesView: (patch) =>+ set((s) => ({ subtitles: { ...s.subtitles, ...patch } })),++ setCueText: (id, text) => {+ const trimmed = text.replace(/\s+/g, " ").trim();+ const cue = get().subtitles.cues.find((c) => c.id === id);+ if (!cue || cue.text === trimmed) return;+ push();+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: trimmed+ ? s.subtitles.cues.map((c) =>+ // Hand-edited text no longer matches the word timings.+ c.id === id ? { ...c, text: trimmed, words: undefined } : c+ )+ : s.subtitles.cues.filter((c) => c.id !== id),+ },+ }));+ },++ splitCue: (id, charOffset) => {+ const s = get();+ const cue = s.subtitles.cues.find((c) => c.id === id);+ if (!cue) return;+ const before = cue.text.slice(0, charOffset).trim();+ const after = cue.text.slice(charOffset).trim();+ if (!before || !after) return;+ let leftEnd: number;+ let rightStart: number;+ let leftWords: SubtitleCue["words"];+ let rightWords: SubtitleCue["words"];+ if (cue.words && cue.words.length > 1) {+ // Word timings are intact: split on the word under the caret so both+ // halves keep real timestamps.+ let n = 0;+ let idx = cue.words.length - 1;+ for (let i = 0; i < cue.words.length; i++) {+ n += cue.words[i].w.length + 1;+ if (charOffset < n) {+ idx = Math.max(1, i + 1);+ break;+ }+ }+ leftWords = cue.words.slice(0, idx);+ rightWords = cue.words.slice(idx);+ if (rightWords.length === 0) return;+ leftEnd = leftWords[leftWords.length - 1].t1;+ rightStart = rightWords[0].t0;+ } else {+ const t = cue.start + (cue.end - cue.start) * (charOffset / Math.max(1, cue.text.length));+ leftEnd = rightStart = Math.round(t * 100) / 100;+ }+ push();+ const left: SubtitleCue = {+ ...cue,+ end: leftEnd,+ text: leftWords ? leftWords.map((w) => w.w).join(" ") : before,+ words: leftWords,+ };+ const right: SubtitleCue = {+ id: uid(),+ start: rightStart,+ end: cue.end,+ text: rightWords ? rightWords.map((w) => w.w).join(" ") : after,+ words: rightWords,+ };+ set((cur) => ({+ subtitles: {+ ...cur.subtitles,+ cues: cur.subtitles.cues.flatMap((c) => (c.id === id ? [left, right] : [c])),+ },+ }));+ },++ mergeCueIntoPrev: (id) => {+ const cues = get().subtitles.cues;+ const i = cues.findIndex((c) => c.id === id);+ if (i <= 0) return;+ push();+ const prev = cues[i - 1];+ const cue = cues[i];+ const merged: SubtitleCue = {+ ...prev,+ end: Math.max(prev.end, cue.end),+ text: `${prev.text} ${cue.text}`.replace(/\s+/g, " ").trim(),+ words: prev.words && cue.words ? [...prev.words, ...cue.words] : undefined,+ };+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.flatMap((c) =>+ c.id === prev.id ? [merged] : c.id === id ? [] : [c]+ ),+ },+ }));+ },++ deleteCue: (id) => {+ if (!get().subtitles.cues.some((c) => c.id === id)) return;+ push();+ set((s) => ({+ subtitles: { ...s.subtitles, cues: s.subtitles.cues.filter((c) => c.id !== id) },+ }));+ },++ updateCueTransient: (id, patch) =>+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: s.subtitles.cues.map((c) => (c.id === id ? { ...c, ...patch } : c)),+ },+ })),++ sortCues: () =>+ set((s) => ({+ subtitles: {+ ...s.subtitles,+ cues: [...s.subtitles.cues].sort((a, b) => a.start - b.start),+ },+ })),+ setPxPerSec: (v) => {+ const pxPerSec = Math.max(12, Math.min(800, v));+ set({ pxPerSec });+ const id = get().projectId;+ if (id) saveUiState(id, { pxPerSec: Math.round(pxPerSec * 100) / 100 });+ },+ setTimelineH: (h) => {+ const timelineH = Math.round(Math.max(TIMELINE_H_MIN, Math.min(TIMELINE_H_MAX, h)));+ set({ timelineH });+ const id = get().projectId;+ if (id) saveUiState(id, { timelineH });+ },+ setExportOpen: (v) => set({ exportOpen: v }),+ setDropActive: (v) => set({ dropActive: v }),+ setAiOpen: (v) => {+ set({ aiOpen: v });+ try {+ localStorage.setItem("cut-ai-open", v ? "1" : "0");+ } catch {+ // View preference only.+ }+ },++ copySelection: () => {+ const s = get();+ const sel = s.selection;+ if (!sel) return false;+ if (sel.kind === "clip") {+ const c = s.clips.find((x) => x.id === sel.id);+ if (!c) return false;+ clipboard = { kind: "clip", item: { ...c } };+ } else if (sel.kind === "audio") {+ const a = s.audioClips.find((x) => x.id === sel.id);+ if (!a) return false;+ clipboard = { kind: "audio", item: { ...a } };+ } else {+ const o = s.overlays.find((x) => x.id === sel.id);+ if (!o) return false;+ clipboard = { kind: "text", item: { ...o } };+ }+ return true;+ },++ paste: () => {+ const cb = clipboard;+ if (!cb) return false;+ const s = get();+ // The copied item's media must still exist in this project.+ if (+ (cb.kind === "clip" || cb.kind === "audio") &&+ !s.assets.some((a) => a.id === cb.item.assetId)+ )+ return false;+ push();+ const t = s.currentTime;+ if (cb.kind === "clip") {+ // Insert after the clip under the playhead (end of track otherwise).+ const spans = getClipSpans(s.clips, s.assets);+ let index = s.clips.length;+ for (let i = 0; i < spans.length; i++) {+ if (t < spans[i].start + spans[i].len) {+ index = i + 1;+ break;+ }+ }+ const clip: VideoClip = { ...cb.item, id: uid() };+ set((cur) => ({+ clips: [...cur.clips.slice(0, index), clip, ...cur.clips.slice(index)],+ selection: { kind: "clip", id: clip.id },+ }));+ } else if (cb.kind === "audio") {+ const item: AudioClip = { ...cb.item, id: uid(), start: Math.max(0, t) };+ set((cur) => ({+ audioClips: [...cur.audioClips, item],+ selection: { kind: "audio", id: item.id },+ }));+ } else {+ const len = Math.max(0.2, cb.item.end - cb.item.start);+ const item: TextOverlay = { ...cb.item, id: uid(), start: Math.max(0, t), end: Math.max(0, t) + len };+ set((cur) => ({+ overlays: [...cur.overlays, item],+ selection: { kind: "text", id: item.id },+ }));+ }+ return true;+ },++ undo: () => {+ flush(); // commit any uncommitted edit before stepping back+ const prev = history.pop();+ if (!prev) return;+ future.push(snapshot());+ set({ ...prev, selection: null });+ },++ redo: () => {+ flush();+ const next = future.pop();+ if (!next) return;+ history.push(snapshot());+ if (history.length > HISTORY_CAP) history.shift();+ set({ ...next, selection: null });+ },+ };+});++// Track real edits to the persistable doc so a deferred checkpoint (see push)+// knows whether an edit actually happened between capture and commit.+useEditor.subscribe((s, prev) => {+ if (+ s.clips !== prev.clips ||+ s.audioClips !== prev.audioClips ||+ s.overlays !== prev.overlays ||+ s.subtitles !== prev.subtitles+ )+ docSeq++;+});++/** The persistable slice of the editor state, for autosave. */+export function serializeDoc(s: {+ projectName: string;+ assets: MediaAsset[];+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: TextOverlay[];+ aspect: Aspect;+ publish: { caption: string; tags: string; soundTitle: string; handle: string };+ subtitles: SubtitlesBlock;+}): Partial<ProjectDoc> {+ const assets: StoredAsset[] = s.assets.map(+ ({ id, fileName, name, type, duration, width, height }) => ({+ id,+ fileName,+ name,+ type,+ duration,+ ...(width !== undefined ? { width } : {}),+ ...(height !== undefined ? { height } : {}),+ })+ );+ return {+ name: s.projectName,+ assets,+ clips: s.clips,+ audioClips: s.audioClips,+ overlays: s.overlays,+ aspect: s.aspect,+ subtitles: s.subtitles,+ publish: { ...s.publish },+ };+}++export function clipLen(c: VideoClip | AudioClip) {+ return Math.max(MIN_LEN, c.out - c.in);+}++export function getClipSpans(+ clips: VideoClip[],+ assets: MediaAsset[]+): ClipSpan[] {+ // Map lookup, not a per-clip assets.find — this runs every playback frame.+ const byId = new Map(assets.map((a) => [a.id, a]));+ const spans: ClipSpan[] = [];+ let t = 0;+ for (const clip of clips) {+ const asset = byId.get(clip.assetId);+ if (!asset) continue;+ const len = clipLen(clip);+ spans.push({ clip, asset, start: t, len });+ t += len;+ }+ return spans;+}++export function totalDuration(clips: VideoClip[]) {+ return clips.reduce((sum, c) => sum + clipLen(c), 0);+}++export const useTotalDuration = () => useEditor((s) => totalDuration(s.clips));diff --git a/site/src/cut/lib/subtitles.ts b/site/src/cut/lib/subtitles.tsnew file mode 100644index 00000000..75ff4d19--- /dev/null+++ b/site/src/cut/lib/subtitles.ts@@ -0,0 +1,42 @@+import { formatTime } from "./time";+import type { SubtitleCue, TextOverlay } from "./types";++/** Caption look shared by the preview layer and the export burn-in —+ * TikTok-style bold white on a translucent plate, low center. */+export const SUB_STYLE = {+ x: 0.5,+ y: 0.8,+ size: 42,+ font: "sf",+ weight: 700,+ color: "#FFFFFF",+ shadow: true,+ plate: true,+} as const;++/** Balance a caption onto up to two lines so it never overflows the frame. */+export function wrapCaption(text: string): string {+ const t = text.trim().replace(/\s+/g, " ");+ if (t.length <= 26) return t;+ const mid = t.length / 2;+ let best = -1;+ for (let i = t.indexOf(" "); i !== -1; i = t.indexOf(" ", i + 1)) {+ if (best === -1 || Math.abs(i - mid) < Math.abs(best - mid)) best = i;+ }+ return best === -1 ? t : t.slice(0, best) + "\n" + t.slice(best + 1);+}++/** A cue as a synthetic overlay, so captions ride the title pipeline. */+export function cueOverlay(cue: SubtitleCue): TextOverlay {+ return { id: `sub-${cue.id}`, text: wrapCaption(cue.text), start: cue.start, end: cue.end, ...SUB_STYLE };+}++/** The cue under a given time, if any. */+export function cueAt(cues: SubtitleCue[], t: number): SubtitleCue | undefined {+ return cues.find((c) => t >= c.start && t < c.end);+}++/** Compact panel timestamp (m:ss.s) — the same convention as the transport+ * readout, so a cue and the playhead never show different times for one+ * instant, and a rounded 59.97s can't render as an invalid ":60". */+export const fmtCueTime = formatTime;diff --git a/site/src/cut/lib/textRender.ts b/site/src/cut/lib/textRender.tsnew file mode 100644index 00000000..52521d2b--- /dev/null+++ b/site/src/cut/lib/textRender.ts@@ -0,0 +1,73 @@+"use client";++import { fontStack, type TextOverlay } from "./types";++export const LINE_HEIGHT = 1.25;+export const PLATE_PAD_X = 0.55; // em+export const PLATE_PAD_Y = 0.3; // em+export const PLATE_RADIUS = 0.32; // em+export const PLATE_FILL = "rgba(0, 0, 0, 0.55)";+export const SHADOW = { color: "rgba(0, 0, 0, 0.65)", blur: 14, offsetY: 2 };++/**+ * Render an overlay to a transparent full-frame PNG at the export resolution.+ * Uses the same font stacks and metrics as the DOM preview so the export+ * matches what the user sees.+ */+export async function renderOverlayPng(+ overlay: TextOverlay,+ width: number,+ height: number+): Promise<Blob> {+ // Overlay sizes are frame pixels with a 1080 design short side (9:16 is+ // 1080 wide, 16:9 is 1080 tall), so scaling by the short side keeps text+ // the same visual size in either aspect and at any export resolution.+ const scale = Math.min(width, height) / 1080;+ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d")!;++ const fpx = overlay.size * scale;+ ctx.font = `${overlay.weight} ${fpx}px ${fontStack(overlay.font)}`;+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";++ const lines = overlay.text.split("\n");+ const lineH = fpx * LINE_HEIGHT;+ const totalH = lines.length * lineH;+ const cx = overlay.x * width;+ const cy = overlay.y * height;++ if (overlay.plate) {+ const maxW = Math.max(...lines.map((l) => ctx.measureText(l).width), 1);+ const padX = PLATE_PAD_X * fpx;+ const padY = PLATE_PAD_Y * fpx;+ const r = (overlay.plateRadius ?? PLATE_RADIUS) * fpx;+ const w = maxW + padX * 2;+ const h = totalH + padY * 2;+ ctx.fillStyle = PLATE_FILL;+ ctx.beginPath();+ ctx.roundRect(cx - w / 2, cy - h / 2, w, h, r);+ ctx.fill();+ }++ if (overlay.shadow) {+ ctx.shadowColor = SHADOW.color;+ ctx.shadowBlur = SHADOW.blur * scale;+ ctx.shadowOffsetY = SHADOW.offsetY * scale;+ }++ ctx.fillStyle = overlay.color;+ lines.forEach((line, i) => {+ const y = cy - totalH / 2 + lineH * (i + 0.5);+ ctx.fillText(line, cx, y);+ });++ return new Promise((resolve, reject) =>+ canvas.toBlob(+ (b) => (b ? resolve(b) : reject(new Error("Could not render text overlay."))),+ "image/png"+ )+ );+}diff --git a/site/src/cut/lib/time.ts b/site/src/cut/lib/time.tsnew file mode 100644index 00000000..29c4168e--- /dev/null+++ b/site/src/cut/lib/time.ts@@ -0,0 +1,19 @@+/** 63.4 -> "1:03.4" | 8.02 -> "0:08.0" */+export function formatTime(t: number) {+ const clamped = Math.max(0, t);+ const m = Math.floor(clamped / 60);+ const s = clamped - m * 60;+ const whole = Math.floor(s);+ const tenth = Math.floor((s - whole) * 10);+ return `${m}:${String(whole).padStart(2, "0")}.${tenth}`;+}++/** Full timecode for the transport readout: "0:14.23" (hundredths). */+export function formatTimecode(t: number) {+ const clamped = Math.max(0, t);+ const m = Math.floor(clamped / 60);+ const s = clamped - m * 60;+ const whole = Math.floor(s);+ const hund = Math.floor((s - whole) * 100);+ return `${m}:${String(whole).padStart(2, "0")}.${String(hund).padStart(2, "0")}`;+}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsnew file mode 100644index 00000000..32e14353--- /dev/null+++ b/site/src/cut/lib/types.ts@@ -0,0 +1,181 @@+export type AssetType = "video" | "audio";++/** Project output frame. Vertical (TikTok/Reels) or widescreen (YouTube). */+export type Aspect = "9:16" | "16:9";++export const FRAME: Record<Aspect, { w: number; h: number }> = {+ "9:16": { w: 1080, h: 1920 },+ "16:9": { w: 1920, h: 1080 },+};++export const ASPECT_LABEL: Record<Aspect, string> = {+ "9:16": "Vertical · 9:16",+ "16:9": "Widescreen · 16:9",+};++/** Asset fields persisted in project.json. */+export interface StoredAsset {+ id: string;+ fileName: string; // file inside the project's media/ folder+ name: string; // original display name+ type: AssetType;+ duration: number; // seconds+ width?: number;+ height?: number;+}++/** Runtime asset: stored fields plus derived/browser-only data. */+export interface MediaAsset extends StoredAsset {+ url: string; // /api/projects/<id>/media/<fileName>+ /** Filmstrip frames (video only), evenly spaced every `thumbStep` seconds. */+ thumbs?: string[];+ thumbStep?: number;+ /** Normalized waveform peaks 0..1 (audio only). */+ peaks?: number[];+}++/** A clip on the magnetic video track. Order in the array is timeline order. */+export interface VideoClip {+ id: string;+ assetId: string;+ in: number; // trim-in inside the source, seconds+ out: number; // trim-out inside the source, seconds+ muted: boolean;+ /** How the clip meets the 9:16 frame: letterboxed ("fit", default) or+ * scaled to cover it ("fill", cropping the overflow). */+ fit?: "fit" | "fill";+ /** Crop-window pan in fill mode, -1..1 per axis (0 = centered): which part+ * of the oversized video stays visible. */+ panX?: number;+ panY?: number;+}++/** A clip on the free-form soundtrack track. */+export interface AudioClip {+ id: string;+ assetId: string;+ start: number; // timeline position, seconds+ in: number;+ out: number;+ volume: number; // 0..1.5+ fadeIn?: number; // seconds, ramp up from the clip start+ fadeOut?: number; // seconds, ramp down into the clip end+}++export type FontId = "sf" | "serif" | "rounded" | "mono" | "impact";++export interface FontDef {+ id: FontId;+ label: string;+ stack: string;+}++export const FONTS: FontDef[] = [+ { id: "sf", label: "SF Pro", stack: '-apple-system, "SF Pro Display", "Helvetica Neue", Helvetica, Arial, sans-serif' },+ { id: "serif", label: "New York", stack: '"New York", ui-serif, Georgia, "Times New Roman", serif' },+ { id: "rounded", label: "Rounded", stack: 'ui-rounded, "SF Pro Rounded", "Arial Rounded MT Bold", "Helvetica Neue", sans-serif' },+ { id: "mono", label: "Mono", stack: 'ui-monospace, "SF Mono", Menlo, "Courier New", monospace' },+ { id: "impact", label: "Impact", stack: 'Impact, "Arial Black", "Helvetica Neue", sans-serif' },+];++export const fontStack = (id: FontId) =>+ FONTS.find((f) => f.id === id)?.stack ?? FONTS[0].stack;++export interface TextOverlay {+ id: string;+ text: string;+ start: number; // timeline seconds+ end: number;+ x: number; // center, fraction of frame width 0..1+ y: number; // center, fraction of frame height 0..1+ size: number; // px at a 1080-wide frame+ font: FontId;+ weight: 400 | 700;+ color: string;+ shadow: boolean;+ plate: boolean; // translucent rounded plate behind the text+ plateRadius?: number; // plate corner radius in em (default PLATE_RADIUS)+}++/** One subtitle caption, timed against the timeline (not the source files). */+export interface SubtitleCue {+ id: string;+ start: number; // timeline seconds+ end: number;+ text: string;+ /** Word timings from the transcriber; dropped once the text is hand-edited+ * (they no longer match), which falls back to proportional splitting. */+ words?: { t0: number; t1: number; w: string }[];+}++export interface SubtitlesBlock {+ cues: SubtitleCue[];+ /** Render captions on the preview and burn them into exports. */+ showOnVideo: boolean;+ /** Show the cue track on the timeline. */+ showOnTimeline: boolean;+ locale?: string;+ generatedAt?: number;+}++export const emptySubtitles = (): SubtitlesBlock => ({+ cues: [],+ showOnVideo: true,+ showOnTimeline: true,+});++export type Selection =+ | { kind: "clip"; id: string }+ | { kind: "audio"; id: string }+ | { kind: "text"; id: string }+ | null;++export interface ClipSpan {+ clip: VideoClip;+ asset: MediaAsset;+ start: number; // timeline start+ len: number;+}++/** The document persisted as project.json inside each project folder. */+export interface ProjectDoc {+ version: 1;+ name: string;+ createdAt: number;+ updatedAt: number;+ assets: StoredAsset[];+ clips: VideoClip[];+ audioClips: AudioClip[];+ overlays: TextOverlay[];+ /** Output frame; absent in older projects (which are all 9:16). */+ aspect?: Aspect;+ /** Auto-generated (then hand-edited) subtitles. */+ subtitles?: SubtitlesBlock;+ /** Legacy per-project view metadata — view state now lives in IndexedDB;+ * still read on open so older project.json files keep their zoom. */+ ui?: {+ pxPerSec?: number;+ };+ /** TikTok publishing metadata, prepared here and copied over on upload. */+ publish?: {+ caption?: string;+ tags?: string;+ soundTitle?: string;+ handle?: string;+ };+}++export interface ProjectSummary {+ id: string;+ name: string;+ createdAt: number;+ updatedAt: number;+ duration: number;+ clipCount: number;+ assetCount: number;+ /** Media file used for the card poster / hover preview. */+ previewFile?: string;+}++export const mediaUrl = (projectId: string, fileName: string) =>+ `/api/projects/${projectId}/media/${encodeURIComponent(fileName)}`;diff --git a/site/src/cut/lib/uiState.ts b/site/src/cut/lib/uiState.tsnew file mode 100644index 00000000..ebe2b6fe--- /dev/null+++ b/site/src/cut/lib/uiState.ts@@ -0,0 +1,65 @@+"use client";++/**+ * Per-project view state (zoom level, timeline panel height) — how this+ * browser looks at a project, not part of the cut. Stored in IndexedDB+ * keyed by project id; project.json only carries real content.+ */+export interface ProjectUiState {+ pxPerSec?: number;+ timelineH?: number;+}++const DB_NAME = "cut";+const STORE = "project-ui";++function openDb(): Promise<IDBDatabase> {+ return new Promise((resolve, reject) => {+ const req = indexedDB.open(DB_NAME, 1);+ req.onupgradeneeded = () => {+ if (!req.result.objectStoreNames.contains(STORE)) req.result.createObjectStore(STORE);+ };+ req.onsuccess = () => resolve(req.result);+ req.onerror = () => reject(req.error);+ });+}++export async function loadUiState(projectId: string): Promise<ProjectUiState> {+ try {+ const db = await openDb();+ return await new Promise((resolve) => {+ const req = db.transaction(STORE).objectStore(STORE).get(projectId);+ req.onsuccess = () => resolve((req.result as ProjectUiState) ?? {});+ req.onerror = () => resolve({});+ });+ } catch {+ return {}; // e.g. private-mode quota — fall back to defaults+ }+}++// Writes are debounced and merged so slider drags don't hammer the store.+let pending: { projectId: string; patch: ProjectUiState } | null = null;+let timer: ReturnType<typeof setTimeout> | null = null;++async function flush() {+ const job = pending;+ pending = null;+ if (!job) return;+ try {+ const db = await openDb();+ const tx = db.transaction(STORE, "readwrite");+ const store = tx.objectStore(STORE);+ const req = store.get(job.projectId);+ req.onsuccess = () =>+ store.put({ ...((req.result as ProjectUiState) ?? {}), ...job.patch }, job.projectId);+ } catch {+ // View state is best-effort; losing it only resets zoom/height defaults.+ }+}++export function saveUiState(projectId: string, patch: ProjectUiState) {+ if (pending && pending.projectId !== projectId) void flush();+ pending = { projectId, patch: { ...(pending?.patch ?? {}), ...patch } };+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => void flush(), 300);+}diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.tsnew file mode 100644index 00000000..0631f5a4--- /dev/null+++ b/site/src/cut/server/ai/bridge.ts@@ -0,0 +1,94 @@+/**+ * Bridge between a running chat request and the browser.+ *+ * The chat route holds an open UI-message stream per session. When a+ * provider calls an MCP tool, the proxy POSTs here; we write the tool call+ * into the chat stream (the browser executes it against the editor store+ * and POSTs the result back), then hand the result to the provider.+ */++export interface UIChunkWriter {+ write: (chunk: Record<string, unknown>) => void;+}++interface Waiter {+ resolve: (r: { output?: unknown; errorText?: string }) => void;+ timer: ReturnType<typeof setTimeout>;+}++interface Session {+ writer: UIChunkWriter;+ waiters: Map<string, Waiter>;+}++// Survives dev-server module reloads.+const g = globalThis as unknown as { __veditorAiSessions?: Map<string, Session> };+const sessions = (g.__veditorAiSessions ??= new Map<string, Session>());++export function registerSession(key: string, writer: UIChunkWriter) {+ sessions.set(key, { writer, waiters: new Map() });+}++export function unregisterSession(key: string) {+ const s = sessions.get(key);+ if (s) {+ for (const w of s.waiters.values()) {+ clearTimeout(w.timer);+ w.resolve({ errorText: "The chat request ended before the tool finished." });+ }+ }+ sessions.delete(key);+}++const TOOL_TIMEOUT_MS = 120_000; // subtitles generation can take a while++/**+ * Forward a tool call to the browser via the chat stream and wait for the+ * result. Returns { output } or { errorText }.+ */+export function callBrowserTool(+ sessionKey: string,+ toolName: string,+ input: unknown+): Promise<{ output?: unknown; errorText?: string }> {+ const session = sessions.get(sessionKey);+ if (!session) {+ return Promise.resolve({ errorText: "No live editor session for this chat." });+ }+ const toolCallId = crypto.randomUUID().slice(0, 12);+ session.writer.write({ type: "tool-input-available", toolCallId, toolName, input });+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ session.waiters.delete(toolCallId);+ const errorText = `The editor did not answer the ${toolName} call in time.`;+ session.writer.write({ type: "tool-output-error", toolCallId, errorText });+ resolve({ errorText });+ }, TOOL_TIMEOUT_MS);+ session.waiters.set(toolCallId, {+ timer,+ resolve: (r) => {+ if (r.errorText !== undefined) {+ session.writer.write({ type: "tool-output-error", toolCallId, errorText: r.errorText });+ } else {+ session.writer.write({ type: "tool-output-available", toolCallId, output: r.output ?? null });+ }+ resolve(r);+ },+ });+ });+}++/** Called by /api/ai/tool-result when the browser finishes a tool. */+export function resolveBrowserTool(+ sessionKey: string,+ toolCallId: string,+ result: { output?: unknown; errorText?: string }+): boolean {+ const session = sessions.get(sessionKey);+ const waiter = session?.waiters.get(toolCallId);+ if (!session || !waiter) return false;+ session.waiters.delete(toolCallId);+ clearTimeout(waiter.timer);+ waiter.resolve(result);+ return true;+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsnew file mode 100644index 00000000..cef42113--- /dev/null+++ b/site/src/cut/server/ai/catalog.ts@@ -0,0 +1,301 @@+/**+ * The assistant's tool catalog and skills library.+ *+ * Tools are defined once here (JSON Schema) and exposed to both providers+ * through the stdio MCP proxy. Every tool except the `server: true` ones is+ * executed in the browser against the editor store, so the assistant edits+ * the exact same state the user sees.+ */++export interface AiToolDef {+ name: string;+ description: string;+ inputSchema: Record<string, unknown>;+ /** Handled directly by the server (no browser round-trip). */+ server?: boolean;+}++const obj = (+ properties: Record<string, unknown>,+ required: string[] = []+): Record<string, unknown> => ({+ type: "object",+ properties,+ required,+ additionalProperties: false,+});++const num = (description: string) => ({ type: "number", description });+const str = (description: string) => ({ type: "string", description });+const bool = (description: string) => ({ type: "boolean", description });++export const AI_TOOLS: AiToolDef[] = [+ {+ name: "get_state",+ description:+ "Read the full current editor state: clips, soundtrack, titles, subtitles, selection, playhead, view settings, publish metadata. Use this whenever the context snapshot is not enough or might be stale.",+ inputSchema: obj({}),+ },+ {+ name: "capture_frame",+ description:+ "Capture what the video preview currently shows (at the playhead) as an image, so you can see the frame, titles, and captions exactly as rendered.",+ inputSchema: obj({}),+ },+ {+ name: "seek",+ description: "Move the playhead to a time (seconds, clamped to the cut).",+ inputSchema: obj({ t: num("Timeline time in seconds") }, ["t"]),+ },+ {+ name: "set_playing",+ description: "Start or stop playback.",+ inputSchema: obj({ playing: bool("true to play, false to pause") }, ["playing"]),+ },+ {+ name: "select",+ description:+ "Select a clip, soundtrack clip, or title (or clear the selection). Selection drives the inspector panel.",+ inputSchema: obj({+ kind: { type: "string", enum: ["clip", "audio", "text", "none"], description: "What to select" },+ id: str("The item id (omit for kind=none)"),+ }, ["kind"]),+ },+ {+ name: "split_at",+ description:+ "Split the video (and a selected soundtrack clip) at a time, like pressing S. Omit t to split at the playhead.",+ inputSchema: obj({ t: num("Timeline seconds to cut at (optional)") }),+ },+ {+ name: "move_clip",+ description: "Reorder a video clip to a new index on the magnetic track.",+ inputSchema: obj({ clipId: str("Video clip id"), toIndex: num("Target index, 0-based") }, ["clipId", "toIndex"]),+ },+ {+ name: "trim_clip",+ description:+ "Set a video clip's trim points inside its source media (seconds). Changing `in` hides the leading part; `out` the trailing part.",+ inputSchema: obj({ clipId: str("Video clip id"), in: num("New in point (optional)"), out: num("New out point (optional)") }, ["clipId"]),+ },+ {+ name: "set_clip_muted",+ description: "Mute or unmute a video clip's own audio.",+ inputSchema: obj({ clipId: str("Video clip id"), muted: bool("true to mute") }, ["clipId", "muted"]),+ },+ {+ name: "detach_audio",+ description:+ "iMovie-style Detach Audio: lift a clip's sound onto the soundtrack track (mutes the clip) so it can be edited independently. Select the clip first or pass its id.",+ inputSchema: obj({ clipId: str("Video clip id (optional if one is selected)") }),+ },+ {+ name: "delete_item",+ description: "Delete a video clip, soundtrack clip, or title by id.",+ inputSchema: obj({+ kind: { type: "string", enum: ["clip", "audio", "text"], description: "Item kind" },+ id: str("Item id"),+ }, ["kind", "id"]),+ },+ {+ name: "add_title",+ description:+ "Add a text title overlay. Position is the text center as a fraction of the frame (x,y in 0..1; y=0.42 is the default band). Size is px at 1080-wide.",+ inputSchema: obj({+ text: str("The title text (\\n for line breaks)"),+ start: num("Start time s (default: playhead)"),+ end: num("End time s (default: start+3)"),+ x: num("Center x 0..1 (default 0.5)"),+ y: num("Center y 0..1 (default 0.42)"),+ size: num("Font size px at 1080w (default 88)"),+ color: str("CSS color (default #FFFFFF)"),+ font: { type: "string", enum: ["sf", "serif", "rounded", "mono", "impact"], description: "Font family id" },+ weight: { type: "number", enum: [400, 700], description: "Font weight" },+ shadow: bool("Drop shadow (default true)"),+ plate: bool("Translucent plate behind text (default false)"),+ }, ["text"]),+ },+ {+ name: "update_title",+ description:+ "Update any properties of an existing title overlay (text, timing, position, size, font, weight, color, shadow, plate). This is the tool for 'make this text better' requests — pass the overlay id from the selection or state.",+ inputSchema: obj({+ id: str("Overlay id"),+ text: str("New text"),+ start: num("Start s"),+ end: num("End s"),+ x: num("Center x 0..1"),+ y: num("Center y 0..1"),+ size: num("Font size px at 1080w"),+ color: str("CSS color"),+ font: { type: "string", enum: ["sf", "serif", "rounded", "mono", "impact"], description: "Font family id" },+ weight: { type: "number", enum: [400, 700], description: "Font weight" },+ shadow: bool("Drop shadow"),+ plate: bool("Backdrop plate"),+ }, ["id"]),+ },+ {+ name: "update_audio",+ description:+ "Update a soundtrack clip: volume (0..1.5), fadeIn/fadeOut seconds, start position, or in/out trim.",+ inputSchema: obj({+ id: str("Soundtrack clip id"),+ volume: num("0..1.5"),+ fadeIn: num("Fade-in seconds"),+ fadeOut: num("Fade-out seconds"),+ start: num("Timeline start s"),+ in: num("Source in s"),+ out: num("Source out s"),+ }, ["id"]),+ },+ {+ name: "set_framing",+ description:+ "Set how a video clip meets the 9:16 frame: 'fit' letterboxes the whole picture (default), 'fill' scales it to cover the frame and crops the overflow. In fill mode panX/panY (-1..1, 0=centered) choose which part stays visible — e.g. panY=-1 keeps the top.",+ inputSchema: obj({+ clipId: str("Video clip id"),+ mode: { type: "string", enum: ["fit", "fill"], description: "Framing mode" },+ panX: num("Crop pan -1 (left) .. 1 (right), fill mode only"),+ panY: num("Crop pan -1 (top) .. 1 (bottom), fill mode only"),+ }, ["clipId", "mode"]),+ },+ {+ name: "freeze_frame",+ description:+ "Extract the video frame at a time (default: the playhead — what the user is looking at) as a still clip and insert it into the timeline. Default insert position is index 0, making it the first thing viewers see (a cover/hook frame).",+ inputSchema: obj({+ t: num("Timeline time of the frame to grab (default: playhead)"),+ duration: num("Still clip length in seconds, 0.5–10 (default 1)"),+ index: num("Insert position on the video track (default 0 = first)"),+ }),+ },+ {+ name: "subtitles_generate",+ description:+ "Transcribe the cut on-device (Apple speech) and create subtitle captions. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",+ inputSchema: obj({ locale: str("BCP-47 locale like en-US (default en-US)") }),+ },+ {+ name: "subtitles_set_view",+ description: "Toggle subtitles on the video (preview + export burn-in) and/or the timeline cue track.",+ inputSchema: obj({ showOnVideo: bool("Captions on the video"), showOnTimeline: bool("Cue track on the timeline") }),+ },+ {+ name: "update_cue",+ description: "Edit a subtitle cue's text or retime it (start/end seconds).",+ inputSchema: obj({ id: str("Cue id"), text: str("New text"), start: num("Start s"), end: num("End s") }, ["id"]),+ },+ {+ name: "delete_cue",+ description: "Delete a subtitle cue.",+ inputSchema: obj({ id: str("Cue id") }, ["id"]),+ },+ {+ name: "set_publish",+ description:+ "Set the TikTok publish metadata: caption (4,000 char limit incl. tags), tags (space-separated words, # added automatically), soundTitle, handle.",+ inputSchema: obj({+ caption: str("Caption text"),+ tags: str("Space or comma separated tags"),+ soundTitle: str("Sound title"),+ handle: str("Creator handle without @"),+ }),+ },+ {+ name: "set_view",+ description:+ "Adjust the timeline view: zoom (pxPerSec 12..800), fit the whole cut, or panel height (170..600).",+ inputSchema: obj({+ pxPerSec: num("Zoom in px per second"),+ fit: bool("Fit the whole cut to the window"),+ timelineH: num("Timeline panel height px"),+ }),+ },+ {+ name: "undo",+ description: "Undo the last edit (unlimited).",+ inputSchema: obj({}),+ },+ {+ name: "redo",+ description: "Redo the last undone edit.",+ inputSchema: obj({}),+ },+ {+ name: "open_export",+ description:+ "Open the export dialog so the user can render the cut (TikTok 1080p, Quick share 1080p, or Draft 720p). Exporting itself stays a user action.",+ inputSchema: obj({}),+ },+ {+ name: "list_skills",+ description: "List the available skill documents about how this editor works.",+ inputSchema: obj({}),+ server: true,+ },+ {+ name: "read_skill",+ description:+ "Read a skill document (detailed docs for a part of the editor: every setting, where it lives, and how it behaves). Use before working in an unfamiliar area.",+ inputSchema: obj({ name: str("Skill name from list_skills") }, ["name"]),+ server: true,+ },+];++/** Deep documentation the model can pull in on demand. */+export const AI_SKILLS: Record<string, string> = {+ "editor-overview": `# Cut editor overview+Cut is a local, project-based short-video editor. Each project has an output aspect — 9:16 vertical (1080×1920, TikTok/Reels/Shorts) or 16:9 widescreen (1920×1080, YouTube) — switchable from the pill in the top bar; the current one is in editor_state project.aspect. Layout:+- Left icon rail tabs: Media (project files + Exports list), Library (shared reusable assets), Record (camera/mic), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata).+- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.+- Right: the Inspector — its content follows the selection (video clip, soundtrack clip, or title).+- Bottom: the timeline (resizable by dragging its top border). Tracks top-to-bottom: video (magnetic, clips snap end-to-end), soundtrack (free-positioned green clips), titles (purple bars), subtitles (amber cue bars, when enabled).+Everything autosaves to the project folder. Undo/redo is unlimited (⌘Z / ⇧⌘Z).+Times are in seconds on the shared timeline. The playhead is currentTime; a skimmer previews under the mouse without moving the playhead.`,++ "timeline-editing": `# Timeline editing+- Video track is magnetic: clips are ordered by index; there are no gaps. move_clip reorders; total duration = sum of (out-in).+- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.+- split_at cuts the clip under that time into two clips at the exact frame. With a soundtrack clip selected it splits that instead.+- delete_item removes items; the video track closes the gap automatically.+- detach_audio lifts a video clip's sound to the soundtrack track (and mutes the clip) so audio can be cut independently of video.+- freeze_frame grabs one frame (default: the playhead — what the user currently sees) as a still clip and inserts it, by default at index 0 as a cover/hook frame ("make this the first frame"). The still is baked at the project's current aspect with the clip's framing applied; if the user later switches aspect they should capture a fresh one.+- set_framing: per-clip Fit (letterbox) vs Fill (crop to cover the project frame). In Fill, panX/panY position the crop window; the user can also drag the video directly in the preview. The control lives in the Inspector under "Framing" when a video clip is selected. Landscape footage usually wants fill + a pan that keeps the subject.+- The user can copy/paste any selected segment (video, audio, title) with ⌘C/⌘V; pastes land at the playhead.+- Zoom: set_view pxPerSec (12..800) or fit. The timeline panel height: set_view timelineH (170..600).`,++ "titles": `# Titles (text overlays)+Each overlay: text, start/end (seconds visible), x/y center (fractions 0..1 of the project frame), size (frame px; the design short side is 1080), font (sf=SF Pro, serif=New York, rounded, mono, impact), weight (400/700), color (any CSS color), shadow (bool), plate (translucent dark plate behind the text).+Inspector shows these when a title is selected. The color row has fixed swatches, a custom picker, and the last 3 custom colors.+Good TikTok titles: short punchy lines, high contrast (white/yellow + shadow or plate), size 72–110, keep inside the middle 80% of the frame (x 0.1..0.9, y 0.1..0.9), avoid the caption band (y≈0.8) when subtitles are on.+Titles burn into the export exactly as previewed.`,++ "audio-and-subtitles": `# Audio & subtitles+Soundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source. Fades render with ffmpeg afade on export.+Subtitles: subtitles_generate transcribes the current cut fully on-device (Apple speech, macOS 26). Cues are caption-sized (≈38 chars). If no speech exists, no cues are created and nothing renders on the video — never add captions to a speechless video.+Editing: update_cue (text or retime), delete_cue. In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.+subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue track).+Caption style is fixed: bold white SF, translucent plate, bottom-center (y≈0.8).`,++ "publish-and-export": `# Publish & export+Publish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).+Export (open_export): presets Best 1080p CRF19, Quick share 1080p, Draft 720p — H.264 + AAC, 30fps, rendered at the project aspect (9:16 or 16:9), titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place.`,+};++/** System prompt shared by all providers. */+export function systemPrompt(): string {+ return `You are Cut's editing copilot, embedded in a local TikTok video editor. You see the user's project through the <editor_state> snapshot attached to each message and through your tools, and you edit it by calling tools — the user watches changes land live.++Rules:+- Act directly with tools; don't describe steps the user should click through unless they ask how.+- Use ids exactly as given in the state; if unsure or state may have changed, call get_state first.+- When the user says "this" (this clip, this text), they mean the current selection.+- Keep replies short and concrete — one or two sentences about what you did. No headings, no fluff.+- All edits are undoable (unlimited undo), so prefer doing over asking. Only ask when the request is genuinely ambiguous.+- Times are seconds. The frame is the project's aspect: 1080×1920 (9:16) or 1920×1080 (16:9) — see project.aspect in editor_state.+- Read list_skills / read_skill before working in an area you're unsure about — they document every setting.+- Never add subtitles to a video without speech; never invent transcript content.+- capture_frame shows you the actual rendered frame when visual judgment matters.`;+}++export const AI_SKILL_INDEX = Object.keys(AI_SKILLS);diff --git a/site/src/cut/server/ai/mcp-proxy.mjs b/site/src/cut/server/ai/mcp-proxy.mjsnew file mode 100644index 00000000..ba0f0bd4--- /dev/null+++ b/site/src/cut/server/ai/mcp-proxy.mjs@@ -0,0 +1,77 @@+#!/usr/bin/env node+/**+ * Minimal stdio MCP server that proxies Cut's editor tools.+ *+ * Spawned by whichever model harness is chatting (Claude Agent SDK or the+ * Codex CLI). Speaks newline-delimited JSON-RPC on stdio and forwards+ * tools/list + tools/call to the local Next server, which routes execution+ * into the user's open editor tab.+ *+ * usage: node mcp-proxy.mjs <baseUrl> <sessionKey>+ */++const [, , BASE = "http://localhost:3000", SESSION = ""] = process.argv;++let buffer = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (chunk) => {+ buffer += chunk;+ let nl;+ while ((nl = buffer.indexOf("\n")) !== -1) {+ const line = buffer.slice(0, nl).trim();+ buffer = buffer.slice(nl + 1);+ if (line) void handle(line);+ }+});+process.stdin.on("end", () => process.exit(0));++function send(msg) {+ process.stdout.write(JSON.stringify(msg) + "\n");+}++async function handle(line) {+ let req;+ try {+ req = JSON.parse(line);+ } catch {+ return;+ }+ const { id, method, params } = req;+ const reply = (result) => id !== undefined && send({ jsonrpc: "2.0", id, result });+ const fail = (message) =>+ id !== undefined && send({ jsonrpc: "2.0", id, error: { code: -32000, message } });++ try {+ if (method === "initialize") {+ reply({+ protocolVersion: params?.protocolVersion ?? "2024-11-05",+ capabilities: { tools: {} },+ serverInfo: { name: "cut", version: "1.0.0" },+ });+ } else if (method === "notifications/initialized" || method === "notifications/cancelled") {+ // notifications: no response+ } else if (method === "ping") {+ reply({});+ } else if (method === "tools/list") {+ const res = await fetch(`${BASE}/api/ai/proxy?type=catalog`);+ const { tools } = await res.json();+ reply({ tools });+ } else if (method === "tools/call") {+ const res = await fetch(`${BASE}/api/ai/proxy`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ sessionKey: SESSION,+ name: params?.name,+ args: params?.arguments ?? {},+ }),+ });+ const body = await res.json();+ reply(body); // { content: [...], isError? } — already MCP-shaped+ } else if (id !== undefined) {+ send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown method ${method}` } });+ }+ } catch (err) {+ fail(err instanceof Error ? err.message : String(err));+ }+}diff --git a/site/src/cut/server/ai/models.ts b/site/src/cut/server/ai/models.tsnew file mode 100644index 00000000..049d1aba--- /dev/null+++ b/site/src/cut/server/ai/models.ts@@ -0,0 +1,18 @@+export interface AiModel {+ id: string;+ label: string;+ provider: "claude" | "codex" | "test";+ hidden?: boolean;+}++/** Claude ids verified against the local CLI; GPT ids are Codex's naming. */+export const AI_MODELS: AiModel[] = [+ { id: "claude-fable-5", label: "Fable 5", provider: "claude" },+ { id: "claude-opus-4-8", label: "Opus 4.8", provider: "claude" },+ { id: "claude-sonnet-5", label: "Sonnet 5", provider: "claude" },+ { id: "claude-haiku-4-5-20251001", label: "Haiku 4.5", provider: "claude" },+ { id: "gpt-5.5", label: "GPT-5.5", provider: "codex" },+ { id: "gpt-5.4", label: "GPT-5.4", provider: "codex" },+ // Hermetic test provider for e2e runs — hidden unless enabled in the UI.+ { id: "cut-test", label: "Test model", provider: "test", hidden: true },+];diff --git a/site/src/cut/server/frames.ts b/site/src/cut/server/frames.tsnew file mode 100644index 00000000..634f992b--- /dev/null+++ b/site/src/cut/server/frames.ts@@ -0,0 +1,109 @@+import { spawn } from "node:child_process";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { mediaPath } from "./projects";++function run(cmd: string, args: string[]): Promise<void> {+ return new Promise((resolve, reject) => {+ const p = spawn(cmd, args);+ let err = "";+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-2000)));+ p.on("error", (e) =>+ reject(+ e.message.includes("ENOENT")+ ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")+ : e+ )+ );+ p.on("close", (code) =>+ code === 0 ? resolve() : reject(new Error(err.split("\n").slice(-3).join("\n")))+ );+ });+}++function probeDims(file: string): Promise<{ width: number; height: number }> {+ return new Promise((resolve) => {+ const p = spawn("ffprobe", [+ "-v", "error",+ "-select_streams", "v:0",+ "-show_entries", "stream=width,height",+ "-of", "csv=p=0",+ file,+ ]);+ let out = "";+ p.stdout.on("data", (d) => (out += d));+ p.on("close", () => {+ const [w, h] = out.trim().split(",").map(Number);+ resolve({ width: w || 1080, height: h || 1920 });+ });+ p.on("error", () => resolve({ width: 1080, height: 1920 }));+ });+}++export interface FreezeFraming {+ fit: "fit" | "fill";+ panX: number;+ panY: number;+}++/**+ * Render a still-video clip from one frame of a project media file+ * (a freeze frame), written into the project's media folder.+ *+ * When `frame` is given the still is composited exactly as the preview shows+ * it — letterboxed (fit) or crop-panned (fill) into the project frame — so+ * the capture is locked to the aspect at capture time. Switching the project+ * aspect later letterboxes the baked still; capture another to re-fit.+ */+export async function makeFreezeFrame(+ projectId: string,+ sourceFile: string,+ srcTime: number,+ duration: number,+ frame?: { w: number; h: number },+ framing?: FreezeFraming+): Promise<{ fileName: string; duration: number; width: number; height: number }> {+ const src = mediaPath(projectId, sourceFile);+ const dur = Math.min(10, Math.max(0.5, duration));+ const stampTime = Math.max(0, srcTime);+ const tmp = await mkdtemp(path.join(os.tmpdir(), "veditor-freeze-"));+ const d = new Date();+ const pad = (n: number) => String(n).padStart(2, "0");+ const fileName = `freeze-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}-${crypto.randomUUID().slice(0, 4)}.mp4`;+ try {+ const png = path.join(tmp, "frame.png");+ await run("ffmpeg", ["-y", "-ss", stampTime.toFixed(3), "-i", src, "-frames:v", "1", png]);++ let vf: string | null = null;+ if (frame) {+ const { w, h } = frame;+ if (framing?.fit === "fill") {+ // Same crop-window math as the preview canvas: pan -1..1 → 0..1.+ const kx = (0.5 + (framing.panX ?? 0) / 2).toFixed(4);+ const ky = (0.5 + (framing.panY ?? 0) / 2).toFixed(4);+ vf = `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}:(iw-ow)*${kx}:(ih-oh)*${ky}`;+ } else {+ vf = `scale=${w}:${h}:force_original_aspect_ratio=decrease,pad=${w}:${h}:(ow-iw)/2:(oh-ih)/2:black`;+ }+ }++ await run("ffmpeg", [+ "-y",+ "-loop", "1",+ "-i", png,+ "-t", dur.toFixed(3),+ "-r", "30",+ ...(vf ? ["-vf", vf] : []),+ "-c:v", "libx264",+ "-preset", "veryfast",+ "-pix_fmt", "yuv420p",+ mediaPath(projectId, fileName),+ ]);+ if (frame) return { fileName, duration: dur, width: frame.w, height: frame.h };+ const dims = await probeDims(png);+ return { fileName, duration: dur, width: dims.width, height: dims.height };+ } finally {+ void rm(tmp, { recursive: true, force: true });+ }+}diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsnew file mode 100644index 00000000..8894c4a0--- /dev/null+++ b/site/src/cut/server/jobs.ts@@ -0,0 +1,287 @@+import { spawn, type ChildProcess } from "node:child_process";+import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { exportsDir, mediaPath, readProject } from "./projects";+import { hasStream, num } from "./util";++export interface ExportSpec {+ projectId: string;+ width: number;+ height: number;+ fps: number;+ crf: number;+ preset: string;+ duration: number;+ clips: {+ file: string;+ in: number;+ out: number;+ muted: boolean;+ /** "fit" letterboxes (default); "fill" covers the frame and crops. */+ fit?: "fit" | "fill";+ panX?: number; // crop-window pan -1..1 (fill mode)+ panY?: number;+ }[];+ audio: {+ file: string;+ in: number;+ out: number;+ start: number;+ volume: number;+ fadeIn?: number;+ fadeOut?: number;+ }[];+ overlays: { file: string; start: number; end: number }[];+}++export interface Job {+ id: string;+ status: "running" | "done" | "error";+ progress: number; // 0..1+ error?: string;+ tmpDir: string;+ outPath: string;+ outName: string;+ proc?: ChildProcess;+ log: string[];+}++// Survives dev-server module reloads.+const g = globalThis as unknown as { __veditorJobs?: Map<string, Job> };+const jobs = (g.__veditorJobs ??= new Map<string, Job>());++export function getJob(id: string) {+ return jobs.get(id);+}++export function cancelJob(id: string) {+ const job = jobs.get(id);+ if (job?.proc && job.status === "running") {+ job.proc.kill("SIGKILL");+ job.status = "error";+ job.error = "Export canceled.";+ }+}++function stamp() {+ const d = new Date();+ const p = (n: number) => String(n).padStart(2, "0");+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;+}++export async function createJob(form: FormData): Promise<Job> {+ const spec = JSON.parse(String(form.get("spec"))) as ExportSpec;+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-"));+ const id = crypto.randomUUID().slice(0, 12);+ const outDir = exportsDir(spec.projectId);+ await mkdir(outDir, { recursive: true });+ // Include the unique job id so two exports in the same second can't collide+ // on the same output path (which would clobber the first render).+ const outName = `export-${stamp()}-${id}.mp4`;+ const job: Job = {+ id,+ status: "running",+ progress: 0,+ tmpDir,+ outPath: path.join(outDir, outName),+ outName,+ log: [],+ };+ jobs.set(id, job);++ try {+ if (!(await readProject(spec.projectId))) throw new Error("Project not found.");+ // Overlay PNGs are rendered in the browser and uploaded with the spec.+ for (const [key, value] of form.entries()) {+ if (value instanceof File && key !== "spec") {+ await writeFile(path.join(tmpDir, path.basename(key)), Buffer.from(await value.arrayBuffer()));+ }+ }+ void runExport(job, spec).catch((err: unknown) => {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ void rm(job.outPath, { force: true }); // no half-written files in exports/+ });+ } catch (err) {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ }+ return job;+}++async function resolveMedia(spec: ExportSpec, file: string) {+ const p = mediaPath(spec.projectId, file);+ const info = await stat(p).catch(() => null);+ if (!info?.isFile()) throw new Error(`Media file missing from project: ${file}`);+ return p;+}++async function runExport(job: Job, spec: ExportSpec) {+ if (spec.clips.length === 0) throw new Error("Nothing to export.");+ const { width: W, height: H, fps } = spec;++ // One ffmpeg input per distinct media file (from the project folder),+ // plus one per uploaded overlay PNG.+ const mediaFiles = [+ ...new Set([...spec.clips, ...spec.audio].map((c) => c.file)),+ ];+ const audioPresence = new Map<string, boolean>();+ const videoPresence = new Map<string, boolean>();+ const inputs: string[] = [];+ const inputIndex = new Map<string, number>();+ // Resolve paths in order first so ffmpeg input indices stay deterministic,+ // then probe every file's streams concurrently.+ const paths = await Promise.all(mediaFiles.map((f) => resolveMedia(spec, f)));+ mediaFiles.forEach((f, i) => {+ inputIndex.set(f, inputs.length / 2);+ inputs.push("-i", paths[i]);+ });+ await Promise.all(+ mediaFiles.map(async (f, i) => {+ audioPresence.set(f, await hasStream(paths[i], "a"));+ // If the video probe itself fails, assume the clip HAS video rather than+ // silently replacing it with black frames — a normal .mp4 must never+ // export as a black screen just because one ffprobe hiccupped.+ let probeFailed = false;+ const hasVideo = await hasStream(paths[i], "v", () => (probeFailed = true));+ videoPresence.set(f, hasVideo || probeFailed);+ })+ );+ for (const o of spec.overlays) {+ inputIndex.set(o.file, inputs.length / 2);+ inputs.push("-i", path.join(job.tmpDir, path.basename(o.file)));+ }++ const filters: string[] = [];++ // Per-clip normalized video + audio segments for concat.+ spec.clips.forEach((c, j) => {+ const idx = inputIndex.get(c.file)!;+ const dur = Math.max(0.1, c.out - c.in);+ if (videoPresence.get(c.file)) {+ const frame =+ c.fit === "fill"+ ? // Cover the frame, then crop; the pan chooses the visible window.+ `scale=${W}:${H}:force_original_aspect_ratio=increase,` ++ `crop=${W}:${H}:(iw-ow)*${num(0.5 + Math.max(-1, Math.min(1, c.panX ?? 0)) / 2)}` ++ `:(ih-oh)*${num(0.5 + Math.max(-1, Math.min(1, c.panY ?? 0)) / 2)}`+ : `scale=${W}:${H}:force_original_aspect_ratio=decrease,` ++ `pad=${W}:${H}:(ow-iw)/2:(oh-ih)/2:color=black`;+ filters.push(+ `[${idx}:v]trim=${num(c.in)}:${num(c.out)},setpts=PTS-STARTPTS,` ++ `fps=${fps},${frame},setsar=1,format=yuv420p[v${j}]`+ );+ } else {+ // No video stream in this file: keep the cut alive with black frames.+ filters.push(+ `color=c=black:s=${W}x${H}:r=${fps},trim=0:${num(dur)},setpts=PTS-STARTPTS,format=yuv420p[v${j}]`+ );+ }+ if (!c.muted && audioPresence.get(c.file)) {+ filters.push(+ `[${idx}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` ++ `apad=whole_dur=${num(dur)},atrim=0:${num(dur)}[a${j}]`+ );+ } else {+ filters.push(+ `anullsrc=r=44100:cl=stereo,atrim=0:${num(dur)},asetpts=PTS-STARTPTS[a${j}]`+ );+ }+ });++ const concatIn = spec.clips.map((_, j) => `[v${j}][a${j}]`).join("");+ filters.push(`${concatIn}concat=n=${spec.clips.length}:v=1:a=1[vcat][acat]`);++ // Burn in text overlays, each windowed to its timeline range.+ let vLabel = "vcat";+ spec.overlays.forEach((o, k) => {+ const idx = inputIndex.get(o.file)!;+ const next = `vov${k}`;+ filters.push(+ `[${vLabel}][${idx}:v]overlay=0:0:enable='between(t,${num(o.start)},${num(o.end)})'[${next}]`+ );+ vLabel = next;+ });++ // Soundtrack clips: trim, gain, shift into place, mix with clip audio.+ const soundLabels: string[] = [];+ spec.audio.forEach((a, k) => {+ const idx = inputIndex.get(a.file)!;+ if (!audioPresence.get(a.file)) return;+ const delayMs = Math.max(0, Math.round(a.start * 1000));+ const len = Math.max(0.1, a.out - a.in);+ const fades: string[] = [];+ if (a.fadeIn && a.fadeIn > 0.01) fades.push(`afade=t=in:st=0:d=${num(a.fadeIn)}`);+ if (a.fadeOut && a.fadeOut > 0.01)+ fades.push(`afade=t=out:st=${num(Math.max(0, len - a.fadeOut))}:d=${num(a.fadeOut)}`);+ filters.push(+ `[${idx}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,` ++ `aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo,` ++ `volume=${num(a.volume)},` ++ (fades.length ? fades.join(",") + "," : "") ++ `adelay=${delayMs}:all=1[snd${k}]`+ );+ soundLabels.push(`snd${k}`);+ });++ let aLabel = "acat";+ if (soundLabels.length > 0) {+ const mixIn = ["acat", ...soundLabels].map((l) => `[${l}]`).join("");+ filters.push(+ `${mixIn}amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`+ );+ aLabel = "amix";+ }++ const args = [+ "-y",+ ...inputs,+ "-filter_complex", filters.join(";"),+ "-map", `[${vLabel}]`,+ "-map", `[${aLabel}]`,+ "-c:v", "libx264",+ "-preset", spec.preset,+ "-crf", String(spec.crf),+ "-profile:v", "high",+ "-pix_fmt", "yuv420p",+ "-color_range", "tv",+ "-colorspace", "bt709",+ "-c:a", "aac",+ "-b:a", "192k",+ "-movflags", "+faststart",+ "-t", num(spec.duration),+ job.outPath,+ ];++ await new Promise<void>((resolve, reject) => {+ const proc = spawn("ffmpeg", args);+ job.proc = proc;+ proc.stderr.on("data", (chunk: Buffer) => {+ const text = chunk.toString();+ job.log.push(text);+ if (job.log.length > 200) job.log.shift();+ const m = /time=(\d+):(\d+):([\d.]+)/.exec(text);+ if (m) {+ const t = Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]);+ job.progress = Math.min(0.99, t / Math.max(0.1, spec.duration));+ }+ });+ proc.on("error", (err) =>+ reject(+ err.message.includes("ENOENT")+ ? new Error("ffmpeg was not found. Install it with: brew install ffmpeg")+ : err+ )+ );+ proc.on("close", (code) => {+ if (code === 0) resolve();+ else if (job.error) reject(new Error(job.error));+ else reject(new Error(`ffmpeg exited with code ${code}.\n${job.log.slice(-8).join("")}`));+ });+ });++ job.progress = 1;+ job.status = "done";+}diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsnew file mode 100644index 00000000..9956ef21--- /dev/null+++ b/site/src/cut/server/library.ts@@ -0,0 +1,166 @@+import { spawn } from "node:child_process";+import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import path from "node:path";+import { mediaPath as projectMediaPath, readProject } from "./projects";+import { exists, uniqueName } from "./util";++/** The shared library: reusable media that lives outside any project. */+export const LIBRARY_ROOT = path.join(process.cwd(), "library");+const LIB_MEDIA = path.join(LIBRARY_ROOT, "media");+const INDEX = path.join(LIBRARY_ROOT, "library.json");++export interface LibraryAsset {+ id: string;+ fileName: string;+ name: string;+ type: "video" | "audio";+ duration: number;+ width?: number;+ height?: number;+ addedAt: number;+}++interface LibraryIndex {+ assets: LibraryAsset[];+}++export function libMediaPath(fileName: string) {+ const safe = path.basename(fileName);+ if (!safe || safe.startsWith(".")) throw new Error("Invalid file name.");+ return path.join(LIB_MEDIA, safe);+}++async function readIndex(): Promise<LibraryIndex> {+ try {+ return JSON.parse(await readFile(INDEX, "utf8")) as LibraryIndex;+ } catch {+ return { assets: [] };+ }+}++async function writeIndex(idx: LibraryIndex) {+ await mkdir(LIB_MEDIA, { recursive: true });+ await writeFile(INDEX, JSON.stringify(idx, null, 2));+}++export async function listLibrary(): Promise<LibraryAsset[]> {+ const idx = await readIndex();+ return idx.assets.sort((a, b) => b.addedAt - a.addedAt);+}++const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;+const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;++function ffprobe(args: string[]): Promise<string> {+ return new Promise((resolve, reject) => {+ const p = spawn("ffprobe", ["-v", "error", ...args]);+ let out = "";+ p.stdout.on("data", (d) => (out += d));+ p.on("error", reject);+ p.on("close", (code) =>+ code === 0 ? resolve(out.trim()) : reject(new Error("Could not read this media file."))+ );+ });+}++async function probe(filePath: string) {+ const duration = parseFloat(+ await ffprobe(["-show_entries", "format=duration", "-of", "csv=p=0", filePath])+ );+ let width: number | undefined;+ let height: number | undefined;+ if (VIDEO_RE.test(filePath)) {+ const dims = await ffprobe([+ "-select_streams", "v:0",+ "-show_entries", "stream=width,height",+ "-of", "csv=p=0",+ filePath,+ ]).catch(() => "");+ const [w, h] = dims.split(",").map(Number);+ if (w && h) {+ width = w;+ height = h;+ }+ }+ return { duration: Number.isFinite(duration) ? duration : 0, width, height };+}++async function freeName(original: string) {+ const base = path.basename(original).replace(/[^\w.\-() ]+/g, "_").slice(-80);+ return uniqueName(base, libMediaPath);+}++function typeOf(fileName: string): "video" | "audio" | null {+ if (VIDEO_RE.test(fileName)) return "video";+ if (AUDIO_RE.test(fileName)) return "audio";+ return null;+}++async function register(fileName: string, name: string): Promise<LibraryAsset> {+ const type = typeOf(fileName);+ if (!type) throw new Error("Unsupported file type.");+ const meta = await probe(libMediaPath(fileName));+ const asset: LibraryAsset = {+ id: crypto.randomUUID().slice(0, 8),+ fileName,+ name,+ type,+ duration: meta.duration,+ ...(meta.width ? { width: meta.width, height: meta.height } : {}),+ addedAt: Date.now(),+ };+ const idx = await readIndex();+ idx.assets.push(asset);+ await writeIndex(idx);+ return asset;+}++/** Upload a file straight into the library. */+export async function addUpload(file: File): Promise<LibraryAsset> {+ if (!typeOf(file.name)) throw new Error("Unsupported file type.");+ await mkdir(LIB_MEDIA, { recursive: true });+ const fileName = await freeName(file.name);+ await writeFile(libMediaPath(fileName), Buffer.from(await file.arrayBuffer()));+ return register(fileName, file.name);+}++/** Copy a project's media file into the library for reuse. */+export async function addFromProject(+ projectId: string,+ fileName: string,+ name: string+): Promise<LibraryAsset> {+ const src = projectMediaPath(projectId, fileName);+ if (!(await exists(src))) throw new Error("Media file not found in project.");+ await mkdir(LIB_MEDIA, { recursive: true });+ const dest = await freeName(fileName);+ await copyFile(src, libMediaPath(dest));+ return register(dest, name || fileName);+}++/** Copy a library asset into a project's media folder. Returns the file name+ * inside the project. */+export async function useInProject(assetId: string, projectId: string): Promise<string> {+ const idx = await readIndex();+ const asset = idx.assets.find((a) => a.id === assetId);+ if (!asset) throw new Error("Library asset not found.");+ if (!(await readProject(projectId))) throw new Error("Project not found.");++ const base = asset.fileName;+ const dest = await uniqueName(base, (n) => projectMediaPath(projectId, n));+ await copyFile(libMediaPath(base), projectMediaPath(projectId, dest));+ return dest;+}++export async function removeAsset(id: string) {+ const idx = await readIndex();+ const asset = idx.assets.find((a) => a.id === id);+ if (!asset) throw new Error("Library asset not found.");+ idx.assets = idx.assets.filter((a) => a.id !== id);+ await writeIndex(idx);+ await rm(libMediaPath(asset.fileName), { force: true });+}++export function getAsset(id: string) {+ return readIndex().then((idx) => idx.assets.find((a) => a.id === id));+}diff --git a/site/src/cut/server/native/cut-stt.swift b/site/src/cut/server/native/cut-stt.swiftnew file mode 100644index 00000000..886810ab--- /dev/null+++ b/site/src/cut/server/native/cut-stt.swift@@ -0,0 +1,83 @@+// cut-stt — on-device speech-to-text with word timestamps.+//+// Wraps Apple's SpeechAnalyzer/SpeechTranscriber (macOS 26+, the engine+// behind Voice Memos transcripts): fully local, no permission needed for+// file input. Compiled on demand by server/transcribe.ts.+//+// usage: cut-stt <audio-file> [locale]+// stdout: {"locale":"en-US","words":[{"t0":0.12,"t1":0.48,"w":"Hello"}]}++import AVFoundation+import Foundation+import Speech++struct Word: Codable {+ let t0: Double+ let t1: Double+ let w: String+}++struct Output: Codable {+ let locale: String+ let words: [Word]+}++func fail(_ message: String) -> Never {+ FileHandle.standardError.write(Data((message + "\n").utf8))+ exit(1)+}++@main+struct Main {+ static func main() async {+ guard CommandLine.arguments.count >= 2 else { fail("usage: cut-stt <audio-file> [locale]") }+ let path = CommandLine.arguments[1]+ let localeId = CommandLine.arguments.count >= 3 ? CommandLine.arguments[2] : "en-US"+ let locale = Locale(identifier: localeId)++ do {+ let transcriber = SpeechTranscriber(+ locale: locale,+ transcriptionOptions: [],+ reportingOptions: [],+ attributeOptions: [.audioTimeRange]+ )++ // First run per locale downloads the on-device model; no-op afterwards.+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {+ try await request.downloadAndInstall()+ }++ let analyzer = SpeechAnalyzer(modules: [transcriber])+ let file = try AVAudioFile(forReading: URL(fileURLWithPath: path))++ let collector = Task {+ var words: [Word] = []+ for try await result in transcriber.results {+ for run in result.text.runs {+ guard let range = run.audioTimeRange else { continue }+ let text = String(result.text[run.range].characters)+ .trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { continue }+ words.append(Word(t0: range.start.seconds, t1: range.end.seconds, w: text))+ }+ }+ return words+ }++ if let last = try await analyzer.analyzeSequence(from: file) {+ try await analyzer.finalizeAndFinish(through: last)+ } else {+ await analyzer.cancelAndFinishNow()+ }++ let words = try await collector.value+ let out = Output(locale: locale.identifier(.bcp47), words: words)+ let data = try JSONEncoder().encode(out)+ FileHandle.standardOutput.write(data)+ FileHandle.standardOutput.write(Data("\n".utf8))+ } catch {+ fail("cut-stt: \(error)")+ }+ }+}diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsnew file mode 100644index 00000000..33f9dd09--- /dev/null+++ b/site/src/cut/server/projects.ts@@ -0,0 +1,136 @@+import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";+import path from "node:path";+import type { ProjectDoc, ProjectSummary } from "@/cut/lib/types";+import { exists, uniqueName } from "./util";++/** All projects live here; each project is one folder holding project.json,+ * its raw media files, and its exports. */+export const PROJECTS_ROOT = path.join(process.cwd(), "projects");++const ID_RE = /^[a-z0-9][a-z0-9-]{2,40}$/;++export function projectDir(id: string) {+ if (!ID_RE.test(id)) throw new Error("Invalid project id.");+ return path.join(PROJECTS_ROOT, id);+}++export const mediaDir = (id: string) => path.join(projectDir(id), "media");+export const exportsDir = (id: string) => path.join(projectDir(id), "exports");++export function mediaPath(id: string, fileName: string) {+ const safe = path.basename(fileName);+ if (!safe || safe.startsWith(".")) throw new Error("Invalid file name.");+ return path.join(mediaDir(id), safe);+}++export function exportPath(id: string, fileName: string) {+ const safe = path.basename(fileName);+ if (!safe || safe.startsWith(".")) throw new Error("Invalid file name.");+ return path.join(exportsDir(id), safe);+}++/** Rendered exports in the project folder, newest first. */+export async function listExports(id: string) {+ const dir = exportsDir(id);+ const names = await readdir(dir).catch(() => [] as string[]);+ const items = await Promise.all(+ names+ .filter((n) => n.endsWith(".mp4"))+ .map(async (n) => {+ const info = await stat(path.join(dir, n)).catch(() => null);+ return info?.isFile() && info.size > 0+ ? { file: n, size: info.size, mtime: info.mtimeMs }+ : null;+ })+ );+ return items+ .filter((x): x is { file: string; size: number; mtime: number } => x !== null)+ .sort((a, b) => b.mtime - a.mtime);+}++const docPath = (id: string) => path.join(projectDir(id), "project.json");++export async function readProject(id: string): Promise<ProjectDoc | null> {+ try {+ return JSON.parse(await readFile(docPath(id), "utf8")) as ProjectDoc;+ } catch {+ return null;+ }+}++export async function writeProject(id: string, doc: ProjectDoc) {+ doc.updatedAt = Date.now();+ await writeFile(docPath(id), JSON.stringify(doc, null, 2));+}++export async function createProject(name: string): Promise<ProjectSummary> {+ const id = crypto.randomUUID().slice(0, 10);+ await mkdir(mediaDir(id), { recursive: true });+ await mkdir(exportsDir(id), { recursive: true });+ const now = Date.now();+ const doc: ProjectDoc = {+ version: 1,+ name: name.trim() || "Untitled",+ createdAt: now,+ updatedAt: now,+ assets: [],+ clips: [],+ audioClips: [],+ overlays: [],+ };+ await writeFile(docPath(id), JSON.stringify(doc, null, 2));+ return summarize(id, doc);+}++export async function deleteProject(id: string) {+ const dir = projectDir(id);+ if (!(await exists(docPath(id)))) throw new Error("Project not found.");+ await rm(dir, { recursive: true, force: true });+}++function summarize(id: string, doc: ProjectDoc): ProjectSummary {+ const duration = doc.clips.reduce((sum, c) => sum + Math.max(0, c.out - c.in), 0);+ // Preview: the first clip's source video, else any video asset.+ const firstClipAsset = doc.clips.length+ ? doc.assets.find((a) => a.id === doc.clips[0].assetId)+ : undefined;+ const previewAsset =+ firstClipAsset ?? doc.assets.find((a) => a.type === "video");+ return {+ id,+ name: doc.name,+ createdAt: doc.createdAt,+ updatedAt: doc.updatedAt,+ duration,+ clipCount: doc.clips.length,+ assetCount: doc.assets.length,+ previewFile: previewAsset?.fileName,+ };+}++export async function listProjects(): Promise<ProjectSummary[]> {+ await mkdir(PROJECTS_ROOT, { recursive: true });+ const entries = await readdir(PROJECTS_ROOT, { withFileTypes: true });+ const names = entries+ .filter((e) => e.isDirectory() && ID_RE.test(e.name))+ .map((e) => e.name);+ // Read every project.json concurrently — listing latency shouldn't grow+ // linearly with the number of projects.+ const docs = await Promise.all(names.map((n) => readProject(n)));+ return names+ .map((n, i) => (docs[i] ? summarize(n, docs[i]!) : null))+ .filter((x): x is ProjectSummary => x !== null)+ .sort((a, b) => b.updatedAt - a.updatedAt);+}++/** Store an uploaded media file in the project folder, deduping the name. */+export async function saveMedia(id: string, file: File): Promise<string> {+ await mkdir(mediaDir(id), { recursive: true });+ const base = path+ .basename(file.name)+ .replace(/[^\w.\-() ]+/g, "_")+ .slice(-80);+ const fileName = await uniqueName(base, (n) => mediaPath(id, n));+ await writeFile(mediaPath(id, fileName), Buffer.from(await file.arrayBuffer()));+ return fileName;+}diff --git a/site/src/cut/server/serveFile.ts b/site/src/cut/server/serveFile.tsnew file mode 100644index 00000000..b7d58f20--- /dev/null+++ b/site/src/cut/server/serveFile.ts@@ -0,0 +1,85 @@+import { createReadStream } from "node:fs";+import { stat } from "node:fs/promises";+import path from "node:path";+import { Readable } from "node:stream";++const TYPES: Record<string, string> = {+ ".mp4": "video/mp4",+ ".m4v": "video/mp4",+ ".mov": "video/quicktime",+ ".webm": "video/webm",+ ".mkv": "video/x-matroska",+ ".mp3": "audio/mpeg",+ ".m4a": "audio/mp4",+ ".aac": "audio/aac",+ ".wav": "audio/wav",+ ".ogg": "audio/ogg",+ ".flac": "audio/flac",+};++export function contentTypeFor(p: string) {+ return TYPES[path.extname(p).toLowerCase()] ?? "application/octet-stream";+}++interface Opts {+ /** Override the MIME type (defaults to the extension's type). */+ contentType?: string;+ /** When set, serve as a download with this filename. */+ downloadName?: string;+}++/**+ * Serve a file from disk with HTTP Range support (206/416), so <video>/<audio>+ * elements and the export download can seek efficiently. Shared by every+ * project/library/export media route.+ */+export async function serveFileRange(+ filePath: string,+ req: Request,+ opts: Opts = {}+): Promise<Response> {+ const info = await stat(filePath).catch(() => null);+ if (!info?.isFile()) return new Response("Not found.", { status: 404 });++ const size = info.size;+ const headers: Record<string, string> = {+ "Content-Type": opts.contentType ?? contentTypeFor(filePath),+ "Accept-Ranges": "bytes",+ "Cache-Control": "no-cache",+ };+ if (opts.downloadName)+ headers["Content-Disposition"] = `attachment; filename="${opts.downloadName}"`;++ const range = req.headers.get("range");+ const m = range ? /bytes=(\d*)-(\d*)/.exec(range) : null;+ if (m && (m[1] || m[2])) {+ let start = m[1] ? parseInt(m[1], 10) : 0;+ let end = m[2] ? parseInt(m[2], 10) : size - 1;+ if (!m[1]) {+ // suffix range: last N bytes+ start = Math.max(0, size - parseInt(m[2], 10));+ end = size - 1;+ }+ end = Math.min(end, size - 1);+ if (start > end || start >= size) {+ return new Response("Range not satisfiable.", {+ status: 416,+ headers: { "Content-Range": `bytes */${size}` },+ });+ }+ const stream = Readable.toWeb(createReadStream(filePath, { start, end })) as ReadableStream;+ return new Response(stream, {+ status: 206,+ headers: {+ ...headers,+ "Content-Length": String(end - start + 1),+ "Content-Range": `bytes ${start}-${end}/${size}`,+ },+ });+ }++ const stream = Readable.toWeb(createReadStream(filePath)) as ReadableStream;+ return new Response(stream, {+ headers: { ...headers, "Content-Length": String(size) },+ });+}diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.tsnew file mode 100644index 00000000..e860ad20--- /dev/null+++ b/site/src/cut/server/transcribe.ts@@ -0,0 +1,248 @@+import { spawn } from "node:child_process";+import { mkdir, mkdtemp, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { mediaPath, readProject } from "./projects";+import { hasStream, num, round } from "./util";++/** The audible slice of the cut, in timeline time (mirrors ExportSpec). */+export interface TranscribeSpec {+ projectId: string;+ duration: number;+ locale?: string;+ clips: { file: string; in: number; out: number; muted: boolean }[];+ audio: { file: string; in: number; out: number; start: number; volume: number }[];+}++interface Word {+ t0: number;+ t1: number;+ w: string;+}++export interface Cue {+ id: string;+ start: number;+ end: number;+ text: string;+ words: Word[];+}++export interface TranscribeJob {+ id: string;+ projectId: string;+ status: "running" | "done" | "error";+ stage: "audio" | "model" | "transcribe";+ error?: string;+ cues?: Cue[];+}++// Survives dev-server module reloads (same trick as export jobs).+const g = globalThis as unknown as { __veditorSttJobs?: Map<string, TranscribeJob> };+const jobs = (g.__veditorSttJobs ??= new Map<string, TranscribeJob>());++export function getTranscribeJob(id: string) {+ return jobs.get(id);+}++function run(cmd: string, args: string[], notFound?: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const p = spawn(cmd, args);+ let out = "";+ let err = "";+ p.stdout.on("data", (d) => (out += d));+ p.stderr.on("data", (d) => (err += d));+ p.on("error", (e) =>+ reject(e.message.includes("ENOENT") && notFound ? new Error(notFound) : e)+ );+ p.on("close", (code) => {+ if (code === 0) resolve(out);+ else reject(new Error(err.trim().split("\n").slice(-4).join("\n") || `${cmd} exited ${code}`));+ });+ });+}++/**+ * The speech engine: Apple's on-device SpeechAnalyzer (macOS 26+), wrapped by+ * a tiny Swift CLI compiled on first use into ~/.cache/cut. Nothing ever+ * leaves the machine.+ */+async function ensureStt(): Promise<string> {+ const src = path.join(process.cwd(), "src", "cut", "server", "native", "cut-stt.swift");+ const bin = path.join(os.homedir(), ".cache", "cut", "cut-stt");+ const [b, s] = await Promise.all([stat(bin).catch(() => null), stat(src)]);+ if (b?.isFile() && b.mtimeMs >= s.mtimeMs) return bin;+ await mkdir(path.dirname(bin), { recursive: true });+ await run(+ "swiftc",+ ["-O", "-parse-as-library", src, "-o", bin],+ "Swift compiler not found. Install the Xcode Command Line Tools: xcode-select --install"+ ).catch((e: Error) => {+ throw new Error(`Could not build the on-device speech engine (needs macOS 26+).\n${e.message}`);+ });+ return bin;+}++/** Group word timings into short caption-sized cues (CapCut/Opus style). */+export function groupWords(words: Word[]): Cue[] {+ const MAX_CHARS = 38;+ const MAX_DUR = 3.5;+ const GAP = 0.6;+ const cues: Cue[] = [];+ let cur: Word[] = [];+ const flush = () => {+ if (cur.length === 0) return;+ const start = round(cur[0].t0);+ cues.push({+ id: crypto.randomUUID().slice(0, 8),+ start,+ end: round(Math.max(cur[cur.length - 1].t1, start + 0.3)),+ text: cur.map((w) => w.w).join(" "),+ words: cur.map((w) => ({ t0: round(w.t0), t1: round(w.t1), w: w.w })),+ });+ cur = [];+ };+ for (const w of words) {+ if (cur.length > 0) {+ const last = cur[cur.length - 1];+ const chars = cur.reduce((n, x) => n + x.w.length + 1, 0) + w.w.length;+ if (+ w.t0 - last.t1 > GAP ||+ chars > MAX_CHARS ||+ w.t1 - cur[0].t0 > MAX_DUR ||+ /[.!?…]$/.test(last.w)+ )+ flush();+ }+ cur.push(w);+ }+ flush();+ return cues;+}++export async function createTranscribeJob(spec: TranscribeSpec): Promise<TranscribeJob> {+ const job: TranscribeJob = {+ id: crypto.randomUUID().slice(0, 12),+ projectId: spec.projectId,+ status: "running",+ stage: "audio",+ };+ jobs.set(job.id, job);+ void runTranscribe(job, spec).catch((err: unknown) => {+ job.status = "error";+ job.error = err instanceof Error ? err.message : String(err);+ });+ return job;+}++async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {+ if (!(await readProject(spec.projectId))) throw new Error("Project not found.");+ if (spec.clips.length === 0) throw new Error("Add a video to the timeline first.");++ const tmpDir = await mkdtemp(path.join(os.tmpdir(), "veditor-stt-"));+ try {+ // Render the cut's audible mix (clip audio + soundtrack, in timeline+ // time) to a 16 kHz mono wav — the same graph the export uses, minus+ // video, so cue times line up with the timeline exactly.+ const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file))];+ const inputs: string[] = [];+ const inputIndex = new Map<string, number>();+ const audible = new Map<string, boolean>();+ const paths = files.map((f) => mediaPath(spec.projectId, f));+ await Promise.all(+ paths.map(async (p, i) => {+ if (!(await stat(p).catch(() => null)))+ throw new Error(`Media file missing: ${files[i]}`);+ })+ );+ files.forEach((f, i) => {+ inputIndex.set(f, inputs.length / 2);+ inputs.push("-i", paths[i]);+ });+ await Promise.all(+ files.map(async (f, i) => audible.set(f, await hasStream(paths[i], "a")))+ );++ const hasSpeechSource =+ spec.clips.some((c) => !c.muted && audible.get(c.file)) ||+ spec.audio.some((a) => audible.get(a.file));+ if (!hasSpeechSource) {+ job.cues = [];+ job.status = "done";+ return;+ }++ const filters: string[] = [];+ spec.clips.forEach((c, j) => {+ const dur = Math.max(0.1, c.out - c.in);+ if (!c.muted && audible.get(c.file)) {+ filters.push(+ `[${inputIndex.get(c.file)}:a]atrim=${num(c.in)}:${num(c.out)},asetpts=PTS-STARTPTS,` ++ `aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono,` ++ `apad=whole_dur=${num(dur)},atrim=0:${num(dur)}[a${j}]`+ );+ } else {+ filters.push(`anullsrc=r=16000:cl=mono,atrim=0:${num(dur)},asetpts=PTS-STARTPTS[a${j}]`);+ }+ });+ filters.push(+ spec.clips.map((_, j) => `[a${j}]`).join("") + `concat=n=${spec.clips.length}:v=0:a=1[acat]`+ );++ const soundLabels: string[] = [];+ spec.audio.forEach((a, k) => {+ if (!audible.get(a.file)) return;+ filters.push(+ `[${inputIndex.get(a.file)}:a]atrim=${num(a.in)}:${num(a.out)},asetpts=PTS-STARTPTS,` ++ `aresample=16000,aformat=sample_fmts=s16:channel_layouts=mono,` ++ `volume=${num(a.volume)},adelay=${Math.max(0, Math.round(a.start * 1000))}:all=1[snd${k}]`+ );+ soundLabels.push(`snd${k}`);+ });+ let aLabel = "acat";+ if (soundLabels.length > 0) {+ filters.push(+ ["acat", ...soundLabels].map((l) => `[${l}]`).join("") ++ `amix=inputs=${soundLabels.length + 1}:duration=first:dropout_transition=0:normalize=0[amix]`+ );+ aLabel = "amix";+ }++ const wav = path.join(tmpDir, "mix.wav");+ await run(+ "ffmpeg",+ [+ "-y",+ ...inputs,+ "-filter_complex", filters.join(";"),+ "-map", `[${aLabel}]`,+ "-ac", "1",+ "-ar", "16000",+ "-t", num(spec.duration),+ wav,+ ],+ "ffmpeg was not found. Install it with: brew install ffmpeg"+ );++ job.stage = "model";+ const bin = await ensureStt();++ job.stage = "transcribe";+ const out = await run(bin, [wav, spec.locale ?? "en-US"]);+ const parsed = JSON.parse(out) as { words: Word[] };+ // Clamp to the cut and drop anything degenerate the model emits.+ const words = parsed.words+ .filter((w) => w.w.trim().length > 0 && w.t1 > w.t0 - 0.001)+ .map((w) => ({+ t0: Math.max(0, Math.min(w.t0, spec.duration)),+ t1: Math.max(0, Math.min(w.t1, spec.duration)),+ w: w.w.trim(),+ }))+ .filter((w) => w.t1 > w.t0);++ job.cues = groupWords(words);+ job.status = "done";+ } finally {+ void rm(tmpDir, { recursive: true, force: true });+ }+}diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.tsnew file mode 100644index 00000000..5aef4894--- /dev/null+++ b/site/src/cut/server/util.ts@@ -0,0 +1,62 @@+import { spawn } from "node:child_process";+import { stat } from "node:fs/promises";+import path from "node:path";++/** Does a file/dir exist? (stat, coerced to a boolean.) */+export async function exists(p: string) {+ return stat(p).then(+ () => true,+ () => false+ );+}++/**+ * First variant of `base` (stem, stem-1, stem-2, …) whose resolved path does+ * not already exist. Used to avoid clobbering when copying/saving media.+ */+export async function uniqueName(base: string, pathFor: (name: string) => string) {+ const ext = path.extname(base);+ const stem = base.slice(0, base.length - ext.length) || "media";+ let name = base;+ for (let n = 1; await exists(pathFor(name)); n++) name = `${stem}-${n}${ext}`;+ return name;+}++/** ffmpeg time/value formatting: millisecond precision, fixed 3 decimals. */+export const num = (n: number) => (Math.round(n * 1000) / 1000).toFixed(3);++/** Round to hundredths (cue/timeline times). */+export const round = (n: number) => Math.round(n * 100) / 100;++/**+ * Whether a media file carries a stream of the given kind ("a" audio /+ * "v" video). Resolves false only when ffprobe reports no such stream; a+ * probe that errors is reported by `onProbeError` so callers can decide+ * whether to assume the stream is present rather than silently dropping it.+ */+export function hasStream(+ file: string,+ kind: "a" | "v",+ onProbeError?: (err: Error) => void+): Promise<boolean> {+ return new Promise((resolve) => {+ const p = spawn("ffprobe", [+ "-v", "error",+ "-select_streams", kind,+ "-show_entries", "stream=codec_type",+ "-of", "csv=p=0",+ file,+ ]);+ let out = "";+ p.stdout.on("data", (d) => (out += d));+ p.on("close", (code) => {+ // A non-zero exit means the probe itself failed, not "no stream".+ if (code !== 0) onProbeError?.(new Error(`ffprobe exited ${code} for ${file}`));+ resolve(out.trim().length > 0);+ });+ p.on("error", (err) => {+ onProbeError?.(err);+ resolve(false);+ });+ });+}