Open source CapCut alternative.
TypeScript
feat(site): share local Cut data across accounts on the Mac [rebuild]
David Lec149eba46c08
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 0d224b3e..e1dc70c0 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -1,6 +1,6 @@# Cut-Cut (publicly "Donkey Cut") is a standalone, free video editor. Its product domain is `donkeycut.com` — a marketing landing at `/` and the editor at `/app/…`; links on retired domains are redirected there at the edge (Cloudflare). The host serves only the client bundle — every page is client-rendered — and the page does all real work against the Cut engine: a local server the Donkey Mac app ships and supervises on the user's own Mac. The engine uses local disk, the app's bundled ffmpeg, on-device speech, and the user's own Claude/Codex CLI logins. Using the app requires a Donkey sign-in, and every engine request carries the signed-in account id: each account's projects and library live in that account's own folder on the Mac, so accounts sharing a machine don't see each other's work. AI generation — images, video, and voiceovers — and the assistant's Gemini models additionally spend credits: the page posts to Donkey's hosted inference routes with the user's session and credits. `donkeycut.com` owns sign-in directly — the auth pages and the Google callback serve on that host — so the session is a plain host-only cookie. Generated media lands back in the project through the engine like any other file; Gemini chat turns, including their editor tool calls, run entirely in the page.+Cut (publicly "Donkey Cut") is a standalone, free video editor. Its product domain is `donkeycut.com` — a marketing landing at `/` and the editor at `/app/…`; links on retired domains are redirected there at the edge (Cloudflare). The host serves only the client bundle — every page is client-rendered — and the page does all real work against the Cut engine: a local server the Donkey Mac app ships and supervises on the user's own Mac. The engine uses local disk, the app's bundled ffmpeg, on-device speech, and the user's own Claude/Codex CLI logins. Using the app requires a Donkey sign-in. Local projects and the library belong to the Mac user, shared by every Donkey account that signs in on that Mac. AI generation — images, video, and voiceovers — and the assistant's Gemini models additionally spend credits: the page posts to Donkey's hosted inference routes with the user's session and credits. `donkeycut.com` owns sign-in directly — the auth pages and the Google callback serve on that host — so the session is a plain host-only cookie. Generated media lands back in the project through the engine like any other file; Gemini chat turns, including their editor tool calls, run entirely in the page.**The engine rule:** the engine API surface (`/api/cut/*`) runs only on the user's Mac. On a hosted deploy every one of those routes answers 404 before any handler runs, so the unauthenticated routes are unreachable there and nothing can execute off-Mac — the engine has no path to Donkey's production models; the page reaches them only through Donkey's own authenticated inference APIs. Don't wrap the engine's routes in the Donkey auth helper, reach for Prisma from them, or bill them against credits; local-only is the design for everything the engine does.@@ -58,11 +58,11 @@ Both renders are subject to the same content boundary as the doc. Captions are bEvery Cut API route is a framework-free handler (web-standard request in, response out) registered once in a route table (`matchCutRoute`), namespaced under `/api/cut/*` to keep it clear of Donkey's own APIs. Both surfaces dispatch through that one table: the packaged engine mounts it directly, and the Next dev server reaches it through a single optional-catch-all route (`/api/cut/[[...slug]]`). They are the same router — static-over-dynamic precedence, HEAD, and 405s behave identically, and there is nowhere for the two to drift. The hosted 404 is applied once, in that shared dispatch.-The shared dispatch also binds each request to the account id the page sends, and every project and library path builds on that account's folder — only the health probe runs outside a scope. A request without an id is refused before any handler runs. The engine has no way to verify the id (it never talks to the hosted backend), so this separates accounts that share a Mac; it is not protection against a hostile local user, who owns the disk anyway. Data written before scoping existed is adopted by the first account that connects.+Local data belongs to the Mac user: every account that signs in on the Mac sees the same projects and library. The page still appends the signed-in account id to engine URLs because engines released before 2026-08 refuse requests without it; the current dispatch ignores it.## The engine-The engine is a single compiled binary built from the site's Cut code and version-locked to the app: the app's dev run script and release packaging build and bundle it automatically (no separate step), and the app stamps its own release version into the engine's environment, so updates ride app releases. The Donkey app spawns it at launch — regardless of sign-in, since Cut is free and standalone — restarts it with backoff if it dies, and stops it on quit. The engine's lifetime is tied to the app process: the engine watches the pid that spawned it and exits when that process is gone, and at launch the app replaces an engine on the port stamped with a different version, so engine fixes always ship with the app update. An engine matching the app's version (another instance) or a developer-run "dev" engine is left alone. Its data lives in the user's Movies folder (`~/Movies/DonkeyCut`), one folder per Donkey account, so projects and exports are visible in Finder and openable by other apps; its logs under the user's Logs folder.+The engine is a single compiled binary built from the site's Cut code and version-locked to the app: the app's dev run script and release packaging build and bundle it automatically (no separate step), and the app stamps its own release version into the engine's environment, so updates ride app releases. The Donkey app spawns it at launch — regardless of sign-in, since Cut is free and standalone — restarts it with backoff if it dies, and stops it on quit. The engine's lifetime is tied to the app process: the engine watches the pid that spawned it and exits when that process is gone, and at launch the app replaces an engine on the port stamped with a different version, so engine fixes always ship with the app update. An engine matching the app's version (another instance) or a developer-run "dev" engine is left alone. Its data lives in the user's Movies folder (`~/Movies/DonkeyCut`), shared by every Donkey account that signs in on the Mac, so projects and exports are visible in Finder and openable by other apps; its logs under the user's Logs folder.Because a GUI-spawned process inherits a bare PATH, the engine rebuilds it: tools shipped beside the engine binary first (they version with the app), then the app's bundled tools (bundled tool always wins), then the user's login-shell PATH and common install dirs. That is how it finds the speech tool, ffmpeg, and the user's `claude` and `codex`.diff --git a/site/src/cut/engine/main.ts b/site/src/cut/engine/main.tsindex d83a3995..04e153a4 100644--- a/site/src/cut/engine/main.ts+++ b/site/src/cut/engine/main.ts@@ -5,8 +5,8 @@* are computed at module load time), then dispatches:** donkey-cut-engine serve the Cut API on 127.0.0.1- * donkey-cut-engine mcp-proxy <base> <key> <user> stdio MCP proxy (spawned- * by the engine itself for AI chats)+ * donkey-cut-engine mcp-proxy <base> <key> stdio MCP proxy (spawned by the+ * engine itself for AI chats)*/process.env.DONKEY_CUT_ENGINE ??= "1";@@ -16,7 +16,7 @@ void (async () => {if (cmd === "mcp-proxy") {const { engineBaseUrl } = await import("./config");const { runMcpProxy } = await import("../server/ai/mcp-proxy-core.mjs");- runMcpProxy(rest[0] ?? engineBaseUrl(), rest[1] ?? "", rest[2] ?? "");+ runMcpProxy(rest[0] ?? engineBaseUrl(), rest[1] ?? "");return;}await import("./serve");diff --git a/site/src/cut/engine/serve.ts b/site/src/cut/engine/serve.tsindex f83f1a3e..0e925478 100644--- a/site/src/cut/engine/serve.ts+++ b/site/src/cut/engine/serve.ts@@ -3,7 +3,7 @@ import { Readable } from "node:stream";import { allowedOrigin, corsHeaders, preflightHeaders } from "../server/cors";import { matchCutRoute, runCutRoute } from "../server/http/routes";-import { migrateCutDataDir } from "../server/migrateDataDir";+import { flattenCutUsers, migrateCutDataDir } from "../server/migrateDataDir";import { ensureToolPath, resolveOnPath } from "../server/tool-path";import { enginePort } from "./config";@@ -75,6 +75,7 @@ function exitWithParent() {async function start() {exitWithParent();migrateCutDataDir();+ flattenCutUsers();await ensureToolPath();// The Agent SDK can't resolve its built-in CLI from inside a compileddiff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.tsindex 56a73763..e2417c7c 100644--- a/site/src/cut/lib/api.ts+++ b/site/src/cut/lib/api.ts@@ -131,10 +131,10 @@ export function engineOrigin(): string {// The signed-in Donkey account, set by RequireSession before the app renders.// Every engine URL carries it (the `u` param) — headers can't, because media-// loads as plain <video>/<img> src — and the engine keeps each account's-// projects and library in that user's own folder. The engine refuses data-// requests without it, so a scope-less URL fails visibly instead of showing-// another account's data.+// loads as plain <video>/<img> src. Local data is shared by every account on+// the Mac, so current engines ignore the param; engines released before+// 2026-08 refuse data requests without it, which is why the page keeps+// sending it.let engineUser: string | null = null;export function setEngineUser(id: string) {diff --git a/site/src/cut/server/ai/mcp-proxy-core.mjs b/site/src/cut/server/ai/mcp-proxy-core.mjsindex a895944f..e6f4a134 100644--- a/site/src/cut/server/ai/mcp-proxy-core.mjs+++ b/site/src/cut/server/ai/mcp-proxy-core.mjs@@ -9,12 +9,7 @@* Two launchers share this core: mcp-proxy.mjs (dev, spawned by file path* with node) and the engine binary's `mcp-proxy` subcommand.*/-export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "", USER = "") {- // Every Cut data route runs inside a user scope keyed by the `u` param; the- // proxy inherits the chatting account's id so its own tools/list and- // tools/call land in that same scope instead of 400ing as out-of-scope.- const scoped = (path) =>- USER ? `${path}${path.includes("?") ? "&" : "?"}u=${encodeURIComponent(USER)}` : path;+export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {let buffer = "";process.stdin.setEncoding("utf8");process.stdin.on("data", (chunk) => {@@ -83,14 +78,14 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "", USER =} else if (method === "tools/list") {// Idempotent: retry so a momentary hiccup can't leave the model with an// empty tool set (which reads to it as "editing tools aren't reachable").- const res = await fetchEngine(`${BASE}${scoped("/api/cut/ai/proxy?type=catalog")}`, undefined, "tools/list", true);+ const res = await fetchEngine(`${BASE}/api/cut/ai/proxy?type=catalog`, undefined, "tools/list", true);const { tools } = await res.json();reply({ tools });} else if (method === "tools/call") {// No retry: the call may already have run on the editor by the time the// response is lost, and re-running a generation tool would double-charge.const res = await fetchEngine(- `${BASE}${scoped("/api/cut/ai/proxy")}`,+ `${BASE}/api/cut/ai/proxy`,{method: "POST",headers: { "Content-Type": "application/json" },diff --git a/site/src/cut/server/ai/mcp-proxy.mjs b/site/src/cut/server/ai/mcp-proxy.mjsindex f463e29b..5c489b87 100644--- a/site/src/cut/server/ai/mcp-proxy.mjs+++ b/site/src/cut/server/ai/mcp-proxy.mjs@@ -4,9 +4,9 @@* the Next dev server. The engine binary launches the same core via its* `mcp-proxy` subcommand instead.*- * usage: node mcp-proxy.mjs <baseUrl> <sessionKey> <userId>+ * usage: node mcp-proxy.mjs <baseUrl> <sessionKey>*/import { runMcpProxy } from "./mcp-proxy-core.mjs";-const [, , BASE, SESSION, USER] = process.argv;-runMcpProxy(BASE, SESSION, USER);+const [, , BASE, SESSION] = process.argv;+runMcpProxy(BASE, SESSION);diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex 1cc43169..7b4786a3 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -14,7 +14,6 @@ import {import { rewriteCaptions, translateCaptions } from "../ai/captions";import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../ai/catalog";-import { currentCutUser } from "../userScope";interface ChatBody {messages: UIMessage[];@@ -30,14 +29,11 @@ const proxyPath = () =>path.join(process.cwd(), "src", "cut", "server", "ai", "mcp-proxy.mjs");/** How to spawn the MCP proxy. The engine binary spawns itself with its- * mcp-proxy subcommand; the dev server spawns node on the proxy source. The- * account id rides along so the proxy's own engine calls carry the `u` scope- * every data route requires — without it tools/list 400s and the model, left- * with no editor tools, narrates tool calls as raw XML instead. */-function mcpCommand(base: string, sessionKey: string, user: string): { command: string; args: string[] } {+ * mcp-proxy subcommand; the dev server spawns node on the proxy source. */+function mcpCommand(base: string, sessionKey: string): { command: string; args: string[] } {return process.env.DONKEY_CUT_ENGINE- ? { command: process.execPath, args: ["mcp-proxy", base, sessionKey, user] }- : { command: process.execPath, args: [proxyPath(), base, sessionKey, user] };+ ? { command: process.execPath, args: ["mcp-proxy", base, sessionKey] }+ : { command: process.execPath, args: [proxyPath(), base, sessionKey] };}function lastUserText(messages: UIMessage[]): string {@@ -70,7 +66,6 @@ async function runClaude(body: ChatBody,base: string,sessionKey: string,- user: string,signal: AbortSignal) {const q = query({@@ -88,7 +83,7 @@ async function runClaude(mcpServers: {cut: {type: "stdio",- ...mcpCommand(base, sessionKey, user),+ ...mcpCommand(base, sessionKey),alwaysLoad: true,},},@@ -166,10 +161,9 @@ async function runCodex(body: ChatBody,base: string,sessionKey: string,- user: string,signal: AbortSignal) {- const mcp = mcpCommand(base, sessionKey, user);+ const mcp = mcpCommand(base, sessionKey);const session = body.providerSession;const args = ["exec"];if (session) args.push("resume", session);@@ -394,7 +388,6 @@ export const aiApi = {async chat(req: Request) {const body = (await req.json()) as ChatBody;const base = new URL(req.url).origin;- const user = currentCutUser();const sessionKey = crypto.randomUUID();const userText = lastUserText(body.messages);const attachments = lastUserAttachments(body.messages);@@ -410,11 +403,11 @@ export const aiApi = {emit({ type: "data-session", data: { sessionKey }, transient: true });try {if (body.model.startsWith("claude")) {- await runClaude(emit, prompt, body, base, sessionKey, user, req.signal);+ 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, user, req.signal);+ await runCodex(emit, prompt, body, base, sessionKey, req.signal);}} catch (err) {emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });diff --git a/site/src/cut/server/http/next.ts b/site/src/cut/server/http/next.tsindex c5d5d2d9..438e0856 100644--- a/site/src/cut/server/http/next.ts+++ b/site/src/cut/server/http/next.ts@@ -1,7 +1,15 @@import { hostedApiBlock } from "../local-only";+import { flattenCutUsers } from "../migrateDataDir";import { ensureToolPath } from "../tool-path";import { matchCutRoute, runCutRoute } from "./routes";+let flattened = false;+function flattenOnce() {+ if (flattened) return;+ flattened = true;+ flattenCutUsers();+}+/*** The Cut API surface as a Next route handler. A single optional-catch-all route* (src/app/api/cut/[[...slug]]/route.ts) delegates here, so the Next dev server@@ -14,8 +22,10 @@ export async function cutCatchAll(req: Request): Promise<Response> {if (blocked) return blocked;// The dev server spawns tools (yt-dlp, ffmpeg, …) in-process, so it needs- // the same widened PATH the packaged engine builds at startup.+ // the same widened PATH the packaged engine builds at startup, and it runs+ // the same users/-dir flatten the engine runs before serving data routes.await ensureToolPath();+ flattenOnce();const { pathname } = new URL(req.url);const match = matchCutRoute(req.method, pathname);diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.tsindex 850ec539..accdb817 100644--- a/site/src/cut/server/http/routes.ts+++ b/site/src/cut/server/http/routes.ts@@ -1,4 +1,3 @@-import { isValidCutUser, runWithCutUser } from "../userScope";import { matchRouteTable } from "./match";import { aiApi } from "./ai";import { engineApi } from "./engine";@@ -14,9 +13,6 @@ interface CutRoute {method: "GET" | "POST" | "PUT" | "DELETE";path: string; // ":name" segments bind paramshandler: TableHandler;- /** Health is the one route outside a user scope: probes and the app's- * supervisor hit it with no session in hand. */- scoped?: false;}/**@@ -25,7 +21,7 @@ interface CutRoute {* catch-all route and the packaged engine — so the two surfaces cannot drift.*/export const CUT_ROUTES: CutRoute[] = [- { method: "GET", path: "/api/cut/engine/health", handler: () => engineApi.health(), scoped: false },+ { method: "GET", path: "/api/cut/engine/health", handler: () => engineApi.health() },{ method: "GET", path: "/api/cut/projects", handler: () => projectsApi.list() },{ method: "POST", path: "/api/cut/projects", handler: (req) => projectsApi.create(req) },@@ -98,29 +94,18 @@ export const CUT_ROUTES: CutRoute[] = [];export type RouteMatch =- | { handler: TableHandler; params: Record<string, string>; head: boolean; scoped: boolean }+ | { handler: TableHandler; params: Record<string, string>; head: boolean }| { methodNotAllowed: string[] };-/**- * Run a matched route inside the requesting user's data scope. The page- * appends the signed-in account id to every engine URL (api.ts); binding it- * here — the one dispatch both mounts share — means every handler, and every- * path built during it, is per-user by construction. A request without a- * valid id never reaches a handler.- */+/** Dispatch a matched route. The page still appends the signed-in account id+ * (`u`) to engine URLs because engines released before 2026-08 refuse requests+ * without it; this dispatch ignores it — local data belongs to the Mac user,+ * whichever Donkey account is signed in. */export async function runCutRoute(req: Request,- match: { handler: TableHandler; params: Record<string, string>; scoped: boolean }+ match: { handler: TableHandler; params: Record<string, string> }): Promise<Response> {- if (!match.scoped) return match.handler(req, match.params);- const user = new URL(req.url).searchParams.get("u");- if (!user || !isValidCutUser(user)) {- return new Response(- JSON.stringify({ error: "This page is out of date with the Donkey app — reload the tab." }),- { status: 400, headers: { "Content-Type": "application/json" } }- );- }- return runWithCutUser(user, () => match.handler(req, match.params));+ return match.handler(req, match.params);}/**@@ -136,6 +121,5 @@ export function matchCutRoute(method: string, pathname: string): RouteMatch | nuhandler: match.route.handler,params: match.params,head: match.head,- scoped: match.route.scoped !== false,};}diff --git a/site/src/cut/server/jobs.ts b/site/src/cut/server/jobs.tsindex 93c0a2eb..46b6eb01 100644--- a/site/src/cut/server/jobs.ts+++ b/site/src/cut/server/jobs.ts@@ -6,15 +6,11 @@ import { assertLocalRuntime } from "./local-only";import { createJobRegistry } from "./jobRegistry";import { runExport, type ExportSpec } from "./exportPipeline";import { exportsDir, mediaPath, projectDir, readProject } from "./projects";-import { currentCutUser } from "./userScope";export type { ExportSpec } from "./exportPipeline";export interface Job {id: string;- /** The Donkey account that started the job. The cross-project feed is scoped- * to it, so accounts sharing a Mac never see each other's exports. */- user: string;projectId: string;/** Shown in the exports dock; the engine assigns it from the project doc. */projectName: string;@@ -104,13 +100,11 @@ function jobView(j: Job) {};}-/** Every export job for the requesting account, across all its projects — the- * source of truth the app-wide exports dock reflects, so it shows the same set- * in every tab. Scoped to the account so a shared Mac never crosses feeds. */+/** Every export job across all projects — the source of truth the app-wide+ * exports dock reflects, so it shows the same set in every tab. */export function listAllJobs() {- const user = currentCutUser();return [...jobs.values()]- .filter((j) => j.target !== "preview" && j.user === user)+ .filter((j) => j.target !== "preview").sort((a, b) => a.createdAt - b.createdAt).map(jobView);}@@ -170,7 +164,6 @@ export async function createJob(form: FormData): Promise<Job> {assertLocalRuntime();const spec = JSON.parse(String(form.get("spec"))) as ExportSpec;const id = crypto.randomUUID().slice(0, 12);- const user = currentCutUser();const preview = spec.target === "preview";// Previews are best-effort hover proxies: they take a free slot or bow out,@@ -180,7 +173,6 @@ export async function createJob(form: FormData): Promise<Job> {if (preview && runningCount() >= MAX_RUNNING) {const job: Job = {id,- user,projectId: spec.projectId,projectName: "",target: "preview",@@ -200,7 +192,6 @@ export async function createJob(form: FormData): Promise<Job> {const job: Job = {id,- user,projectId: spec.projectId,projectName: "",target: preview ? "preview" : "export",diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 0f32f7b1..50fc70c2 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -1,13 +1,14 @@import { spawn } from "node:child_process";import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";import path from "node:path";+import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";import { mediaPath as projectMediaPath, readProject } from "./projects";-import { cutUserRoot } from "./userScope";import { exists, uniqueName, writeJsonAtomic } from "./util";-/** The user's library: reusable media that lives outside any project. */-const libraryRoot = () => path.join(cutUserRoot(), "library");+/** The Mac's library: reusable media that lives outside any project, shared by+ * every account that signs in on this Mac. */+const libraryRoot = () => path.join(cutDataRoot(), "library");const libMedia = () => path.join(libraryRoot(), "media");const indexPath = () => path.join(libraryRoot(), "library.json");diff --git a/site/src/cut/server/migrateDataDir.ts b/site/src/cut/server/migrateDataDir.tsindex 4dfa0788..12cf8195 100644--- a/site/src/cut/server/migrateDataDir.ts+++ b/site/src/cut/server/migrateDataDir.ts@@ -2,6 +2,8 @@ import fs from "node:fs";import os from "node:os";import path from "node:path";+import { cutDataRoot } from "./dataDir";+/*** One-time launch migration (shipped 2026-08-04): the Cut data root moved from* ~/Library/Application Support/DonkeyCut to ~/Movies/DonkeyCut. The engine@@ -40,3 +42,161 @@ export function migrateCutDataDir(): void {// Leftover cleanup only; the engine runs fine with the folder still there.}}++/**+ * One-time launch migration (shipped 2026-08-07): local Cut data belongs to the+ * Mac user, so the per-account users/<id>/ layer is gone — projects/ and+ * library/ sit directly under the data root. This folds every account dir into+ * the root: project folders move over (a name collision gains a -2, -3, …+ * suffix), folder and library indexes merge, and library media files are+ * copied in with the same suffixing, their index entries re-pointed, before+ * the source dir is removed. The most recently used account merges first, so+ * its names stay unsuffixed. Both mounts run it before serving data routes.+ *+ * TODO: delete this function and its callers after 2026-10-06 — by then+ * auto-updating installs have migrated.+ */+export function flattenCutUsers(): void {+ const root = cutDataRoot();+ const usersDir = path.join(root, "users");+ if (!fs.existsSync(usersDir)) return;+ try {+ const accountDirs = fs+ .readdirSync(usersDir, { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => path.join(usersDir, e.name))+ .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);+ for (const dir of accountDirs) {+ mergeProjects(path.join(dir, "projects"), path.join(root, "projects"));+ mergeLibrary(path.join(dir, "library"), path.join(root, "library"));+ removeIfEmpty(dir);+ }+ removeIfEmpty(usersDir);+ if (!fs.existsSync(usersDir)) console.log(`flattened cut user data into ${root}`);+ } catch (err) {+ console.error(+ `cut user-dir flatten failed, keeping ${usersDir}: ${err instanceof Error ? err.message : String(err)}`+ );+ }+}++/** A directory name not yet taken in `dest`: the name itself, else -2, -3, … */+function freeDirName(dest: string, name: string): string {+ if (!fs.existsSync(path.join(dest, name))) return name;+ for (let n = 2; ; n++) {+ const candidate = `${name}-${n}`;+ if (!fs.existsSync(path.join(dest, candidate))) return candidate;+ }+}++/** A file name not yet taken in `dest`, suffixing before the extension. */+function freeFileName(dest: string, name: string): string {+ if (!fs.existsSync(path.join(dest, name))) return name;+ const ext = path.extname(name);+ const stem = name.slice(0, name.length - ext.length);+ for (let n = 2; ; n++) {+ const candidate = `${stem}-${n}${ext}`;+ if (!fs.existsSync(path.join(dest, candidate))) return candidate;+ }+}++function readJson<T>(file: string): T | null {+ try {+ return JSON.parse(fs.readFileSync(file, "utf8")) as T;+ } catch {+ return null;+ }+}++/** Remove a directory that holds nothing (Finder's .DS_Store included). */+function removeIfEmpty(dir: string): void {+ if (!fs.existsSync(dir)) return;+ const entries = fs.readdirSync(dir);+ if (entries.length === 1 && entries[0] === ".DS_Store") {+ fs.rmSync(path.join(dir, ".DS_Store"), { force: true });+ }+ if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);+}++interface FolderEntry {+ id: string;+}++function mergeProjects(src: string, dest: string): void {+ if (!fs.existsSync(src)) return;+ fs.mkdirSync(dest, { recursive: true });+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {+ const from = path.join(src, entry.name);+ if (entry.isDirectory()) {+ fs.renameSync(from, path.join(dest, freeDirName(dest, entry.name)));+ } else if (entry.name === "folders.json") {+ const ours = readJson<{ folders?: FolderEntry[] }>(from)?.folders ?? [];+ const destFile = path.join(dest, "folders.json");+ const merged = readJson<{ folders?: FolderEntry[] }>(destFile)?.folders ?? [];+ const known = new Set(merged.map((f) => f.id));+ for (const f of ours) if (!known.has(f.id)) merged.push(f);+ fs.writeFileSync(destFile, JSON.stringify({ folders: merged }));+ fs.rmSync(from, { force: true });+ } else if (entry.name === "folders.json.bak" || entry.name === ".DS_Store") {+ fs.rmSync(from, { force: true });+ }+ }+ removeIfEmpty(src);+}++interface LibraryIndexFile {+ assets?: { fileName: string; folderId?: string | null }[];+ folders?: FolderEntry[];+ templates?: { media?: { fileName: string }[] }[];+}++function mergeLibrary(src: string, dest: string): void {+ if (!fs.existsSync(src)) return;+ if (!fs.existsSync(dest)) {+ fs.renameSync(src, dest);+ return;+ }+ // Read the account's index up front — library.json, then its .bak mirror.+ // An index file that exists but is unreadable in both copies aborts this+ // account's merge with everything left in place: merging the media without+ // it would strand every asset, and deleting it would destroy the one+ // recoverable record of the account's library.+ const srcIndexFile = path.join(src, "library.json");+ const srcIndex =+ readJson<LibraryIndexFile>(srcIndexFile) ?? readJson<LibraryIndexFile>(`${srcIndexFile}.bak`);+ if (srcIndex === null && fs.existsSync(srcIndexFile)) {+ console.error(`keeping ${src}: library.json and its backup are both unreadable`);+ return;+ }+ const index = srcIndex ?? { assets: [] };+ // Copy media in, then commit the merged index, then remove the source dir.+ // The copies keep every step re-runnable: a crash anywhere leaves at worst+ // duplicate files or duplicate entries to clean up by hand — an index entry+ // can never end up pointing at another account's file.+ const renamed = new Map<string, string>();+ const srcMedia = path.join(src, "media");+ const destMedia = path.join(dest, "media");+ if (fs.existsSync(srcMedia)) {+ fs.mkdirSync(destMedia, { recursive: true });+ for (const name of fs.readdirSync(srcMedia)) {+ if (name === ".DS_Store") continue;+ const to = freeFileName(destMedia, name);+ fs.copyFileSync(path.join(srcMedia, name), path.join(destMedia, to));+ if (to !== name) renamed.set(name, to);+ }+ }+ for (const a of index.assets ?? []) a.fileName = renamed.get(a.fileName) ?? a.fileName;+ for (const t of index.templates ?? [])+ for (const m of t.media ?? []) m.fileName = renamed.get(m.fileName) ?? m.fileName;+ const destIndexFile = path.join(dest, "library.json");+ const destIndex = readJson<LibraryIndexFile>(destIndexFile) ?? { assets: [] };+ destIndex.assets = [...(destIndex.assets ?? []), ...(index.assets ?? [])];+ const known = new Set((destIndex.folders ?? []).map((f) => f.id));+ destIndex.folders = [+ ...(destIndex.folders ?? []),+ ...(index.folders ?? []).filter((f) => !known.has(f.id)),+ ];+ destIndex.templates = [...(destIndex.templates ?? []), ...(index.templates ?? [])];+ fs.writeFileSync(destIndexFile, JSON.stringify(destIndex));+ fs.rmSync(src, { recursive: true, force: true });+}diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.tsindex c935bab0..b6c12d39 100644--- a/site/src/cut/server/projects.ts+++ b/site/src/cut/server/projects.ts@@ -1,13 +1,14 @@import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";+import { cutDataRoot } from "./dataDir";import { assertLocalRuntime } from "./local-only";-import { cutUserRoot } from "./userScope";import { exists, uniqueName, writeJsonAtomic } from "./util";-/** The requesting user's projects live here; each project is one folder- * holding project.json, its raw media files, and its exports. */-const projectsRoot = () => path.join(cutUserRoot(), "projects");+/** Projects live directly under the data root, shared by every account that+ * signs in on this Mac; each project is one folder holding project.json, its+ * raw media files, and its exports. */+const projectsRoot = () => path.join(cutDataRoot(), "projects");// Project folders are grouping metadata only; it lives beside the project dirs// as a plain file, so the project-dir scan (which requires ID_RE) skips it.const foldersIndex = () => path.join(projectsRoot(), "folders.json");diff --git a/site/src/cut/server/userScope.ts b/site/src/cut/server/userScope.tsdeleted file mode 100644index 4d23d58b..00000000--- a/site/src/cut/server/userScope.ts+++ /dev/null@@ -1,38 +0,0 @@-import { AsyncLocalStorage } from "node:async_hooks";-import path from "node:path";-import { cutDataRoot } from "./dataDir";--/**- * Every data route runs inside a signed-in user's scope: the page sends the- * Donkey account id with each engine request (the `u` query param api.ts- * appends), the dispatcher binds it here, and all project/library paths hang- * off users/<id> under the data root. The engine cannot verify the id — it- * never talks to the hosted backend — so this is per-account separation on a- * shared Mac, not protection against a hostile local user.- */-const scope = new AsyncLocalStorage<string>();--// Donkey account ids are URL-safe tokens; anything else is refused before it-// can become a filesystem path.-const USER_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;--export const isValidCutUser = (id: string) => USER_ID_RE.test(id);--export function runWithCutUser<T>(id: string, fn: () => T): T {- if (!isValidCutUser(id)) throw new Error("Invalid user id.");- return scope.run(id, fn);-}--/** The current request's per-user data root. Path helpers build on this, so a- * path outside a user scope is impossible by construction. */-export function cutUserRoot(): string {- return path.join(cutDataRoot(), "users", currentCutUser());-}--/** The account id bound to the current request. The AI chat threads it into the- * spawned MCP proxy so the proxy's own engine calls stay in the same scope. */-export function currentCutUser(): string {- const id = scope.getStore();- if (!id) throw new Error("No user scope bound to this request.");- return id;-}